blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
da908f4f0dc1ba4da105d176bbb4a2a7c5573f63 | Prostotakvishlo/Test | /88887.py | 345 | 3.765625 | 4 | import turtle
turtle.shape('turtle')
def koch(order, size):
if order == 0:
turtle.forward(size)
else:
koch(order-1, size/3)
turtle.left(60)
koch(order-1, size/3)
turtle.right(120)
koch(order-1, size/3)
turtle.left(60)
koch(order-1, size/3)
koch(4, 500)
turtle.mainloop()
|
4407e6b40cda3682f22eb67af702491999031c5f | lxy-kyb/algorithm_python | /AlgorithmPython/AlgorithmPython/Data Structure/BinarySearchTree.py | 4,257 | 3.96875 | 4 |
class TreeNode:
def __init__(self, data, left, right, parent):
self.data = data
self.left = left
self.right = right
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def preOrder(self, node):
if node is not None:
print node.data,
self.preOrder(node.left)
self.preOrder(node.right)
def inOrder(self, node):
if node is not None:
self.inOrder(node.left)
print node.data,
self.inOrder(node.right)
def postOrder(self, node):
if node is not None:
self.postOrder(node.left)
self.postOrder(node.right)
print node.data,
def Tree_Search(self, node, k):
if node is None or node.data == k:
return node
if k < node.data:
return self.Tree_Search(node.left, k)
else:
return self.Tree_Search(node.right, k)
def Iterative_Tree_Search(selft, node, k):
while node is not none and node.data != k:
if k < node.data:
node = node.left
else:
node = node.right
return node
def Tree_Minimun(self, node):
while node is not None:
node = node.left
return node
def Tree_Maximum(self, node):
while node is not None:
node = node.right
return node
#The successor of T is the smallest number bigger than T
def Tree_Successor(self, node):
if node.right is not None:
return self.Tree_Minimun(node.right)
p = node.parent
while p is not None and node == p.right:
node = p
p = node.parent
return p
#The Predecessor of T is the biggest number smaller than T
def Tree_Predecessor(self, node):
if node.left is not None:
return self.Tree_Maximum(node.left)
p = node.parent
while p is not None and node == p.left:
node = p
p = node.parent
return p
def Tree_Insert(self, data):
node = self.root
TmpNode = node
while node is not None:
TmpNode = node
if node.data > data:
node = node.left
else:
node = node.right
NewNode = TreeNode(data, None, None, None)
NewNode.parent = TmpNode
if TmpNode is None:
self.root = NewNode
elif TmpNode.data > data:
TmpNode.left = NewNode
else:
TmpNode.right = NewNode
#relace the substree rooted at node u with the subtree root at node v
#if u.parent is None u is the root so v is the new root
def Transplant(self, u, v):
if u.parent is None:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
if v is not None:
v.parent = u.parent
#nodeSuc is the Successor of z if z has right child the successor must be the node in the subtree
#if the nodeSuc is z.right replace z with nodSuc and let z.left to be nodeSuc.left
#Otherwise, repace nodeSuc while nodeSuc.right and let z.right to be nodeSuc.right Then repace z with nodSuc
def Tree_Delete(self, z):
if z.left is None:
self.Transplant(z, z.right)
elif z.right is None:
self.Transplant(z, z.left)
else:
nodeSuc = self.Tree_Minimun(z.right)
if nodeSuc.parent != z:
self.Transplant(nodeSuc, nodeSuc.right)
nodeSuc.right = z.right
nodeSuc.right.parent = nodeSuc
self.Transplant(z, nodeSuc)
nodeSuc.left = z.left
nodeSuc.left.parent = nodeSuc
btree = BinarySearchTree()
btree.Tree_Insert(5)
btree.Tree_Insert(10)
btree.Tree_Insert(12)
btree.Tree_Insert(4)
btree.Tree_Delete(btree.Tree_Search(btree.root, 10))
print btree.Tree_Search(btree.root, 4), btree.Tree_Search(btree.root, 10)
btree.preOrder(btree.root)
print
btree.inOrder(btree.root)
print
btree.postOrder(btree.root)
print
|
932fe11333cd1b1b7fb1c4d0f91c58acd8d5f411 | DyllanSowersTR/IT310 | /Project 1/partA.py | 1,745 | 4.0625 | 4 | import random
#Got some help from StackOverflow, but created it into my own code with additional code for personal touch as well.
#https://stackoverflow.com/questions/46709794/birthday-paradox-python-incorrect-probability-output
#Definition for the birthday paradox listing
def BirthdayParadox():
#Create empty list
birthdayList = []
#Insert random integers from 1 to 365 (days in the year) with a total of 25 integers or (people)
#I chose 25 people because it is more than 23.
birthdayList = [random.randint(1, 365) for i in range(25)]
#Sort the random int list from smallest to largest
birthdayList.sort()
#Create a check that runs through the list to find matches.
#If true, there is a match and will add to total number of matches in my pring statements further down.
for a in range(len(birthdayList)):
while a < (len(birthdayList))-1:
if birthdayList [a] == birthdayList [a+1]:
#Printed list for testing
#print(birthdayList[a])
return True
a = a + 1
return False
#Create a counter to select your total amount of times to run through the list
count = 0
rangeNum = 1000
for i in range (rangeNum):
if BirthdayParadox() == True:
count = count + 1
#I created 2 print statements for grammar checks since it bothered me when there was only one match
if count == 1:
print('Out of 25 people... in', rangeNum, 'full list checks, there was', count, 'match for 2 people with the same birthdays.')
else:
print('Out of 25 people... in', rangeNum, 'full list checks, there were', count, 'matches for 2 people with the same birthdays.')
#Call the defintion to run the code
BirthdayParadox() |
1fcc669c4573304e3921c6ae00882d67c6d96ffd | jgk0/Python-challenges | /lab10/lab10.py | 2,729 | 3.625 | 4 | ###################################################
# MC102 - Algoritmos e Programação de Computadores
# Laboratório 10 - Caça-Palavras 2.0
# Nome:
# RA:
###################################################
"""
Esta função recebe como parâmetro uma matriz, uma posição inicial na
matriz determinada pelos parâmetros linha e coluna e uma palavra que
deve ser buscada na horizontal (da esquerda para direita) a partir da
posição inicial. Caso a palavra seja encontrada a partir da posição
inicial a função deve transformar todas as letras da palavra em
maiúsculas e retornar o valor True. Caso contrário, a função de
retornar o valor False.
"""
def horizontal(matriz, linha, coluna, palavra):
"""
Esta função recebe como parâmetro uma matriz, uma posição inicial na
matriz determinada pelos parâmetros linha e coluna e uma palavra que
deve ser buscada na vertical (de cima para baixo) a partir da posição
inicial. Caso a palavra seja encontrada a partir da posição inicial a
função deve transformar todas as letras da palavra em maiúsculas e
retornar o valor True. Caso contrário, a função de retornar o valor
False.
"""
def vertical(matriz, linha, coluna, palavra):
"""
Esta função recebe como parâmetro uma matriz, uma posição inicial na
matriz determinada pelos parâmetros linha e coluna e uma palavra que
deve ser buscada na diagonal (no sentido inferior direito) a partir da
posição inicial. Caso a palavra seja encontrada a partir da posição
inicial a função deve transformar todas as letras da palavra em
maiúsculas e retornar o valor True. Caso contrário, a função de
retornar o valor False.
"""
def diagonal1(matriz, linha, coluna, palavra):
"""
Esta função recebe como parâmetro uma matriz, uma posição inicial
na matriz determinada pelos parâmetros linha e coluna e uma palavra
que deve ser buscada na diagonal (sentido superior direito) a partir
da posição inicial. Caso a palavra seja encontrada a partir da
posição inicial a função deve transformar todas as letras da palavra
em maiúsculas e retornar o valor True. Caso contrário, a função de
retornar o valor False.
"""
def diagonal2(matriz, linha, coluna, palavra):
# Leitura da matriz
matriz = []
linha = input()
# Dica: use linha.isdigit(), linha.split() e matriz.append()
# para processar a entrada e armazenar a matriz de caracteeres
# Leitura e processamento das palavras
print("-" * 40)
print("Lista de Palavras")
print("-" * 40)
print("Palavra:", palavra)
print("Ocorrencias:", ocorrencias)
print("-" * 40)
# Impressão da matriz
for linha in matriz:
print(" ".join(linha)) |
5ba26eceae96d3a35524201f09891f33f2383e12 | CookyChou/leetcode | /first/play4.py | 328 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/4/4 16:38
# @Author : bgzhou
class Solution:
def rotate(self, nums, k: int) -> None:
nums[:] = nums[-(k % len(nums)):] + nums[:-(k % len(nums))]
if __name__ == '__main__':
s = Solution()
list1 = [1, 2]
s.rotate(list1, 3)
print(list1) |
bc41105ba3c2686bd58918af46665276103dff2c | RobyOneCenobi/The-Turtle-fun | /fabric.py | 1,559 | 3.984375 | 4 | import turtle
import random
""" ustawienia początkowe i rysowanie ramki """
pen = turtle.Turtle()
pen.pensize(1)
pen.pencolor('blue')
pen.penup()
pen.goto(-220, 220)
pen.pendown()
pen.forward(400)
pen.right(90)
pen.forward(400)
pen.right(90)
pen.forward(400)
pen.right(90)
pen.forward(400)
pen.penup()
pen.goto(-200, 200)
pen.pendown()
pen.right(90)
""" losowanie czy kawadrat bedzie pusty czy pełny """
def sygnal():
sygnal = random.randint(1, 2)
return sygnal
""" rysowanie kwadratu pustego """
def kwadrat_pusty():
pen.pendown()
pen.left(180)
for i in range(0, 3):
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.left(90)
return kwadrat_pusty
""" rysowanie kwadratu pełnego """
def kwadrat_pelny():
pen.down()
pen.left(180)
pen.begin_fill()
for i in range(0, 3):
pen.forward(20)
pen.right(90)
pen.forward(20)
pen.end_fill()
pen.left(90)
return kwadrat_pelny
""" rysowanie kwadratu pełnego lub pustego """
def rysuj_kwadrat(sygnal):
if sygnal == 1:
kwadrat_pelny()
pen.penup()
pen.forward(20)
else:
kwadrat_pusty()
pen.penup()
pen.forward(20)
""" przesuwanie sie do kolejnej linii """
def w_dol(ile_razy):
pen.goto(-200, 200 - 20*ile_razy)
return w_dol
""" rysowanie wzoru na formatce 20x20 """
ile_razy = 1
while ile_razy <=20:
for w in range(0, 20):
sygnal( )
s = sygnal( )
rysuj_kwadrat(s)
w_dol(ile_razy)
ile_razy += 1
turtle.mainloop()
|
44471df9935c1a87147214d0650e534373ed391d | arun-me/copy | /100DaysOfPython/test_bmi.py | 424 | 4.375 | 4 | #bmi calculator
height = float(input('enter your height (cms)\n'))
weight = float( input('enter your weight (kg)\n'))
bmi = round(weight/(height/100)**2,2)
if bmi < 18.5:
bmi_type="Under Weight"
elif bmi < 25 :
bmi_type="Normal"
elif bmi < 30 :
bmi_type="Over Weight"
elif bmi< 35 :
bmi_type="Obesity"
else:
bmi_type="Clinical Obesity"
print(f'yout bmi is {bmi}, which is {bmi_type}')
|
77dfb1b8f1d81f1f97efecb7729ec6c420e49f19 | bencebalint/flask-exmple-4-ITBraniacs | /school/element/teacher.py | 591 | 3.84375 | 4 | from typing import List
from element.person import Person
class Teacher(Person):
def __init__(self, name: str, address: str):
super().__init__(name, address)
self.__courses: List[str] = []
def add_course(self, course: str) -> bool:
if len(self.__courses) < 3:
self.__courses.append(course)
return True
return False
def __str__(self):
data = ""
for d in self.__courses:
data += str(d)
return "Teacher[name: " + self.name + ", address: " + self.address + ", courses: " + data + "]"
|
4f875dec97a13dffaee8f8a74aaead27c146ce7b | bencebalint/flask-exmple-4-ITBraniacs | /school/element/student.py | 881 | 3.5625 | 4 | from typing import List
from element.person import Person
class Student(Person):
def __init__(self, name: str, address: str):
super().__init__(name, address)
self.__courses: List[str] = []
self.__grades: List[int] = []
def __str__(self) -> str:
datas = []
for i in range(len(self.__courses)):
datas.append(str(dict(course=self.__courses[i], grade=self.__grades[i])))
return "Student[name: " + self.name + ", address: " + self.address + ', courses_grades: ' + str(datas) + ']'
def add_course_grade(self, course: str, grade: int):
self.__courses.append(course)
self.__grades.append(grade)
def get_average(self) -> float:
s = 0
for i in self.__grades:
s = s + i
return s/(len(self.__grades))
def print_grades(self):
print(self.__grades) |
2ea3832c8ad23a22e48d400c8f339afb31a9e0c7 | podhmo/metashape | /examples/openapi/17with-newtype-userdefined/value.py | 904 | 3.53125 | 4 | import typing as t
class Person:
name: str
MyPerson = t.NewType("MyPerson", Person)
OptionalMyPerson2 = t.NewType("OptionalMyPerson", t.Optional[Person])
OptionalMyPerson3 = t.NewType("OptionalMyPerson2", t.Optional[MyPerson])
MyPeople = t.NewType("MyPeople", t.List[Person])
MyPeople2 = t.NewType("MyPeople2", t.List[MyPerson])
MyPeopleOptional = t.NewType("MyPeopleOptional", t.List[OptionalMyPerson2])
class Value:
person: Person
my_person: MyPerson
optional_person: t.Optional[Person]
optional_my_person: t.Optional[MyPerson]
optional_my_person2: OptionalMyPerson2
optional_my_person3: OptionalMyPerson3
people: t.List[Person]
my_people: MyPeople
my_people2: MyPeople2
my_people_optional: MyPeopleOptional
optional_people: t.Optional[t.List[Person]]
optional_my_people: t.Optional[MyPeople]
optional_my_people2: t.Optional[MyPeople2]
|
82a9de7d33683f6a4ed1f0ca5f2c943abe686dfb | group15bse/BSE-2021 | /src/Chapter7/exercise2.py | 418 | 3.5625 | 4 | try:
mylist=[]
name=input("Enter file name:")
file=open(name,"r")
count=0
for line in file:
if line.startswith("X-DSPAM-Confidence:"):
count+=1
trim=line.find(":")
extract=float(line[trim+1:])
mylist.append(extract)
print("Average spam confidence:",(sum(mylist))/count)
except:
print("File name doesn't exist in current directory!!!") |
a32d035229cee38a3af279ca22b76f2da5c9f977 | group15bse/BSE-2021 | /src/chapter2/exercise3.py | 215 | 4.0625 | 4 | #input for users' hours
Hours = float(input("Enter hours: "))
#input for uers' rate
Rate = float(input("Enter rate: "))
#computing gross pay
Gross_pay = Hours * Rate
#printing users gross pay
print("Pay:",Gross_pay) |
ffc634fec45abf85122b2fcad063be3e4dc9e703 | group15bse/BSE-2021 | /src/chapter8/exercise1.py | 176 | 3.59375 | 4 | def chop(list):
print(list[1:-1])
def middle(list):
middle = (list[1:-1])
print(middle)
list = ['goat','cow','cat','sheep','dog','hen']
chop(list)
middle(list)
|
da98d3c00028d3245a9233eb93c15c37998c5ff5 | wgwus/py_code_test | /test/process/process_test.py | 926 | 3.515625 | 4 | import time
from multiprocessing import Process
def io_task():
# time.sleep 强行挂起当前进程 1 秒钟
# 所谓”挂起“,就是进程停滞,后续代码无法运行,CPU 无法进行工作的状态
# 相当于进行了一个耗时 1 秒钟的 IO 操作
# 上文提到过的,IO 操作可能会比较耗时,但它不会占用 CPU
time.sleep(1)
def main():
start_time = time.time()
process_list=[]
for i in range(5):
process_list.append(Process(target=io_task)) # 加入到任务列表,到时候去执行
for process in process_list: #开始执行列表里的函数
process.start()
for process in process_list:
process.join()
# 循环 IO 操作 5 次
end_time = time.time()
# 打印运行耗时,保留 2 位小数
print('程序运行耗时:{:.2f}s'.format(end_time-start_time))
if __name__ == '__main__':
main() |
1f4a5bc0a9639ddbc6766cd478a59c409a4b5e4a | Juhkim90/L8-Boolean-Operators-Random-Number-Generator | /main.py | 1,537 | 4.03125 | 4 | import random
print ("Flip coin...")
# 1 = heads, 2 = tails
coin = random.randint(1,2)
if(coin == 1):
print ("It is heads!")
elif(coin == 2):
print ("It is tails!")
print ("Rolling die...")
# Exercise: Rolling dice
die = random.randint(1,6)
if (dice == 1):
print("You rolled a 1!")
elif(dice == 2):
print("You rolled a 2!")
elif(dice == 3):
print("You rolled a 3!")
elif(dice == 4):
print("You rolled a 4!")
elif(dice == 5):
print("You rolled a 5!")
elif (dice == 6):
print("You rolled a 6!")
# Exercise: Rock Paper Scissors (RPS)
import random
print ("Welcome to RPS")
print ("1. rock")
print ("2. paper")
print ("3. scissors")
p1 = input("Enter your choice: ")
cpu = random.randint(1,3)
# 1 : rock , 2 : paper , 3 : scissors
# Convert 1
if (p1 == "1" or p1 == "rock"):
p1 = 1
# Convert 2
elif (p1 == "2" or p1 == "paper"):
p1 = 2
# Convert 3
elif (p1 == "3" or p1 == "scissors"):
p1 = 3
# Rock vs Rock (t)
# Rock vs Paper (l)
# Rock vs Scissors (w)
# Paper vs Rock (w)
# Paper vs Paper (t)
# Paper vs Scissors (l)
# Scissors vs Rock (l)
# Scissors vs Paper (w)
# Scissors vs Scissors (t)
# Tied
if (p1 == cpu):
print ("Tied")
# player won
elif (p1 == 1 and cpu == 3 or p1 == 2 and cpu == 1 or p1 == 3 and cpu == 2):
print ("Player won")
# player lost
elif (p1 == 1 and cpu == 2 or p1 == 2 and cpu == 3 or p1 == 3 and cpu == 1):
print ("Player lost")
if (cpu == 1):
print ("cpu : rock")
elif (cpu == 2):
print ("cpu : paper")
elif (cpu == 3):
print ("cpu : scissors")
|
3bdf1be2bed2efb16e3d387ad70ff17b1136d618 | abhijith-AS/Linkedin-Lead-Generator | /selenium_utilities.py | 25,088 | 3.5 | 4 | '''
Functions for scraping using Selenium
'''
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium import webdriver
import tldextract
from credentials import LINKEDIN_USERNAME
from credentials import LINKEDIN_PASSWORD
import time
def send_word(word, location):
'''
sends keys to an element
:param word: word to send
:param location: element to send to
:return:
'''
for letter in word:
location.send_keys(letter)
time.sleep(0.05)
def page_amount(result_amount):
"""
Description: Calculates the number of
pages there are for the search
-------------------------------------
:param result_amount: amount of
results the page brings up
:return pages: number of pages in the
search
-------------------------------------
Use: v = page_amount(result_amount)
"""
if ',' in result_amount or 'K' in result_amount or int(result_amount) > 1000:
pages = 40
elif int(result_amount) < 25:
pages = 1
else:
pages = int(int(result_amount) / 25)
return pages
def get_driver(max_screen):
"""
Description: Gets a chrome driver
session. User chooses if screen is
maximized
-------------------------------------
:param max_screen: Boolean of if the
chrome window should open maximized
:return driver: and open chrome
driver
-------------------------------------
Use: v = get_driver(max_screen)
"""
if max_screen:
options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)
return driver
elif not max_screen:
driver = webdriver.Chrome()
return driver
else:
print("parameter must be boolean")
def login(driver):
'''
logs into Linkedin from the login page
:param driver: currently active chrome driver
:return:
'''
driver.get("https://www.linkedin.com/")
wait_for_element("login-email", driver, "class")
login_user = driver.find_element_by_class_name("login-email")
login_pass = driver.find_element_by_id("login-password")
send_word(LINKEDIN_USERNAME, login_user)
send_word(LINKEDIN_PASSWORD, login_pass)
login_pass.send_keys(Keys.ENTER)
return
def user_login(driver, user):
'''
logs into Linkedin from the login page
:param driver: currently active chrome driver
:param user: user to login as {"username": "example@example.com", "password": "password345"}
:return:
'''
driver.get("https://www.linkedin.com/")
wait_for_element("login-email", driver, "class")
login_user = driver.find_element_by_class_name("login-email")
login_pass = driver.find_element_by_id("login-password")
send_word(user["username"], login_user)
send_word(user["password"], login_pass)
login_pass.send_keys(Keys.ENTER)
return
def wait_for_element(element, driver, element_type):
"""
Description: Will wait until the
page has loaded the element before
continuing
-------------------------------------
:param element: either a class name
or id
:param driver: the current driver
:param element_type: either "class"
or "id"
:return:
-------------------------------------
Use: wait_for_element(element, driver, element_type)
"""
if element_type == "class":
try:
myElem = WebDriverWait(driver, 8).until(EC.presence_of_element_located((By.CLASS_NAME, element)))
except TimeoutException:
print("Loading for -- {} -- took too much time!".format(element))
elif element_type == "id":
try:
myElem = WebDriverWait(driver, 8).until(EC.presence_of_element_located((By.ID, element)))
except TimeoutException:
print("Loading for -- {} -- took too much time!".format(element))
elif element_type == "selector":
try:
myElem = WebDriverWait(driver, 8).until(EC.presence_of_element_located((By.CSS_SELECTOR, element)))
except TimeoutException:
print("Loading for -- {} -- took too much time!".format(element))
else:
print('Invalid type')
return
def next_page(driver):
'''
clicks the next page button
:param driver: the currently actvive chrome driver
:return:
'''
next_page_class = 'search-results__pagination-next-button'
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
time.sleep(2)
try:
next_page_class = 'search-results__pagination-next-button'
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).click().perform()
time.sleep(4)
except Exception as e:
print(e)
return
def get_pages_data(pages, driver):
'''
:param pages:
:param driver:
:return:
'''
data = {
'contacts': []
}
for page in range(pages):
next_page_class = 'search-results__pagination-next-button'
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
time.sleep(3)
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
names = driver.find_elements_by_class_name("result-lockup")
print('\n\nnames:')
print(names)
for element in names:
try:
profile_url_element = element.find_element_by_class_name("result-lockup__name")
profile_url = profile_url_element.find_element_by_css_selector('a').get_attribute('href')
name = profile_url_element.text
company = element.find_element_by_class_name("result-lockup__position-company").text
other_info = element.find_element_by_class_name("result-lockup__highlight-keyword").text
contact = {
'name': name,
'company': company.split('\n')[0],
'other_info': other_info,
'profile_url': profile_url
}
print(contact)
data['contacts'].append(contact)
except Exception as e:
print(e)
pass
try:
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).click().perform()
time.sleep(4)
except Exception as e:
print(e)
return data
def find_name(full_name):
'''
finds first and last name from full name
:param full_name: the full name to check
:return : returns dict containing first and last name
'''
prefix_array = [
'mc', 'van', 'von',
'mac', 'fitz', 'o',
'de', 'di', 'van de',
'van der', 'van den',
'da'
]
remove_text = """"'!@#$%^&*()_+-={}|:"<>?[]\;',./'"""
remove_array = [
'MBA', 'CFA', 'CPA', 'HRPA',
'CHRP', 'CPHR', 'PHD', 'CHRL',
'CIPD', 'CHRP', 'jr', 'jr.',
'JR', 'JR.', 'Jr', 'Jr.',
'CCWP'
]
first_check = full_name.split(',', 1)[0]
split_name = first_check.split(" ")
clean_words = []
for word in split_name:
word = word.split(',', 1)[0]
if '.' not in word:
for char in remove_text:
word = word.replace(char, '')
clean_words.append(word)
for element in remove_array:
is_not_thing = lambda x: x is not element
cleaned_name = list(filter(is_not_thing, clean_words))
if len(cleaned_name) == 2:
first_name = cleaned_name[0]
last_name = cleaned_name[1]
return {
'first_name': first_name,
'last_name': last_name
}
else:
first_name = cleaned_name.pop(0)
last_name = ''
for word in cleaned_name:
last_name += ' ' + word
return {
'first_name': first_name.strip(),
'last_name': last_name.strip()
}
def clean_up_nav(data):
"""
Description: removes unwanted results
or letters from a sales nav crawl
-------------------------------------
:param array: an array that has gone
through LinkedIn crawler methods
:return clean_array: a clean array
-------------------------------------
Use: v = x.clean_up(array)
"""
clean_data = {
'contacts': []
}
while not data['contacts'] == []:
new_contact = data['contacts'].pop()
if new_contact['name'] != 'LinkedIn Member' and '.' not in new_contact['name']:
name = find_name(new_contact['name'])
split_info = new_contact['other_info'].strip().splitlines()
title = split_info[0].split(' at')[0].split('\n')[0]
company = new_contact['company'].split('\n')[0]
print(title)
contact = {
'first_name': name['first_name'],
'last_name': name['last_name'],
'company': company,
'title': title
}
clean_data['contacts'].append(contact)
return clean_data
def linkedin_scrape(url):
'''
scrapes a LinkedIn url for all user data
:param url: url to scrape through
:return clean_data: returns the cleaned scrape data
'''
driver = get_driver(True)
login(driver)
time.sleep(5)
driver.get(url)
# wait for the result count an calculate pages to look through
wait_for_element('artdeco-tab-primary-text', driver, "class")
result_amount = driver.find_element_by_class_name('artdeco-tab-primary-text').text
pages = page_amount(result_amount)
data = get_pages_data(pages, driver)
clean_data = clean_up_nav(data)
return clean_data
# LINKEDIN ACCOUNT FUNCTIONS
def get_pages_data_accounts(pages, driver):
'''
:param pages:
:param driver:
:return:
'''
data = {
'contacts': []
}
for page in range(pages):
next_page_class = 'search-results__pagination-next-button'
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
time.sleep(3)
names = driver.find_elements_by_class_name("result-lockup")
print('\n\nnames:')
print(names)
for element in names:
try:
profile_url_element = element.find_element_by_class_name("result-lockup__name")
profile_url = profile_url_element.find_element_by_css_selector('a').get_attribute('href')
name = profile_url_element.text
contact = {
'name': name,
'profile_url': profile_url
}
print(contact)
data['contacts'].append(contact)
except Exception as e:
print(e)
pass
try:
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).click().perform()
time.sleep(4)
except Exception as e:
print(e)
return data
def linkedin_account_scrape(url):
'''
scrapes a LinkedIn url for all account data
:param url: url to scrape through
:return clean_data: returns the cleaned scrape data
'''
driver = get_driver(True)
login(driver)
time.sleep(5)
driver.get(url)
# wait for the result count an calculate pages to look through
wait_for_element('spotlight-result-count', driver, "class")
result_amount = driver.find_element_by_class_name('artdeco-tab-primary-text').text
print('\nResult amount: ')
print(result_amount)
pages = page_amount(result_amount)
data = get_pages_data_accounts(pages, driver)
return data
def relevant_result(url, company):
'''
Checks if url is relevant to the company
:param url: url to check
:param company: company to find url for
:return: bool - if relevant or not
'''
false_results = [
'wikipedia', 'google', 'facebook',
'linkedin', 'twitter', 'youtube',
'nytimes', 'yelp', 'crunchbase',
'newswire', 'yelpblog', 'businessinsider',
'instagram', 'techcrunch', 'inc.com',
'wired.com', 'pinterest', 'indeed',
'glassdoor', 'ratemyemployer', 'bloomberg',
'tripadvisor', 'booking.com', 'kijiji',
'yellowpages', 'businesswire'
]
if url is None:
return False
for result in false_results:
if result in url and result not in company:
return False
return True
def get_result_links(results):
'''
gets links from google result objects
:param results:
:return:
'''
urls = []
while not results == []:
result = results.pop(0)
url_list = result.find_elements_by_tag_name('a')
while not url_list == []:
urls.append(url_list.pop().get_attribute('href'))
return urls
def parse_domain(unparsed_url):
'''
parsed a domain for the base domain
:param unparsed_url: unparsed domain to fix
:return: parsed domain
'''
if not unparsed_url == '' and unparsed_url is not None:
new_extract = tldextract.extract(unparsed_url)
return new_extract.registered_domain
return None
def fix_url(url):
if url is None:
return None
replace_url = url.replace('mailto:?body=', 'https://www.').replace('%20', ' ').replace('%3A', ':').replace('%2F', '/').replace('#', '')
return replace_url.split(' ')[0]
def google_company_search(location, company, driver):
'''
scrapes google for a company
:param location: location the search should be in
:param company: company to search for
:param driver: currently active chrome driver
:return:
'''
time.sleep(1.5)
search = company.replace(" ", "+")
driver.get("https://www.google.ca/search?q={}".format(search + '+' + location))
wait_for_element("srg", driver, "class")
results = driver.find_elements_by_class_name("r")
urls = get_result_links(results)
parsed_url = None
possible_result = False
while not possible_result and not urls == []:
url = fix_url(urls.pop(0))
if url is not None:
parsed_url = parse_domain(url)
possible_result = relevant_result(parsed_url, company)
if possible_result:
print('company: ')
print('Using: ' + parsed_url)
return parsed_url
return None
def google_pages_scrape(search_term, driver, pages=1):
'''
scrapes google for a company
:param search_term: company to search for
:param pages: number of pages to scrape
:param driver: currently active chrome driver
:return:
'''
time.sleep(1.5)
search = search_term.replace(" ", "+")
driver.get("https://www.google.ca/search?q={}".format(search))
domains = []
while pages:
wait_for_element("srg", driver, "class")
results = driver.find_elements_by_class_name("r")
urls = get_result_links(results)
next_page_button = driver.find_element_by_class_name('pn')
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
while not urls == []:
url = fix_url(urls.pop(0))
if url is not None:
parsed_url = parse_domain(url)
possible_result = relevant_result(parsed_url, search_term)
if possible_result:
print('Accepting: ' + parsed_url)
domains.append(parsed_url)
next_page_button = driver.find_element_by_class_name('pn')
actions = ActionChains(driver)
actions.move_to_element(next_page_button).click().perform()
pages -= 1
return domains
def url_email_scrape(driver, url):
'''
Scrapes the email from a webpage
:param driver: currently active selenium driver
:param url: url to scrape
:return email: returns the email if found - else None
'''
contact_paths = [
'', '/contact', '/contact-us'
]
results = None
found = False
count = 0
if 'http' not in url and 'https' not in url:
url = 'http://' + url
while not found and count < 3:
try:
driver.get(url + contact_paths[count])
print('Checking ' + url + contact_paths[count])
time.sleep(5)
results = driver.find_element_by_xpath("//*[text()[contains(.,'@')]]")
except Exception:
print('Error')
results = None
if results and results.text:
found = True
else:
print('No email found on ' + url + contact_paths[count])
count += 1
if found:
return results.text
else:
return None
def linkedin_nav_headcount_scrape(accounts):
'''
Retrieves the employees on LinkedIn company headcount
:param accounts: accounts to scrape url for headcount
:return clean_accounts: the number of employees on LinkedIn
'''
try:
driver = get_driver(True)
print('\n\n------ Logging in to LinkedIn ------\n\n')
login(driver)
time.sleep(4)
clean_accounts = []
while accounts:
try:
account = accounts.pop()
print('Checking account:')
print(account)
url = account[1]
driver.get(url)
target_element_name = 'cta-link'
wait_for_element(target_element_name, driver, "class")
count = driver.find_element_by_class_name(target_element_name).text
count_split = count.split(' ')
count_num = int(count_split[0].replace(',', ''))
print('\nEmployee count:')
print(count_num)
print()
account.append(count_num)
print('\nAdding Account\n\n')
print(account)
clean_accounts.append(account)
time.sleep(4)
except Exception as e:
print(e)
print('\n\n----- Error getting account -----\n\n')
time.sleep(3)
return clean_accounts
except Exception as e:
print(e)
print('Login Error')
return []
def quora_question_scraper(url):
'''
:param url:
:return contacts: array of contacts who followed posts on the quora page
'''
driver = get_driver(True)
driver.get(url)
questions = driver.find_elements_by_class_name('question_link')
while questions:
question = questions.pop()
driver.get(question)
time.sleep(3)
follower_button = driver.find_element_by_class_name('')
actions = ActionChains(driver)
actions.move_to_element(follower_button).click().perform()
#ADD SCROLLING TO BOTTOM OF FOLLOWERS
def linkedin_profile_scraper(driver, url):
'''
scrapes data off a linkedin profile
:param driver: currently active driver
:param url: profile url to scrape from
:return contact: returns the contact data as an array
'''
driver.get(url)
time.sleep(3)
profile = []
name = driver.find_element_by_class_name('pv-top-card-section__name')
title = driver.find_element_by_class_name()
return profile
def linkedin_comment_scraper(driver, url):
'''
Scrapes leads from a post on LinkedIn
:param url: url to scrape leads from
:param driver: currently active driver
:return contacts: returns the contacts from the post
'''
scraped_profiles = []
try:
driver.get(url)
time.sleep(3)
# PUT IN A WAIT FOR ELEMENT HERE
button_id = 'show_prev'
more_comments_button = driver.find_elements_by_id(button_id)
while more_comments_button:
actions = ActionChains(driver)
actions.move_to_element(more_comments_button).click().perform()
more_comments_button = driver.find_elements_by_id(button_id)
linkedin_profile_links = driver.find_element_by_class_name('feed-shared-post-meta__profile-link')
while linkedin_profile_links:
link = linkedin_profile_links.pop()
profile_scrape = linkedin_profile_scraper(driver, link)
if profile_scrape:
scraped_profiles.append(profile_scrape)
return scraped_profiles
except Exception as e:
print(e)
return []
def linkedin_post_scraper(urls):
'''
scrape multiple posts from LinkedIn
:param urls: all the post urls to scrape from
:return contacts: returns contacts from multiple posts
'''
contacts = []
driver = get_driver(True)
while urls:
new_contacts = linkedin_comment_scraper(driver, urls.pop())
time.sleep(3)
while new_contacts:
contacts.append(new_contacts.pop())
return contacts
def linkedin_like_post(url, account):
'''
Logs in and likes a post on LinkedIn
:param url: post url of the post to like
:param account: account to like from {"username": "example@example.com", "password": "password345"}
:return:
'''
try:
driver = get_driver(True)
user_login(driver, account)
time.sleep(2)
driver.get(url)
time.sleep(3)
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(3)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# WAIT FOR LIKE ELEMENT
like_button_class = 'like-button'
element = driver.find_element_by_class_name(like_button_class)
actions = ActionChains(driver)
actions.move_to_element(element).click().perform()
except Exception as e:
print(e)
print('Error liking LinkedIn post')
def linkedin_account_domain(nav_results, driver):
'''
Scrapes the company domain from the sales nav page
:param nav_results: array of the account sales nav profile urls
:param driver: the currently active driver
:return: array - the company domain from sales nav - removes company if domain not found
'''
clean_results = []
if nav_results is None:
print('-- ERROR: scrape accounts before using company_domain_scrape() --')
else:
while nav_results:
nav_result = nav_results.pop()
try:
driver.get(nav_result['profile_url'])
time.sleep(1)
next_page_class = 'search-results__pagination-next-button'
wait_for_element(next_page_class, driver, 'class')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).perform()
time.sleep(3)
company_url = 'website'
element = driver.find_element_by_class_name(company_url)
nav_result['domain'] = element.find_element_by_css_selector('a').get_attribute('href')
next_page_button = driver.find_element_by_class_name(next_page_class)
actions = ActionChains(driver)
actions.move_to_element(next_page_button).click().perform()
time.sleep(2)
except Exception as e:
print(e)
return clean_results
def auto_connect(driver, data):
driver.get('')
wait_for_element('nav-search-controls', driver, 'class')
|
9d9b9675c1704e4ca98c541ab602ea0e879f746f | kurodoll/daily-programmer | /301ei/301ei.py | 644 | 3.953125 | 4 | def matches(word, pattern):
for i in range(0, len(word) - len(pattern) + 1):
checkPattern = pattern
j = 0
for c in checkPattern:
if 65 <= ord(c) <= 90:
if not word[i + j] in checkPattern:
checkPattern = checkPattern.replace(c, word[i + j])
j += 1
if checkPattern in word:
return True
if __name__ == "__main__":
import sys
if (len(sys.argv) < 3):
exit()
dictFile = open(sys.argv[1])
for word in dictFile:
word = word.strip('\n')
if (matches(word, sys.argv[2])):
print(word)
|
b3c11fd84d5dc1bf76111a182a71e76b9ce6fc30 | jescobar806/minTic | /fundamentosProgramacion/clase3/ejerciciosPracticaCiclos/11sumaEnteros.py | 201 | 3.78125 | 4 |
number1 = int(input("Ingrese el primer entero del rango: "))
number2 = int(input("Ingrese el segundo entero del rango: "))
suma = 0
for i in range (number1,number2+1):
suma = suma + i
print (suma) |
81eb4375f916b88e9cdd3c1ee7c37b20493e32f6 | jescobar806/minTic | /fundamentosProgramacion/clase3/ejerciciosPracticaCiclos/14name.py | 172 | 4.03125 | 4 |
while True:
name = input ("Ingrese su nombre: ")
if name == "done":
print ("I'm done")
elif name == "END":
break
else:
print (name) |
7e0b13d878fe75d4705310ab3235babdace6c908 | ataylor1184/cse231 | /Proj02/proj02.py | 2,980 | 3.796875 | 4 | quarters = 10
dimes = 10
nickels = 10
pennies = 10
price = 0
int_paid = 0
print("\nWelcome to change-making program.")
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
price = input("Enter the purchase price (xx.xx) or 'q' to quit: ")
price = float(price)*100
int_paid = float(int_paid) *100
while price!="q":
price = float(price)
if price < 0:
print("Error: purchase price must be non-negative.")
elif price > 0:
int_paid = input("Input dollars paid (int): ")
int_paid = int(int_paid) *100
TotalChange = int_paid-price
TotalPossibleChange = (quarters*25)+(dimes*10)+(nickels*5)+(pennies*1)
while TotalChange < 0:
print("Error: insufficient payment.")
int_paid = input("Input dollars paid (int): ")
int_paid = int(int_paid)*100
TotalChange = int_paid-price
if TotalChange == 0:
print("No change.")
elif TotalChange > 0:
QChange =0
DChange=0
NChange=0
PChange=0
int_change_pennies=0
if TotalChange < TotalPossibleChange:
while quarters >= 1 and TotalChange // 25 > 0:
TotalChange = TotalChange-25
QChange +=1
quarters = quarters -1
while dimes >= 1 and TotalChange // 10 > 0:
TotalChange -=10
DChange +=1
dimes-=1
while nickels >= 1 and TotalChange // 5 > 0:
TotalChange -=5
NChange +=1
nickels-=1
while pennies >=1 and TotalChange // 1 > 0:
TotalChange -=1
PChange +=1
pennies -=1
if TotalChange % 1 >0:
PChange +=1
pennies -=1
print('\nCollect change below: ')
if (QChange) > 0:
print ('Quarters:', QChange)
if (DChange) > 0:
print('Dimes:', DChange)
if (NChange) > 0 :
print('Nickels:', NChange)
if (PChange) > 0:
print('Pennies:', PChange)
else:
print("Error: ran out of coins.")
break
print("\nStock: {} quarters, {} dimes, {} nickels, and {} pennies".format(
quarters, dimes, nickels, pennies))
price = input("Enter the purchase price (xx.xx) or 'q' to quit: ")
if str(price) =='q':
break
else :
price = float(price)*100
price =int(price)
|
a194787f8f7e817bf3b7166bcb3b9bce96e024ef | ataylor1184/cse231 | /Proj01/Project01.py | 1,221 | 4.46875 | 4 |
#######################################################
# Computer Project #1
#
# Unit Converter
# prompt for distance in rods
# converts rods to different units as floats
# Outputs the distance in multiple units
# calculates time spent walking that distance
########################################################
Rods = input("Input rods: ")
Rods = float(Rods)
print("You input " + str(Rods) + " rods.")
print("Conversions")
Furlongs = round(float(Rods / 40) ,3) # Converts Rods to Furlongs
Meters = round(float(Rods * 5.0292) , 3) # Converts Rods to Meters
Feet = round(float(Meters / .3048) ,3) # Converts Meters to Feet
Miles = round(float(Meters / 1609.34) , 3) # Converts Meters to Miles
SpeedInRods = float(3.1 *320)/60 # Converts MpH to Rods per minute
Time = round(float(Rods / SpeedInRods) ,3) # Divides distance by speed
print("Meters: " + str(Meters))
print("Feet: " + str(Feet))
print("Miles: " + str(Miles))
print("Furlongs: " + str(Furlongs))
print("Minutes to walk " + str(Rods) + " rods: " + str(Time))
#print("Minutes to walk " + str(Rods) + " Rods:" + )
|
b02608ac822c2cde2573c9d98ac4afcff1bb5f47 | LionsoftIT/Python_3.8 | /costo_abb_piscina.py | 660 | 3.734375 | 4 | """
Creatore: LEONARDO ESSAM DEI ROSSI
E-Mail: leonardo.deirossi@icloud.com
"""
""" Variabili """
costo_studenti = 35;
costo_adulti = 60;
studenti_req_sconto = 3;
sconto_studenti = 25;
totale_adulti = 0;
totale_studenti = 0;
costo_totale = 0;
""" Inserimento dati """
totale_adulti = int(input("Inserisci il numero di adulti: "));
totale_studenti = int(input("Inserisci il numero di studenti: "));
""" Calcoli """
if (totale_studenti >= studenti_req_sconto):
costo_studenti = sconto_studenti;
costo_totale = (totale_adulti * costo_adulti)+(totale_studenti * costo_studenti);
""" In uscita """
print("Il prezzo finale dell'abbonamento è di " + str(costo_totale));
|
f4d0325182a50724f7e8248572d891f039cf0f7c | zsxoff/optimization-methods | /example_newton.py | 791 | 3.6875 | 4 | #!/usr/bin/env python
import misc
from simethods.newton_2d import newton_2d
from siplot.plot import Dot
from siplot.plot_2d import plot_2d
def f(x: float, y: float) -> float:
"""Test function."""
return y**4 + x * y**3 + 2 * (y**2) * (x**2) + y + x**4 - x
def main() -> None:
"""Newton method example."""
start_x = misc.inputf('Enter start X: ')
start_y = misc.inputf('Enter start Y: ')
eps = misc.inputf('eps: ')
x_min, y_min = newton_2d(f, start_x, start_y, eps)
f_min = f(x_min, y_min)
print(f'x_min = {x_min}\n'
f'y_min = {y_min}\n'
f'f(x_min, y_min) = {f_min}\n')
# Plot result.
dots = [
Dot(x_min, y_min, 'ro'),
]
plot_2d(f, dots=dots)
if __name__ == '__main__':
main()
|
64b50b9c39a3d50ac1c65093c95f44dd9fbea05e | hitrj-lis/my_projects | /probe_01/not_pad.py | 2,554 | 3.5 | 4 | from tkinter import Tk, Menu, Text, messagebox, END, filedialog
def context(event):
context_menu.tk_popup(event.x_root, event.y_root)
def close():
if messagebox.askyesno(exit_out_txt, asky_exit_txt):
window.destroy()
def new_file():
if messagebox.askyesno(new_file_txt, asky_new_txt):
text_panel.delete(1.0, END)
window.title(new_file_txt)
def open_file():
try:
if messagebox.askyesno(new_file_txt, asky_new_txt):
file_name = filedialog.askopenfilename()
with open(file_name, 'r', encoding='utf-8') as file:
text_panel.delete(1.0, END)
content = file.read()
text_panel.insert(1.0, content)
window.title(file_name)
else:
return
except FileNotFoundError:
pass
def save_file():
file_name = filedialog.asksaveasfilename()
with open(file_name + '.txt', 'w') as file:
content = text_panel.get(1.0, END)
file.write(content[:-1])
# окно
window = Tk()
window.geometry('800x600')
window.title('Новый файл')
window.resizable(False, False)
# текстовые данные
top_txt = 'Файл'
new_txt = 'Создать'
open_txt = 'Открыть'
save_txt = 'Сохранить'
copy_txt = 'Копировать'
paste_txt = 'Вставить'
cut_txt = 'Вырезать'
exit_out_txt = 'Выход'
asky_exit_txt = 'Все изменения будут утеряны!\n\t Выйти?'
new_file_txt = 'Новый файл'
asky_new_txt = 'Все изменения будут утеряны!\n Создать новый файл?'
# верхняя панель
top_panel = Menu()
window.config(menu=top_panel)
# менюшки в верхней панели
file_menu = Menu(top_panel, tearoff=0)
top_panel.add_cascade(label=top_txt, menu=file_menu)
# меню файл
file_menu.add_command(label=new_txt, accelerator='Ctr+N', command=new_file)
file_menu.add_command(label=open_txt, accelerator='Ctr+O', command=open_file)
file_menu.add_command(label=save_txt, accelerator='Ctr+S', command=save_file)
# текстовое поле
text_panel = Text(width=800, height=600)
text_panel.pack()
# контекстное меню
context_menu = Menu(text_panel, tearoff=0)
context_menu.add_command(label=copy_txt)
context_menu.add_command(label=paste_txt)
context_menu.add_command(label=cut_txt)
# сигнал от пользователя
text_panel.bind('<Button-3>', context)
window.protocol('WM_DELETE_WINDOW', close)
window.mainloop()
|
ac338324e89dbd19f2f1212d624d8b6818698311 | NeimarS/algoritmos_e_programacao_II | /atividade01.py | 3,131 | 3.984375 | 4 | #Atividade 01
def incluir():
try:
nome = input("Digite o nome do produto: ")
preco = float(input("Digite o preço do produto: "))
qtde = int(input("Digite a quantidade do produto: "))
if nome != '' and preco > 0 and qtde > 0:
lst_nome_produto.append(nome)
lst_preco_produto.append(preco)
lst_qtde_produto.append(qtde)
input("Produto cadastrado com sucesso![ENTER]")
else:
input("O nome do produto não pode ser vazio e o preço e quanidade deve ser maior que 0. [ENTER]")
incluir()
except:
input("Ocorreu um erro nos dados informados, tente novamente!")
incluir()
def mostrar():
flag = 0
if len(lst_nome_produto) == 0:
input("Nenhum produto cadastrado! [ENTER]")
else:
print("----------------------------------------")
print("indice - nome")
for x in range(len(lst_nome_produto)):
print(str(x).ljust(9," ") + lst_nome_produto[x])
try:
indice = int(input("Digite o índice do produto: "))
for y in range(len(lst_nome_produto)):
if y == indice:
flag = 1
if flag == 1:
print("----------------------------------------")
print("indice - nome - quantidade - preço")
print(str(indice).ljust(9," ") + lst_nome_produto[indice].ljust(22, " ") + str(lst_qtde_produto[indice]).ljust(8," ")+ str(lst_preco_produto[indice]))
input("[ENTER] para sair")
else:
input("Índice não está na lista! [ENTER]")
mostrar()
except:
input("Índice inválido!")
mostrar()
def remover():
if len(lst_nome_produto) == 0:
input("Nenhum produto cadastrado! [ENTER]")
else:
print("----------------------------------------")
print("indice - nome")
for x in range(len(lst_nome_produto)):
print(str(x).ljust(9," ") + lst_nome_produto[x])
try:
indice = int(input("Digite o índice do produto a remover: "))
for y in range(len(lst_nome_produto)):
if y == indice:
flag = 1
if flag == 1:
del lst_nome_produto[indice]
del lst_preco_produto[indice]
del lst_qtde_produto[indice]
input("Produto removido com sucesso![ENTER]")
else:
input("Índice não está na lista! [ENTER]")
remover()
except:
input("Índice inválido! [ENTER]")
remover()
lst_nome_produto = []
lst_preco_produto = []
lst_qtde_produto = []
while True:
menu = input('''
1-Incluir produto na lista
2-Mostrar dados do produto cadastrado
3-Remover produto pelo índice
4-Finalizar o programa
Escolha: ''')
if menu == '1':
incluir()
if menu == '2':
mostrar()
if menu == '3':
remover()
if menu == '4':
break
|
739483ab59cd0be1df31362e355a814238748a4a | rpadaki/HackPrinceton | /scripts/grapher.py | 2,285 | 3.984375 | 4 | """ Outputs graphs in ready-to-draw format """
import networkx as nx
def whole(distances):
# graphs all node and connects them to all other nodes, with the length
# being a function of the actual distance (no path included)
g = nx.DiGraph()
# for each key-value pair in distances, adds an edge whose start is the
# start point, end is the key, and weight is the value
# only does so if distance is not infinite
for start in distances:
for key, value in distances[start].items():
if not value == "inf" and not start == key:
g.add_edge(start, key, weight=value)
return g
def tree(start, predecessors, graph):
# graphs the shortest path between one node and every other node
g = nx.DiGraph()
# for every pair of predecessors, creates an edge between the two
# with the same weight as determined by connections
# note that the edge starts at the value and goes to the key
print(predecessors[start])
for key, value in predecessors[start].items():
g.add_edge(value, key, weight=graph[value][key]["weight"])
return g
def single(start, end, predecessors, graph):
# graphs the shortest path between two specific nodes
g = nx.DiGraph()
# handle the case where the start and end are the same
if start == end:
g.add_node(start)
return g
# search through the list for the end node and work backwards
# assumes that the start and end are connected
previous = predecessors[start][end]
while True:
# while we haven't reached the start
# add an edge for each connection
g.add_edge(previous, end, weight=graph[previous][end]["weight"])
# move onto the next pair
end = previous
if end == start:
break
previous = predecessors[start][previous]
if end == start:
break
# at this point, should have fully-connected 1D graph
return g
def planet(start, distances):
# graphs one node and connects it to all other nodes, with the length
# being a function of the actual distance (no path included)
g = nx.DiGraph()
# for each key-value pair in distances, adds an edge whose start is the
# start point, end is the key, and weight is the value
# only does so if distance is not infinite
for key, value in distances[start].items():
if not value == "inf" and not start == key:
g.add_edge(start, key, weight=value)
return g |
5fdea903da97b47357c07495b106e03e51304005 | IsidorosT/Python-1st-Semester-1stYear-2019 | /exercise4.py | 6,100 | 3.84375 | 4 | def Zero(*eq):
if len(eq) == 0:
index = 0
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 0
elif k == "-":
res = 0 - index
elif k == "x":
res = index * 0
elif k == "/":
res = 0 / index
else:
if index != 0:
res = 0 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def One(*eq):
if len(eq) == 0:
index = 1
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 1
elif k == "-":
res = 1 - index
elif k == "x":
res = index * 1
elif k == "/" and index != 0 :
res = 1 / index
else:
if index != 0:
res = 1 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Two(*eq):
if len(eq) == 0:
index = 2
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 2
elif k == "-":
res = 2 - index
elif k == "x":
res = index * 2
elif k == "/" and index != 0:
res = 2 / index
else:
if index != 0:
res = 2 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Three(*eq):
if len(eq) == 0:
index = 3
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 3
elif k == "-":
res = 3 - index
elif k =="x":
res = index * 3
elif k == "/" and index != 0:
res = 3 / index
else:
if index != 0:
res = 3 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Four(*eq):
if len(eq) == 0:
index = 4
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 4
elif k == "-":
res = 4 - index
elif k == "x":
res = index * 4
elif k == "/" and index != 0:
res = 4 / index
else:
if index != 0:
res = 4 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Five(*eq):
if len(eq) == 0:
index = 5
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 5
elif k == "-":
res = 5 - index
elif k == "x":
res = index * 5
elif k == "/" and index != 0:
res = 5 / index
else:
if index != 0:
res = 5 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Six(*eq):
if len(eq) == 0:
index = 6
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 6
elif k == "-":
res = 6 - index
elif k == "x":
res = index * 6
elif k == "/" and index != 0:
res = 6 / index
else:
if index != 0:
res = 6 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Seven(*eq):
if len(eq) == 0:
index = 7
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 7
elif k == "-":
res = 7 - index
elif k == "x":
res = index * 7
elif k == "/" and index != 0:
res = 7 / index
else:
if index != 0:
res = 7 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Eight(*eq):
if len(eq) == 0:
index = 8
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 8
elif k == "-":
res = 8 - index
elif k == "x":
res = index * 8
elif k == "/" and index != 0:
res = 8 / index
else:
if index != 0:
res = 8 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Nine(*eq):
if len(eq) == 0:
index = 9
return index
else:
index = eq[0][0]
k = eq[0][1]
if k == "+":
res = index + 9
elif k == "-":
res = 9 - index
elif k == "x":
res = index * 9
elif k == "/" and index != 0:
res = 9 / index
else:
if index != 0:
res = 9 // index
if index == 0:
error = "Division with zero is invalid"
return error
else:
return res
def Plus(num):
k = '+'
return (num, k)
def Minus(num):
k = '-'
return (num, k)
def Times(num):
k = 'x'
return (num, k)
def Divide(num):
k = '/'
return (num, k)
def CDivide(num):
k = 'div'
return (num, k)
|
4748e5ac854c64ffacb466d59367f27094614fd5 | sevmardi/Twitter-Sentiment-Analysis | /src/models/Tweet.py | 1,214 | 4.09375 | 4 | class Tweet(object):
tweet = ""
datetime = ""
user = ""
sentiment = ""
def __init__(self, tweet, user, datetime):
"""
Creates a tweet object container a tweet
"""
self.tweet = tweet
self.datetime = datetime
self.user = user
self.sentiment = ''
def get_tweet(self):
"""
Return the tweet
"""
return self.tweet
def set_tweet(self, tweet):
"""
Set the tweet
"""
self.tweet = tweet
def get_user(self):
"""
Return the author of the tweet
"""
return self.user
def set_user(self, user):
"""
Set the user of the tweet
"""
self.user = user
def get_date(self):
"""
Returns the date of the tweet
"""
return self.datetime
def set_date(self, date):
"""
Return the a datetime stamp of the tweet
"""
self.datetime = date
def get_sentiment(self):
return self.sentiment
def set_sentiment(self, sentiment):
self.sentiment = sentiment
def print_tweet(self):
print(self.get_tweet())
print(self.get_date())
print(self.get_user())
|
9491b3509853916500be73d66b9b906d49015459 | KaliNa1488/Pythonparsers | /Minecraft Coord Helper.py | 417 | 3.859375 | 4 | firstx = int(input('Введите целую первую х координату:'))
secondx = int(input('Введите целую вторую х координату:'))
firsty = int(input('Введите целую первую у координату:'))
secondy = int(input('Введите целую вторую у координату:'))
x = firstx + secondx
y = firsty + secondy
print(x / 2, y / 2) |
0716618a683fb70c6748e7d6ac45c41b2da7f7b9 | vckfnv/Python_datastructure | /datastructure/search추가.py | 1,296 | 3.828125 | 4 | class Node:
def __init__(self, data, llink = None, rlink = None):
self.data = data
self.llink = llink
self.rlink = rlink
def Search(head,a):
while True:
if head.rlink.data >= a:
return head.rlink
break
else:
head = head.rlink
def ListPrint(head):
while True:
if head.rlink == None:
if head.data == None:
print("no data")
else:
print()
break
else:
head = head.rlink
print(head.data," ",end="")
def Insert(head,x):
node=Node(x)
fnode=Search(head,x)
fnode.llink.rlink=node
node.llink=fnode.llink
fnode.llink=node
node.rlink=fnode
def Delete(head):
while True:
if head.rlink == None:
head=head.llink
head.rlink = None
break
else:
head=head.rlink
#fnode=search(head,2)
#print("Find node = ",fnode.data)
#맨끝에 삽입 삭제하는것 과제
head=Node(None)
Insert(head,2)
Insert(head,1)
Insert(head,4)
Insert(head,6)
Insert(head,8)
ListPrint(head)
Delete(head)
Delete(head)
Delete(head)
Delete(head)
Delete(head)
ListPrint(head)
|
77a43f1b10cd3b6a57b648acf48c61d1bbb8427e | vckfnv/Python_datastructure | /datastructure/자료구조개론/큐 리스트.py | 1,227 | 3.703125 | 4 | class QQ():
def __init__(self,n):
self.q=[]
self.front=0
self.rear=0
self.size=n
for i in range(n):
self.q.append(None)
def isFull(self):
if (self.rear+1)%(self.size)==(self.front) and self.q[self.rear]!=0:
return True
else:
return False
def isEmpty(self):
if self.front==self.rear:
return True
else:
return False
def insert(self,data):
if self.isFull():
print("It's full, can't insert anymore")
else:
self.rear=(self.rear+1)%self.size
self.q[self.rear]=(data)
def delete(self):
if self.isEmpty():
print("nothing to delete")
else:
self.front=(self.front+1)%self.size
self.q[self.front]="deleted"
def showup(self):
for i in range(len(self.q)):
print(self.q[i]," ",end='')
print()
qq=QQ(5)
qq.insert(1)
qq.insert(2)
qq.insert(3)
qq.showup()
qq.delete()
qq.showup()
qq.insert(4)
qq.showup()
qq.insert(5)
qq.showup()
qq.insert(6)
qq.showup()
|
1c5147cb238bb21dfe5a7c501f4a386dd5c784ae | MStevenTowns/Advanced-Data-Structures | /Notes/Unordered.py | 841 | 3.703125 | 4 | from Node import *
class UnorderedList:
def __init__(self):
self.head=None
def isEmpty(self):
return self.head==None
def add(self, item):
temp=Node(item)
temp.set_next(self.head)
self.head=temp
def size(self):
current=self.head
count=0
while current!=None:
count=count+1
current=current.get_next()
return count
def search(self, item):
current=self.head
fount=False
while current !=None and not found:
if current.getData()==item:
fount=True
else:
current=current.getNext()
return found
def remove(self, item):
current=self.head
previous=None
fount=False
while not found:
if current.getData()==item:
found=True
else:
previous=current
current=current.getNext()
if previous==None:
self.head=current.getNext()
else:
previous.setNext(current.getNext())
|
751bec5cb00f4d04788d5d8ec9a29210f100d2c5 | MStevenTowns/Advanced-Data-Structures | /Homework02/BinarySearch01.py | 662 | 3.5 | 4 | '''
M. Steven Towns
10/5/16
Homework 02
Part A
THIS MUST BE RUN WITH PYTHON 3
'''
def BinarySearch01(A,k):
low=0
high=len(A)-1
while True:
mid=(low+high)//2
#print(A[mid])
if A[mid]==k:
return mid
elif A[mid]>k:
high=mid-1
else:
low=mid+1
if low>=high:
return "NIL"
usrIn=input("Please give a list of numbers separated by a space (Enter for 0-99): ")
usrIn=usrIn.strip()
if usrIn=='':
A=[i for i in range(100)]
else:
A=usrIn.strip().split(" ")
A=[int(i) for i in A]
usrIn=input("Please give number to search the list for (Enter for 75): ")
k=usrIn.strip()
if k=='':
k=75
else:
k=int(k)
print("Index: "+str(BinarySearch01(A, k)))
|
c5e88509fd38193745bace564fcb01025137dbeb | MStevenTowns/Advanced-Data-Structures | /Notes/merge.py | 216 | 3.578125 | 4 | def merge(l1,l2):
slot1=0
slot2=0
out=[]
while(slot1<len(l1) && slot2<len(l2)):
if(l1[slot1]<l2[slot2]):
out.append(l1[slot1])
slot1++
elif(l1[slot1]>l2[slot2]):
out.append(l2[slot2])
slot2++
|
8be96399d6e1133f21366fde66e016c184d390a5 | mirmozavr/emailsender | /email_sender_html.py | 1,299 | 3.53125 | 4 | import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 465
receiver_email = ""
sender_email = "" # input("Type sending email: ")
password = "" # input("Type your password: ")
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
"""
# this may be used to open external HTML file
# with open("test.html", "r", encoding='utf-8') as f:
# text= f.read()
html = """\
<html>
<body>
<p>Hi,<br>
<a href="https://www.google.com">Google</a>
has many great tutorials.
</p>
</body>
</html>
"""
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email.format, message.as_string())
|
0bbbe5e06da128d89c8eef418360a1be724efa29 | english5040/Bashing-Adventure | /Thing.py | 669 | 3.515625 | 4 | import yaml
import argparse
class Thing:
"""
`Thing` : **`object`**
A `Thing` is the lowest common denominator of game entities,
and describes anything which can be seen or manifested in-game.
"""
description = "You're in a room!"
def __init__(self, arg):
super(Thing, self).__init__()
self.arg = arg
def Look(args):
print(description)
return False
class Item(Thing):
"""
`Item` : **`Thing`**
An `Item` is a Thing that can be taken and dropped.
"""
def __init__(self, arg):
super(Item, self).__init__(arg)
def take(args):
return False
def drop(args):
return False
|
fd49f2b6597fbd971383f3ae32fba841c00b693b | Hansel-Lin420/Python_Pratice | /1~10no7.py | 186 | 3.703125 | 4 | # -*- coding: utf-8 -*-
#輸出1,2,3,4,5,6,8,9,10(沒有7)
"""
Created on Sun May 10 18:30:36 2020
@author: User
"""
for i in range(1,11):
if(i==7):
continue;
print(i)
|
9ac4b6b3da8544f3fb478d871686e73f7c6271e8 | Damianpon/damianpondel96-gmail.com | /zjazd 2/zbiory.py | 257 | 3.5 | 4 | zbior = set()
print(zbior)
zbior.add("x")
zbior.add(1)
print(zbior)
for element in zbior:
print(element)
print(dir(zbior))
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)
print((a & b))
print(a - b)
print(a ^ b)
print(a.pop())
print(a)
print(dir(set())) |
86c8900f4e6235b6e40d34d8eec993b0ae5541fb | Damianpon/damianpondel96-gmail.com | /zjazd I/zad10.py | 610 | 3.875 | 4 | first_number = int(input("Podaj pierwszą liczbę: "))
second_number = int(input("Podaj drugą liczbę: "))
kind_of_operation = input("Podaj znak operacji: ")
if kind_of_operation == "+":
result = first_number + second_number
elif kind_of_operation == "-":
result = first_number - second_number
elif kind_of_operation == "*":
result = first_number * second_number
elif kind_of_operation == "/":
if second_number == 0:
result = "Pamietaj cholero nie dziel przez zero"
else:
result = first_number / second_number
else:
result = "Zła operacja"
print(f"Wynik: {result}") |
793b5d06a3a64bcc3eeefca9fee2e4785ab7295c | Damianpon/damianpondel96-gmail.com | /zjazd I/zadania domowe/zad_domowe_1.py | 1,458 | 4.15625 | 4 | print("Gdzie znajduje się gracz na planszy?")
position_of_X = int(input("Podaj pozycję gracza X: "))
position_of_Y = int(input("Podaj pozycję gracza Y: "))
if position_of_X <= 0 or position_of_Y <= 0:
print("Gracz znajduje się poza planszą")
elif position_of_X <= 40:
if position_of_Y <= 40:
print("Gracz znajduje się w lewym dolnym rogu")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w lewym centralnym rogu")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w lewym górnym rogu")
elif position_of_X > 40 and position_of_X < 60:
if position_of_Y <= 40:
print("Gracz znajduje się w środkowej części na dole planszy")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w środkowej części na środku planszy")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w środkowej części na górze planszy")
elif position_of_X >= 60 and position_of_X <= 100:
if position_of_Y <= 40:
print("Gracz znajduje się w prawej dolnej części planszy")
elif position_of_Y > 40 and position_of_Y < 60:
print("Gracz znajduje się w prawej środkowej części planszy")
elif position_of_Y >= 60 and position_of_Y <= 100:
print("Gracz znajduje się w prawej górnej części planszy")
else:
print("Gracz znajduje się poza planszą")
|
366ee9eb1db60a56c69cd137d8404dc5ef24e023 | Damianpon/damianpondel96-gmail.com | /zjazd I/kolekcje.py | 230 | 3.828125 | 4 | x = (1, 2, 3, 10, 12, "ala", "mm", 2.0)
print(x)
print(type(x))
print(dir(x))
print(x.index("ala"))
print(len(x))
print(len("Ala"))
print(x.count(12))
print(3 in x)
print(x[0])
y = "mariola"
print(y[::-1])
print(tuple("123")) |
9f3c72e251ad5402c5b98099571945e567917bb2 | Damianpon/damianpondel96-gmail.com | /zjazd I/zadania domowe/zad_dod4.py | 917 | 3.546875 | 4 | x = int(input("Wpisz ilość pożądanych boków: "))
lengthOfX = str(x)
numberOfSteps = lengthOfX
listA = []
listA1 = []
for k in range(1, x):
listA1.append(k)
reverselenght = len(listA1)
for y in range(1, x, -1):
listA.append(y)
lengthOfTheLastOne = len(listA)\
lengthOfTheLastOne = 0
reverselenght = x
for i in range(x):
print((reverselenght - 1) * " " + "/" + 2 * lengthOfTheLastOne * " " + "\\")
lengthOfTheLastOne += 1
reverselenght -= 1
for z in range(x):
print(reverselenght * " " + "\\" + ((2 * lengthOfTheLastOne) - 2) * " " + "/")
lengthOfTheLastOne -= 1
reverselenght += 1
print(listA1)
print(listA)
dlugosc = 55
i = 0
y = 0
for i in range(dlugosc):
print(" " * (dlugosc - i - 1) + "/" + 2 * i * " " + "\\")
i += 1
for y in range(dlugosc):
print(" " * y + "\\" + (" " * ((2 * dlugosc - 2)) + "/"))
y += 1
dlugosc -= 1
|
7d8e32f98b09194f3ea072ae4f0372ca19be9f2b | Damianpon/damianpondel96-gmail.com | /zjazd I/listy.py | 279 | 3.75 | 4 | elementy = [1, 2, 3, 4, 5, "xxx", 2.0, 2]
print((type(elementy)))
print(list())
# Lista jest mutowalna --> można ją edytować
x = elementy.append("cos")
print(elementy)
print(x)
print(len(elementy))
while len(elementy) <11:
elementy.append("xx")
print(dir(elementy)) |
20b6485a651ca82c6a96f0952d4f0baf12ad39f4 | Damianpon/damianpondel96-gmail.com | /zjazd 2/slownik.py | 173 | 3.53125 | 4 | ## pol_ang = dict()
pol_ang = {"kot": "cat", "ptak": "bird"}
pol_ang["pies"] = "dog"
pol_ang["kot"]= "kitten"
print(pol_ang)
dict_2 =dict(a=18, b=22, c=33)
print(dict_2)
|
63dec67c550b5ed6aa9ed5e7fcc033b8b62c894c | Damianpon/damianpondel96-gmail.com | /zjazd I/zad_6.py | 207 | 3.765625 | 4 | x = int(input("Podaj liczbę: "))
print()
print(f"Liczba większa od 10:", float(x)>10)
print(f"Liczba jest mniejsza lub równa 15:", float(x)<=15)
print(f"Liczba jest podzielona przez 2:", float(x) %2 ==0)
|
fd7c0e4415f998c40232b1806c18c6178aa694d2 | Damianpon/damianpondel96-gmail.com | /zjazd 3/zad5.py | 1,214 | 3.578125 | 4 | class CashMachine:
def __init__(self):
self.__money = []
@property
def cash_is_available(self):
return len(self.__money) > 0
def put_money_into(self, bills):
self.__money += bills
def withdraw_money(self, amount):
to_withdraw = []
for bill in sorted(self.__money, reverse=True):
if sum(to_withdraw) + bill <= amount:
to_withdraw.append(bill)
if sum(to_withdraw) == amount:
for bill in to_withdraw:
self.__money.remove(bill)
return to_withdraw
class TestCashMashine:
def test_init(self):
cash_machine = CashMachine()
assert cash_machine
def test_is_money_there(self):
cash_machine = CashMachine()
assert cash_machine.cash_is_available == False
def test_put_money(self):
cash_machine = CashMachine()
cash_machine.put_money_into([200, 100, 100, 50])
assert cash_machine.cash_is_available == True
def test_withdraw(self):
cash_machine = CashMachine()
cash_machine.put_money_into([200, 100, 100, 50])
assert cash_machine.withdraw_money(150) == [100, 50] |
04257917b7ed7b125d67613fcc44d5a0b242c0d5 | emna7/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 282 | 3.8125 | 4 | #!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
with open(filename) as f:
i = len(list(f))
if nb_lines >= i or nb_lines <= 0:
nb_lines = i
f.seek(0, 0)
for count in range(nb_lines):
print(f.readline(), end="")
|
ef36fbfb009267f38a6d71d1a5d5aa517395ea38 | emna7/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 3,564 | 3.71875 | 4 | #!/usr/bin/python3
""" Rectangle Class """
from models.base import Base
class Rectangle(Base):
""" rectangle class - inherits from Base
Attributes:
width (obj:`int`): width of rectangle
height (obj:`int`): height of rectangle
x (obj:`int`): x set of rectangle
y (obj:`int`): y set of rectangle
"""
def __init__(self, width, height, x=0, y=0, id=None):
""" the init function """
super().__init__(id)
self.width = width
self.height = height
self.x = x
self.y = y
def int_validator(self, key, value):
""" the validator function """
if not isinstance(value, int):
raise TypeError(key + " must be an integer")
elif key == "width" or key == "height":
if value <= 0:
raise ValueError(key + " must be > 0")
elif key == "x" or key == "y":
if value < 0:
raise ValueError(key + " must be >= 0")
@property
def height(self):
"""height getter"""
return self.__height
@property
def width(self):
"""width getter"""
return self.__width
@property
def x(self):
"""x getter"""
return self.__x
@property
def y(self):
"""y getter"""
return self.__y
@height.setter
def height(self, value):
"""height setter"""
if type(value) is not int:
raise TypeError("height must be an integer")
if value <= 0:
raise ValueError("height must be > 0")
self.__height = value
@width.setter
def width(self, value):
"""width setter"""
if type(value) is not int:
raise TypeError("width must be an integer")
if value <= 0:
raise ValueError("width must be > 0")
self.__width = value
@x.setter
def x(self, value):
"""x setter"""
if type(value) is not int:
raise TypeError("x must be an integer")
if value < 0:
raise ValueError("x must be >= 0")
self.__x = value
@y.setter
def y(self, value):
"""y setter"""
if type(value) is not int:
raise TypeError("y must be an integer")
if value < 0:
raise ValueError("y must be >= 0")
self.__y = value
def area(self):
""" area function """
return self.__width * self.__height
def display(self):
""" display function """
if self.__y > 0:
print("\n" * (self.__y), end="")
for c in range(self.__height):
print(" " * self.__x + "#" * self.__width)
def __str__(self):
""" str function """
return (
"[Rectangle] (" + str(self.id) + ") " +
str(self.__x) + "/" + str(self.__y) + " - " +
str(self.__width) + "/" + str(self.__height)
)
def update(self, *args, **kwargs):
""" update function """
attributes = ['id', 'width', 'height', 'x', 'y']
if args:
for att, arg in zip(attributes, args):
setattr(self, att, arg)
elif kwargs:
for key, value in kwargs.items():
if key in attributes:
setattr(self, key, value)
def to_dictionary(self):
""" the dict function """
dict = {}
dict['id'] = self.id
dict['width'] = self.width
dict['height'] = self.height
dict['x'] = self.x
dict['y'] = self.y
return dict
|
2ca02a9db36617d0d668e31bbbff3380ce863838 | emna7/holbertonschool-higher_level_programming | /0x02-python-import_modules/100-my_calculator.py | 583 | 3.640625 | 4 | #!/usr/bin/python3
from sys import argv
from calculator_1 import add, sub, mul, div
if __name__ == "__main__":
if len(argv) != 4:
print("Usage: ./100-my_calculator.py <a> <operator> <b>")
quit(1)
a = int(argv[1])
b = int(argv[3])
operators = ["+", "-", "*", "/"]
functions = [add, sub, mul, div]
for i, op in enumerate(operators):
if argv[2] == op:
print("{} {} {} = {}".format(a, op, b, functions[i](a, b)))
break
else:
print("Unknown operator. Available operators: +, -, * and /")
quit(1)
|
01622f55a06ffd1f0e208816503eb6a0fb9bda87 | emna7/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 140 | 4.1875 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(my_dict):
for y in sorted(my_dict.keys()):
print("{}: {}".format(y, my_dict[y]))
|
e3a896d52f0d82f123bbc356a2a7265f7de95039 | buratina/Architecting-Scalable-Python-Applications | /Section 3/hash_stream.py | 686 | 3.515625 | 4 | # Code Listing #1
"""
Take an input stream and hash it's contents using MD5 and return the hash digest
"""
# hash_stream.py
from hashlib import sha1
from hashlib import md5
def hash_stream_sha1(stream, chunk_size=4096):
""" Hash a stream of data using sha1 """
shash = sha1()
for chunk in iter(lambda: stream.read(chunk_size), ''):
shash.update(chunk.encode('utf-8'))
return shash.hexdigest()
def hash_stream_md5(stream, chunk_size=4096):
""" Hash a stream of data using sha1 """
shash = md5()
for chunk in iter(lambda: stream.read(chunk_size), ''):
shash.update(chunk.encode('utf-8'))
return shash.hexdigest()
|
03ed31b49a395da0b6f58b93711419a3ab005e3c | allhailthetail/optics-cal | /python/tol-to-fringe.py | 840 | 3.8125 | 4 | #!/usr/bin/python
# Program to calculate fringes given a tolerance.
import math
#import pyperclip
print(
'''
Please Provide Information for the lens:
1. Radius
2. Clear Aperature
3. Given Tolerance
'''
)
# Normal Input:
radius = float(input('Radius?'))
ca = float(input('Clear Aperature?'))
# Three Decimal places for the given tolerance seems to work fine.
tol = float(input('Tolerance?'))
# wavelength:
''' Can change this if necessary, though it's
almost universally 632.8 nm because that's how the
zygo machines' lasers come configured.
'''
w = 632.8
# perform calculations:
res = (tol * 1e6 * (2 * abs(radius) - math.sqrt(4 * radius**2 - ca**2))) / (abs(radius) * w)
# print output:
res = round(res, 2)
print(res)
input()
#pyperclip.copy(round(res, 2))
|
1104189d6e3865a24ba56610dda1540b11420b20 | AnttiMinkkinen/Blob_goes_brr | /Blob_goes_brr!.py | 18,277 | 3.578125 | 4 | import pygame
from math import sqrt
from random import randint
class GoodGuy:
"""Player character. Defining color and starting size and location."""
def __init__(self):
self.color = (0, 100, 0)
self.color_fill = (0, 255, 0)
self.radius = 50
self.radius_fill = self.radius - 4
self.x = window_width/2 - self.radius
self.y = window_height/2 - self.radius
def give_coordinates(self):
return self.x, self.y
def give_center_x(self):
return self.x + self.radius
def give_center_y(self):
return self.y + self.radius
class BadGuy:
"""Enemy blobs. Defining color, size and starting location."""
def __init__(self):
self.color = (100, 0, 0)
self.color_fill = (255, 0, 0)
self.radius = randint(20, 30)
self.radius_fill = self.radius - 4
"""Enemy blobs can spawn from any direction of window and with variating speed.
1 is for left upper corner, 2 if for upper mid etc."""
starting_point = randint(1, 8)
if starting_point == 1:
self.x = randint(-50, 0) - self.radius
self.y = randint(-50, 0) - self.radius
self.x_speed = randint(10, 21) / 10
self.y_speed = randint(10, 21) / 10
elif starting_point == 2:
self.x = randint(0, 800) - self.radius
self.y = randint(-50, 0) - self.radius
self.x_speed = randint(-2, 2) / 10
self.y_speed = randint(10, 21) / 10
elif starting_point == 3:
self.x = randint(800, 850) - self.radius
self.y = randint(-50, 0) - self.radius
self.x_speed = randint(-21, -10) / 10
self.y_speed = randint(10, 21) / 10
elif starting_point == 4:
self.x = randint(-50, 0) - self.radius
self.y = randint(0, 800) - self.radius
self.x_speed = randint(10, 21) / 10
self.y_speed = randint(-2, 2) / 10
elif starting_point == 5:
self.x = randint(800, 850) - self.radius
self.y = randint(0, 800) - self.radius
self.x_speed = randint(-21, -10) / 10
self.y_speed = randint(-2, 2) / 10
elif starting_point == 6:
self.x = randint(-50, 0) - self.radius
self.y = randint(800, 850) - self.radius
self.x_speed = randint(10, 21) / 10
self.y_speed = randint(-21, -10) / 10
elif starting_point == 7:
self.x = randint(0, 800) - self.radius
self.y = randint(800, 850) - self.radius
self.x_speed = randint(-2, 2) / 10
self.y_speed = randint(-21, -10) / 10
elif starting_point == 8:
self.x = randint(800, 850) - self.radius
self.y = randint(800, 850) - self.radius
self.x_speed = randint(-21, -10) / 10
self.y_speed = randint(-21, -10) / 10
def give_coordinates(self):
return self.x, self.y
def give_center_x(self):
return self.x + self.radius
def give_center_y(self):
return self.y + self.radius
class Ammo:
"""Ammo that is shot by player character. Defining color, radius, starting location, speed and direction."""
def __init__(self, x, y, target_x, target_y):
self.color = (0, 100, 0)
self.color_fill = (0, 255, 0)
self.radius = 5
self.radius_fill = 4
self.x = x
self.y = y
self.target_x = target_x
self.target_y = target_y
self.x_speed = 0
self.y_speed = 0
def give_coordinates(self):
return self.x, self.y
class Sweet:
"""Blobs that can be collected. Created when enemy blob is hit with ammo.
Defining color, size, location and speed. Size, location and speed is got from original enemy blob."""
def __init__(self, x, y, x_speed, y_speed, radius):
self.color = (0, 100, 0)
self.color_fill = (0, 255, 0)
self.radius = radius
self.radius_fill = radius - 4
self.x = x
self.y = y
self.x_speed = x_speed
self.y_speed = y_speed
def give_coordinates(self):
return self.x, self.y
def does_bad_guy_hit(bad_guy: BadGuy, good_guy: GoodGuy):
"""Function that calculates if enemy blob hits player character."""
if sqrt((bad_guy.x - good_guy.x) ** 2 + (bad_guy.y - good_guy.y) ** 2) <= bad_guy.radius + good_guy.radius:
bad_guy_hits(bad_guy, good_guy)
def bad_guy_hits(bad_guy: BadGuy, good_guy: GoodGuy):
"""Function that defines what happens when enemy blob hits player character."""
bad_guy_list.remove(bad_guy)
good_guy.radius -= 15
good_guy.radius_fill -= 15
does_game_end(good_guy)
def does_ammo_hit(bad_guy: BadGuy, ammo: Ammo):
"""Function that calculates if ammo hits enemy blob."""
if sqrt((bad_guy.x - ammo.x) ** 2 + (bad_guy.y - ammo.y) ** 2) <= bad_guy.radius + ammo.radius:
ammo_hits(bad_guy, ammo)
def ammo_hits(bad_guy: BadGuy, ammo: Ammo):
"""Function that defines what happens when ammo hits enemy blob."""
try:
sweets_list.append(
Sweet(bad_guy.x, bad_guy.y, bad_guy.x_speed / 5, bad_guy.y_speed / 5, bad_guy.radius))
bad_guy_list.remove(bad_guy)
ammo_list.remove(ammo)
except ValueError:
pass
def does_sweet_hit(sweet: Sweet, good_guy: GoodGuy):
"""Function that calculates if sweet hits player character."""
if sqrt((sweet.x - good_guy.x) ** 2 + (sweet.y - good_guy.y) ** 2) <= sweet.radius + good_guy.radius:
sweet_hits(sweet, good_guy)
def sweet_hits(sweet: Sweet, good_guy: GoodGuy):
"""Function that defines what happens when sweet hits player character."""
good_guy.radius += 2
good_guy.radius_fill += 2
sweets_list.remove(sweet)
def does_game_end(good_guy: GoodGuy):
"""Function that checks if game is over."""
if good_guy.radius <= 7:
global game_over
game_over = True
def good_guy_speeds(good_guy_x, good_guy_y, mouse_x, mouse_y):
"""Function that calculates x and y speed vector. Sum of vectors is always 1. """
"""First calculations check if x or y vector is 0. If x or y are not 0 bot x and y vectors are calculated."""
if good_guy_x == mouse_x and good_guy_y == mouse_y:
returning_x_speed = 0
returning_y_speed = 0
elif good_guy_x == mouse_x:
returning_x_speed = 0
if good_guy_y > mouse_y:
returning_y_speed = -1
else:
returning_y_speed = 1
elif good_guy_y == mouse_y:
if good_guy_x > mouse_x:
returning_x_speed = -1
else:
returning_x_speed = 1
returning_y_speed = 0
else:
if good_guy_x > mouse_x and good_guy_y > mouse_y:
returning_x_speed = - sqrt(1 / (1 + ((good_guy_y - mouse_y) / (good_guy_x - mouse_x)) ** 2))
returning_y_speed = (good_guy_y - mouse_y) / (good_guy_x - mouse_x) * returning_x_speed
elif good_guy_x < mouse_x and good_guy_y > mouse_y:
returning_x_speed = sqrt(1 / (1 + ((good_guy_y - mouse_y) / (mouse_x - good_guy_x)) ** 2))
returning_y_speed = -(good_guy_y - mouse_y) / (mouse_x - good_guy_x) * returning_x_speed
elif good_guy_x > mouse_x and good_guy_y < mouse_y:
returning_x_speed = - sqrt(1 / (1 + ((mouse_y - good_guy_y) / (good_guy_x - mouse_x)) ** 2))
returning_y_speed = -(mouse_y - good_guy_y) / (good_guy_x - mouse_x) * returning_x_speed
else:
returning_x_speed = sqrt(
1 / (1 + ((mouse_y - good_guy_y) / (mouse_x - good_guy_x)) ** 2))
returning_y_speed = (mouse_y - good_guy_y) / (mouse_x - good_guy_x) * returning_x_speed
return returning_x_speed, returning_y_speed
def random():
"""Returns randomly true or false. Used for enemy blob spawn frequency. True = enemy spawn, false = no spawn."""
random_number = randint(1, 100)
if random_number < 6:
return True
return False
def app():
"""Application itself. First game is initialized."""
pygame.init()
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Blob goes brr!")
clock = pygame.time.Clock()
points = 0
target_x = window_width / 2 - player.radius
target_y = window_height / 2 - player.radius
counter = 0
score_printed = False
global game_over
"""Loop that keeps window refreshed."""
while True:
while not game_over:
window.fill((0, 0, 0))
"""Game button listeners. Esc = quit game, space = new game,
mouse1 = shoot to target location and mouse2 = move to target location."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit()
if event.key == pygame.K_SPACE:
bad_guy_list.clear()
ammo_list.clear()
sweets_list.clear()
player.radius = 50
player.radius_fill = 46
player.x = window_width / 2 - player.radius
player.y = window_height / 2 - player.radius
target_x = window_width / 2 - player.radius
target_y = window_height / 2 - player.radius
points = 0
game_over = False
break
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed(3)[2]:
target_x = event.pos[0]
target_y = event.pos[1]
if pygame.mouse.get_pressed(3)[0]:
ammo_x = event.pos[0]
ammo_y = event.pos[1]
ammo_list.append(Ammo(player.x, player.y, ammo_x, ammo_y))
ammo_list[-1].x_speed, ammo_list[-1].y_speed = \
good_guy_speeds(player.x, player.y, ammo_x, ammo_y)
player.radius -= 1
player.radius_fill -= 1
does_game_end(player)
"""Moves ammos on screen. Calculated before drawing every frame."""
for ammo in ammo_list:
if ammo.x < -50 or ammo.x > window_width + 50 or ammo.y < -50 or ammo.y > window_height + 50:
ammo_list.remove(ammo)
ammo.x += ammo.x_speed * 5
ammo.y += ammo.y_speed * 5
"""Initializes ammo render."""
pygame.draw.circle(window, ammo.color, ammo.give_coordinates(), ammo.radius)
pygame.draw.circle(window, ammo.color_fill, ammo.give_coordinates(), ammo.radius_fill)
"""Moves sweets on screen. Calculated before drawing every frame."""
for sweet in sweets_list:
sweet.x += sweet.x_speed
sweet.y += sweet.y_speed
if sweet.x < -50 or sweet.x > window_width + 50 or sweet.y < -50 or sweet.y > window_height + 50:
sweets_list.remove(sweet)
does_sweet_hit(sweet, player)
"""Initializes sweet render."""
pygame.draw.circle(window, sweet.color, sweet.give_coordinates(), sweet.radius)
pygame.draw.circle(window, sweet.color_fill, sweet.give_coordinates(), sweet.radius_fill)
"""Moves enemy blobs on screen. Calculated before drawing every frame."""
for bad_guy in bad_guy_list:
bad_guy.x += bad_guy.x_speed
bad_guy.y += bad_guy.y_speed
if bad_guy.x < -50 or bad_guy.x > window_width + 50 or bad_guy.y < -50 \
or bad_guy.y > window_height + 50:
bad_guy_list.remove(bad_guy)
does_bad_guy_hit(bad_guy, player)
"""Initializes enemy blob render."""
pygame.draw.circle(window, bad_guy.color, bad_guy.give_coordinates(), bad_guy.radius)
pygame.draw.circle(window, bad_guy.color_fill, bad_guy.give_coordinates(), bad_guy.radius_fill)
"""Checks if ammo hits enemy blob."""
for ammo in ammo_list:
does_ammo_hit(bad_guy, ammo)
"""Moves player character on screen. Calculated before drawing every frame."""
good_guy_x_speed, good_guy_y_speed = good_guy_speeds(player.x, player.y, target_x, target_y)
if not target_x - 1 < player.x < target_x + 1:
player.x += good_guy_x_speed
if not target_y - 1 < player.y < target_y + 1:
player.y += good_guy_y_speed
"""Initializes player character render."""
pygame.draw.circle(window, player.color, player.give_coordinates(), player.radius)
pygame.draw.circle(window, player.color_fill, player.give_coordinates(), player.radius_fill)
"""Checks if new enemy blob is added to game."""
if random():
bad_guy_list.append(BadGuy())
"""Player character loses size when time passes."""
counter += 1
if counter == 120:
player.radius -= 1
player.radius_fill -= 1
counter = 0
does_game_end(player)
"""Adds and initializes score render"""
points += 1
font = pygame.font.SysFont("comicsans", 32)
text = font.render(f"Points: {points//60}", True, (0, 200, 0))
window.blit(text, (window_width - 135, 10))
"""Initializes instructions render."""
font = pygame.font.SysFont("comicsans", 26)
text = font.render(
f"Mouse 1: Shoot Mouse 2: Move", False, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height - 30))
"""Renders initialized circles to window."""
pygame.display.flip()
clock.tick(60)
"""When game is over, game window is froze and score is shown."""
while game_over:
"""Listeners for player buttons. Esc = quit and space = new game."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit()
if event.key == pygame.K_SPACE:
bad_guy_list.clear()
ammo_list.clear()
sweets_list.clear()
player.radius = 50
player.radius_fill = 46
player.x = window_width / 2 - player.radius
player.y = window_height / 2 - player.radius
target_x = window_width / 2 - player.radius
target_y = window_height / 2 - player.radius
points = 0
game_over = False
break
"""Opens, reads and writes high score from score.txt."""
try:
with open("score.txt", "r") as file:
score = int(file.readline())
except IOError:
with open("score.txt", "w") as file:
file.write("0")
score = 0
"""Checks if new score if high score. Initializes score rendering."""
if score < points//60 and not score_printed:
font = pygame.font.SysFont("comicsans", 115)
text = font.render(f"NEW HIGH SCORE!", False, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, 100))
font = pygame.font.SysFont("comicsans", 60)
text = font.render(
f"Previous High score: {score}", False, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 - 30))
with open("score.txt", "w") as file:
file.write(str(points // 60))
score_printed = True
elif score >= points//60 and not score_printed:
font = pygame.font.SysFont("comicsans", 60)
text = font.render(
f"High score: {score}", False, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 - 30))
score_printed = True
"""Initializes instruction rendering."""
font = pygame.font.SysFont("comicsans", 120)
text = font.render(
f"Points: {points // 60}", False, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 - 130))
font = pygame.font.SysFont("comicsans", 50)
text = font.render(f"SPACE: New game", True, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 + 60))
text = font.render(f"ESC: Exit game", True, (0, 90, 20))
window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 + 100))
"""Renders initialized texts to window."""
pygame.display.flip()
clock.tick(60)
score_printed = False
"""Global variables used game."""
bad_guy_list = []
ammo_list = []
sweets_list = []
window_width = 800
window_height = 800
game_over = False
player = GoodGuy()
app()
|
a1c8f492f6782a3cbe6cb7fbe417c19b792e2206 | tech4GT/Pattern-Recognition-Lab | /gaussian.py | 318 | 3.96875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math
mu = int(input("Please enter the mean\n"))
variance = int(input("Please enter the variance\n"))
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()
|
4015f8de51d67ec5e32a0aeea0a35216d582c412 | brucecass/playground | /nthV2.py | 5,023 | 4.125 | 4 | #!/opt/local/bin/python
#
# Script name : nthV2.py
# Author : BDC
# Date : 05.10.15
# Description : play script in order to both try to learn a bit of python and to also try to
# hightlight how easy nth term ks3 maths is to Son
#
import sys
def all_same(items):
return all(x == items[0] for x in items)
def ask_ok(prompt, retries=4, complaint='s or e, please!'):
while True:
ok = input(prompt)
if ok in ('e', 'E'):
return True
if ok in ('s', 'S'):
return False
retries = retries - 1
if retries < 0:
raise OSError('uncooperative user')
print(complaint)
def main_loop():
if (ask_ok('Do you want to enter a [s]equence or an [e]quation? ')):
# value returned from prompt must be True which was an 'e' for equation
# therefore prompt user for an equation
#
equation = input('Tell me the equation ')
#
# validate the input and check it is ok equation, well at this point
# lets just check that there is a 'n' in the equation supplied
#
flag = False
for c in equation:
if c in 'n':
flag = True
if (flag):
# this might be a valid equation as it contains an 'n'
# replacing n and expanding out to full string
#
output_string = 'Sequence is '
# lets just assume that we will report back a sequence of 6 numbers max
#
for loop in range(1,6):
temp_str = ' * ' + str(loop)
# bit of string manipulation here: replacing the 'n' with a multiplication
# character and then adding a loop value after i.e. n = * 1 in the first
# iteration
#
new_equation = equation.replace('n',temp_str)
# building up the output sequence string by eval'ing (running the maths)
# and appending the result to the string that was generated the last time
# around the loop
#
try:
if (loop != 5):
output_string = output_string + str(eval(new_equation)) + ','
else:
output_string = output_string + str(eval(new_equation))
except:
# someone must have entered some text that could not be
# mathematically correct - maybe some text
#
print('**** ERROR: bad equation supplied ****\n')
break
# print the sequence of numbers calculated
#
print(output_string)
else:
# this is NOT a valid equation so need to bail out with an error msg
#
print('***Error: bad format of the equation: ',equation,' ***\n')
else:
# value returned from prompt must be False which was an 's' for sequence
# therefore prompt user for a sequence of numbers in a list
#
sequence = input('Give me a comma separated sequence ')
# validate the input and check it is an ok(ish) sequence of numbers, well at
# this point lets just check that there is one or more ',' in the sequence supplied
#
flag = False
for c in sequence:
if c in ',':
flag = True
if (flag):
try:
# this might be a valid sequence of numbers as it contains at least one comma
# next we need to split the sequence string into values
#
my_array = sequence.split(',')
# initiate an empty array/list so that we can add values to it
#
diff_value = []
# lets run through the array/list of values given to us and lets calculate the difference
# between each member of the sequence
#
for i in range(len(my_array)-1):
diff_value.insert(i,int(my_array[i+1])-int(my_array[i]))
# lets run through the array/list of values that have been calcuated between each supplied sequence
# number and lets check that they are all the same i.e. the sequence is a linear sequence
#
if all_same(diff_value):
# All items in the list are the same so we should be able to work out the nth term equation
# from all this and we should be able to calulate the 'offset' value
#
offset_value = int(my_array[0])-int(diff_value[0])
# print out the calculated equation
#
print('Equation is = %d' % diff_value[0],'n','%+d ' % offset_value,'\n')
else:
# hhhmm not all the values in the supplied sequence have the same difference
# So this is NOT a linear sequence and we need to bail out
#
print('***BAIL!! THERE\'S A VALUE IN THE LIST THAT ISN\'T THE SAME!!***\n\n')
except:
# someone must have entered some text that could not be
# mathematically correct - maybe some text
#
print('**** ERROR: bad sequence supplied ****\n')
else:
# this is NOT a valid sequence (or there isn't a comma found in the supplied sequence
# So need to bail out with an error msg
#
print('***Error: bad format of the sequence: ',sequence,' ***\n')
while True:
# infinate loops are bad
try:
# continue to execute the main loop of code until a control+C is hit
main_loop()
except KeyboardInterrupt:
# if we catch a control+C then bail out of the code completely
print('\n\nBye bye then...\n')
sys.exit()
|
57861ae83e1a21f39b3b996534f45acfd6620b45 | RayDiazVega/PF_Python | /ejemplo1.py | 1,419 | 3.5 | 4 | import os
import time
import threading
import multiprocessing
NUM_WORKERS = multiprocessing.cpu_count()
print("The number of workers is",NUM_WORKERS)
def only_sleep():
#Do nothing, wait for a timer to expire
print("PID: %s, Process Name: %s, Thread Name: %s" % (
os.getpid(),
multiprocessing.current_process().name,
threading.current_thread().name))
time.sleep(1)
def crunch_numbers():
#Do some computations
print("PID: %s, Process Name: %s, Thread Name: %s" % (
os.getpid(),
multiprocessing.current_process().name,
threading.current_thread().name))
x = 0
while x < 10000000: x += 1
for f in [only_sleep,crunch_numbers]:
print("\nTesting the funtion:",f.__name__)
# Run tasks serially
start_time = time.time()
for _ in range(NUM_WORKERS): f()
print("Serial time=", time.time() - start_time)
# Run tasks using threads
start_time = time.time()
threads = [threading.Thread(target=f) for _ in range(NUM_WORKERS)]
for thread in threads: thread.start()
for thread in threads: thread.join()
print("Parallel time=", time.time() - start_time)
# Run tasks using processes
start_time = time.time()
processes = [multiprocessing.Process(target=f) for _ in range(NUM_WORKERS)]
for process in processes: process.start()
for process in processes: process.join()
print("Concurrent time=", time.time() - start_time)
|
32f7523065558e174f904c617357c5012c663db0 | diwu1990/RAVEN | /pe/appr_utils.py | 2,089 | 3.609375 | 4 | import torch
import math
import matplotlib.pyplot as plt
class RoundingNoGrad(torch.autograd.Function):
"""
RoundingNoGrad is a rounding operation which bypasses the input gradient to output directly.
Original round()/floor()/ceil() opertions have a gradient of 0 everywhere, which is not useful
when doing approximate computing.
This is something like the straight-through estimator (STE) for quantization-aware training.
"""
# Note that both forward and backward are @staticmethods
@staticmethod
def forward(ctx, input, mode="round"):
if mode == "round":
return input.round()
elif mode == "floor":
return input.floor()
elif mode == "ceil":
return input.ceil()
else:
raise ValueError("Input rounding is not supported.")
# This function has only a single output, so it gets only one gradient
@staticmethod
def backward(ctx, grad_output):
grad_input = grad_output
return grad_input, None
def Trunc(input, intwidth=7, fracwidth=8, rounding="floor"):
"""
Trunc is an operation to convert data to format (1, intwidth, fracwidth).
"""
scale = 2**fracwidth
max_val = (2**(intwidth + fracwidth) - 1)
min_val = 0 - (2**(intwidth + fracwidth))
return RoundingNoGrad.apply(input.mul(scale), rounding).clamp(min_val, max_val).div(scale)
def Trunc_val(input, intwidth=7, fracwidth=8, rounding="round"):
"""
Trunc_val is an operation to convert one single value to format (1, intwidth, fracwidth).
"""
scale = 2**fracwidth
max_val = (2**(intwidth + fracwidth) - 1)
min_val = 0 - (2**(intwidth + fracwidth))
if rounding == "round":
return max(min(round(input*scale), max_val), min_val)/scale
elif rounding == "floor":
return max(min(math.floor(input*scale), max_val), min_val)/scale
elif rounding == "ceil":
return max(min(math.ceil(input*scale), max_val), min_val)/scale
else:
raise ValueError("Input rounding is not supported.")
|
da74ec82c7a56304bf9954cf881198ec978cf781 | bmart353011/Week12-utility | /week12-utility.py | 1,325 | 3.546875 | 4 | # Brendan Martin
# CSCI 102 - Section A
# Week 12 - Part A
import string
def PrintOutput(output):
print("OUTPUT", output)
def LoadFile(file_name):
with open(file_name) as file:
my_list = file.read().splitlines()
return my_list
def UpdateString(s1, s2, index):
my_list = list(s1)
my_list[index] = s2
PrintOutput("".join(my_list))
def FindWordCount(list1, word):
count = list1.count(word)
return count
def ScoreFinder(list1, list2, name):
name1 = name.upper()
my_list = []
for i in list1:
i = i.upper()
my_list.append(i)
if name1 in my_list:
index = my_list.index(name1)
score = list2[index]
print("OUTPUT", name, "got a score of", score)
else:
print("OUPUT player not found")
def Union(list1, list2):
my_list = []
my_list2 = []
my_list1= []
for i in list1:
if i not in my_list1:
my_list1.append(i)
for i in list2:
i = i.upper()
if i not in my_list2:
my_list2.append(i)
my_list = my_list1 + my_list2
return my_list
def Intersection(P1, P2):
my_list = P1 + P2
return my_list
def NotIn(list1, list2):
my_list = []
for i in list1:
if i not in list2:
my_list.append(i)
return my_list
|
1468f557e97a666849aafcd2841fc637b589f6db | Princess-Katen/hello-Python | /04:11:20_Dictionaries_Exercise1.py | 324 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 14:51:37 2020
@author: tatyanamironova
"""
# cat = {"name": "blue", "age": 3.5, "isCute": True}
# cat2 = dict(name="kitty", age=5)
user_info = {"who": "Katten", "what": "loves", "whom": "Medvezhaten"}
for v in user_info.values():
print(v)
|
7f3dc6666df5dbc8b2144dd22a4c175a299aa599 | Princess-Katen/hello-Python | /13:10:2020_Rock_Paper_Scissors + Loop _v.4.py | 1,696 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 13:18:18 2020
@author: tatyanamironova
"""
from random import randint
player_wins = 0
computer_wins = 0
winning_score = 3
while player_wins < winning_score and computer_wins < winning_score:
print (f'Player score: {player_wins} Computer score: {computer_wins}')
print('Rock...')
print('Paper...')
print('Scissors...')
player = input('(Player, make your move): ').lower()
if player == 'quit' or player == 'q':
break
rand_num = randint(0,2)
if rand_num == 0:
computer = 'rock'
elif rand_num == 1:
computer = 'paper'
else:
computer = 'scissors'
print(f'computer plays {computer}')
if player == computer:
print('Its a tie!')
elif player == 'rock':
if computer == 'scissors':
print('Player wins')
player_wins += 1
elif computer == 'paper':
print('computer wins')
computer_wins += 1
elif player == 'paper':
if computer == 'scissors':
print('computer wins')
computer_wins += 1
elif computer == 'rock':
print('Player wins')
player_wins += 1
elif player == 'scissors':
if computer == 'paper':
print('Player wins')
player_wins += 1
elif computer == 'rock':
print('computer wins')
computer_wins += 1
else:
print('something went wrong')
if player_wins > computer_wins:
print('Congrats,you won!')
elif player_wins == computer_wins:
print('Its a tie')
else:
print('Unfortunately, the computer won')
|
37d471c52427aa1af23476037ab9d4d45dad2c22 | Princess-Katen/hello-Python | /21:09:2020_Looping2.py | 193 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 16:26:47 2020
@author: tatyanamironova
"""
'''
r = range(10)
print(list(r))
'''
nums = range(1,10,2)
print(list(nums))
|
024041617a18f2ec2b6ca021d508b012c7a3ae6c | Princess-Katen/hello-Python | /16:11:20_Exercises_Dict_Comp.py | 583 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 13:30:04 2020
@author: tatyanamironova
"""
# list1 = ["CA", "NJ", "RI"]
# list2 = ["California", "New Jersey", "Rhode Island"]
# answer = {list1[i]: list2[i] for i in range(0,3)}
# print(answer)
## create a dictionary fron pairs of lists
##variant 1
# person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
# answer = dict(person)
# print(answer)
##variant 2
person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]]
answer = {thing[0]: thing[1] for thing in person}
print(answer) |
76a06af8da9d4aaab65f789c59f8df6abc8eec38 | Princess-Katen/hello-Python | /04:11:20_Dictionaries_Iteration.py | 404 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 14:51:37 2020
@author: tatyanamironova
"""
# user_info = {"who": "Katten", "what": "loves", "whom": "Medvezhaten"}
# for v in user_info.values():
# print(v)
# user_info = {"who": "Katten", "what": "loves", "whom": "Medvezhaten"}
# user_info.items()
# for k,v in user_info.items():
# print(f"key is {k} and value is {v}")
|
2eb9e68099b1fd7807e641bb3a9fd320a31fdffc | anmolaj/fansite-analytics-challenge | /src/process_log.py | 7,150 | 3.84375 | 4 |
#Importing libraries
import pandas as pd
import re
#Writing a function to clean our input log file and grab the required fields
def clean(line):
"""
input (str) : this is each line contained in the file to be processed
output : It returns a list of the required fields obtained froma a particular line
logic: We use various regular expressions to grab each desired element fromt he line
"""
#We set the regular expression pattern for each required field
requestMethodPattern='"([A-Z]*)\s.*"'
resourcePattern='"[A-Z]*\s*(.*).*"'
requestHttpPattern='"[A-Z]*\s*.*\s+([A-Z]{4}\/.*)"'
fullPattern='^(.*)\s+-\s+-\s+\[(.*)\s+(.*)\]\s+"[A-Z]*\s*.*"\s+(\d.*)?\s+(\d.*|-)$'
#We will make sure that the line is valid log field
try:
requestMethodFull=re.findall(requestMethodPattern,line)
requestMethod=[requestMethodFull if len(requestMethodFull)!=0 else ['']][0]
resourceFull=re.findall(resourcePattern,line)
resource,requestHttp=[resourceFull[0].split() if len(resourceFull[0].split())==2 else (resourceFull[0],'')][0]
full=re.findall(fullPattern,line)[0]
return [full[0],full[1],full[2],requestMethod[0],resource,requestHttp,full[3],full[4],line]
except:
return
def preProcess(data):
"""
input (list) : this is a list of values for each field
output : It returns a dataframe for where each row in the text file has been splitted to required fields
logic: We preprocess the data, by converting '-' to 0 in bytes ,change format of timestamp and bytes so that it becomes easier to analyse further
"""
headers=["host","timeStamp","timeZone","resourcesMethod","resourceUri","resourceHttp","httpResponse","bytes","original"]
dfNasa= pd.DataFrame(data,columns=headers)
dfNasa.loc[dfNasa.bytes== '-', 'bytes'] = 0
dfNasa["bytes"]=pd.to_numeric(dfNasa["bytes"])
dfNasa["timeStamp"]=pd.to_datetime(dfNasa["timeStamp"],format='%d/%b/%Y:%H:%M:%S')
return dfNasa
class Features:
"""
This class contains all features as a function.
"""
def __init__(self,dfNasa):
"""
input (dataFrame) : this is the dataframe over which we have to perform analysis
This initialisation is done to store the values which will be required in other feature methods
Assuming that there is only one timezone for such kind of activities and hence I am aextracting that and storing it
"""
self.dfNasa = dfNasa
self.TZ=dfNasa['timeZone'].unique()[0]
def feature1(self):
"""
This feature calculates the top 10 most active host/IP addresses that have accessed the site and stores it in hosts.txt
"""
file=open("./log_output/hosts.txt","w")
self.dfNasa['host'].value_counts()[:10].reset_index().to_csv(file,sep=',', index=False, header=False)
file.close()
def feature2(self):
"""
This feature calculates the 10 resources that consume the most bandwidth on the site and stores it in resources.txt
"""
file=open("./log_output/resources.txt","w")
bwConsumption=pd.DataFrame(self.dfNasa.groupby('resourceUri')['bytes'].agg(['sum'])).reset_index()
feature2=bwConsumption.sort_values("sum",ascending=False)[:10]
feature2['resourceUri'].to_csv(file,sep=' ',mode='a', index=False, header=False)
file.close()
def feature3(self):
"""
This feature calculates top 10 busiest (or most frequently visited) 60-minute periods and stores it in hours.txt
"""
file=open("./log_output/hours.txt","w")
countTS=self.dfNasa.sort_values(['timeStamp']).groupby(['timeStamp'])['timeStamp'].agg(['count'])
countTS=countTS.reindex(pd.date_range(min(countTS.index),max(countTS.index),freq='s'), fill_value=0)
# if the length is only less than 10 then no point doing extra stuff
if len(countTS)<=10:
countTS.reset_index().to_csv(file,mode='a',sep=',', index=False, header=False)
#else we will perform a rolling sum starting from the first position
else:
finalCount=countTS[::-1].rolling(window=3600, min_periods=0).sum()[::-1].sort_values(['count'],ascending=False)[:10].reset_index()
finalCount['count']=finalCount['count'].astype(int)
finalCount.to_csv(file,mode='a',sep=',', index=False, header=False)
file.close()
def feature4(self):
"""
this feature detect patterns of three failed login attempts from the same IP address over 20 seconds so that all further attempts to the site can be blocked for 5 minutes. Log those possible security breaches.
"""
file=open("./log_output/blocked.txt","w")
dfNasa=self.dfNasa.copy()
dfNasa.sort_values(["host","timeStamp"],inplace=True)
#This logic helps to flag (1) those entries which was a 3rd consecutive failed attemp within 20 second
dfNasa["failed3"]=[1 if http1=='401'and http2=='401' and http3=='401' and x==y and t2-t1<=pd.to_timedelta("20s") else 0 for http1,http2,http3,x,y,t1,t2 in zip(dfNasa["httpResponse"],dfNasa["httpResponse"].shift(1),dfNasa["httpResponse"].shift(2),dfNasa["host"],dfNasa["host"].shift(2),dfNasa["timeStamp"],dfNasa["timeStamp"].shift(2))]
#Setting index as host helps to slice the datadrame by hosts quickly
dfNasa.set_index('host',inplace=True)
hosts=dfNasa[(dfNasa.failed3==1)].index.unique()
#This loops only goes through hosts which have had 3 consecutive failed attempts
for ht in hosts:
#We will now create a dataframe for the current host being considered
hostSub=dfNasa.loc[ht].reset_index(col_fill='host')
# we will keep a track of the index where the 3rd consecutive failed attempt was
ind=hostSub[hostSub.failed3==1].index
#We will loop through each host for every 5 minutes until all th epoints have been examined
while(True):
temp=hostSub.timeStamp[ind[0]]
hostSub=hostSub[ind[0]+1:]
indEnd =hostSub[(hostSub.timeStamp<=temp+pd.to_timedelta("300s"))][-1:].index[0]
tuples=hostSub[hostSub.index.values<=indEnd]["original"]
for line in tuples:
file.write(line)
if (indEnd==len(hostSub) or sum(hostSub.failed3[indEnd+1:])==0 ):
break
ind=ind[1:]
file.close()
"""
Now we execute according to our requirements
"""
#We have to make sure that input is correctly taken
try:
#I use Imap function because it is faster as compared to list comprehension
dfNasaMain=preProcess(map(clean,open("./log_input/log.txt","r")))
except:
print "Please check if file is present in /log_input"
#We create an object for feature and then execute for each of the feature required
feature=Features(dfNasaMain.copy())
feature.feature1()
feature.feature2()
feature.feature3()
feature.feature4()
|
6f6830437b7ced47cae83ad94da9c51572deefcc | oscarsun95/CodilitySolutions_Oscar | /ladder.py | 362 | 3.640625 | 4 | def fibonacci(N):
fib = [0] * N
fib[0] = 1
fib[1] = 1
for i in range(2, N):
fib[i] = fib[i-1] + fib[i-2]
return fib
def solution(A, B):
# write your code in Python 3.6
M = max(A)
fib = fibonacci(M+1)
N = len(A)
res = [0] * N
for i in range(N):
res[i] = fib[A[i]] & ((1 << B[i]) - 1)
return res |
2ddaae1473bf97a58f0b14606208bfbdeef90f49 | clarissabailarina/aprendizado | /operacoes.py | 229 | 3.96875 | 4 | """Este programa fara a soma, subtracao e divisao de varios numeros"""
a = 4
b = 3
print('a soma de a e b e: ' + str(a + b))
print('a multiplicacao de a e b e: ' + str(a * b))
print('a subtracao de a e b e: ' + str(a - b)) |
85839b4d55ce0a406a14b26b6366a931c5fb4ce0 | Jhawk1196/CS3250PythonProject | /src/fontSelect.py | 855 | 3.796875 | 4 | def font_style(
custom_font, font):
"""
Changes font family
:param custom_font: font used by Message in Tkinter GUI
:param font: font the user selects
:return: font used by GUI
"""
custom_font.config(family=font)
return custom_font
def font_size(
custom_font, f_size):
"""
Changes font size
:param custom_font: font used by Message in Tkinter GUI
:param f_size: font size the user selects
:return: font used by GUI
"""
custom_font.config(size=f_size)
return custom_font
def font_color(
label, f_color):
"""
Changes font color in Message object attached to GUI
:param label: font used by Message in Tkinter GUI
:param f_color: font color the user selects
:return: label with new font color
"""
label.config(fg=f_color)
return label
|
e35614c31409fe9144bc7695ee3249a752fd527a | prateek-chawla/DailyCodingProblem | /Solutions/Problem_114.py | 583 | 3.859375 | 4 | def reverseWords(inp):
i, j = 0, len(inp)-1
lDelim, rDelim = ' ', ' '
while(i <= j):
# print("hello")
if inp[i].isalpha() and inp[j].isalpha():
i += 1
j -= 1
elif not inp[i].isalpha():
while i <= j and not inp[i].isalpha():
lDelim += inp[i]
i += 1
elif not inp[j].isalpha():
while(j>=i and not inp[j].isalpha):
rDelim += inp[j]
j -= 1
else:
print(inp[i],inp[j])
inp = "hello/world:here"
reverseWords(inp)
|
556c8b35139d8948b0c218579785dd640b57acde | prateek-chawla/DailyCodingProblem | /Solutions/Problem_120.py | 1,456 | 4.1875 | 4 | '''
Question -->
This problem was asked by Microsoft.
Implement the singleton pattern with a twist. First, instead of storing one instance,
store two instances. And in every even call of getInstance(), return the
first instance and in every odd call of getInstance(), return the second instance.
Approach -->
Create two instances and a flag to keep track of calls to getInstance()
Raise Exception on invalid instantiation
'''
class Singleton:
first_instance = None
second_instance = None
evenFlag = False
def __init__(self):
if Singleton.first_instance is not None and Singleton.second_instance is not None:
raise Exception(" This is a Singleton Class ")
else:
if Singleton.first_instance is None:
Singleton.first_instance = self
else:
Singleton.second_instance = self
@staticmethod
def getInstance():
if Singleton.first_instance is None or Singleton.second_instance is None:
Singleton()
else:
if Singleton.evenFlag:
Singleton.evenFlag = not Singleton.evenFlag
return Singleton.first_instance
else:
Singleton.evenFlag = not Singleton.evenFlag
return Singleton.second_instance
obj1 = Singleton.getInstance()
obj2 = Singleton.getInstance()
obj3 = Singleton.getInstance()
print(obj3)
obj4 = Singleton.getInstance()
print(obj4)
|
14964f7ecbb0c39de4336bab70204958e11aa047 | prateek-chawla/DailyCodingProblem | /Solutions/Problem_116.py | 1,171 | 3.953125 | 4 | '''
Question -->
This problem was asked by Jane Street.
Generate a finite, but an arbitrarily large binary tree quickly in O(1).
That is, generate() should return a tree whose size is unbounded but finite.
Approach -->
Use python lazy properties to generate a tree
Node's left and right are only computed the first time they are accessed,
after that they are stored to prevent repeated evaluations
Reference --> https://stevenloria.com/lazy-properties/
'''
from random import random
NODE_DATA = 0
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.isLeftEvaluated = False
self.isRightEvaluated = False
@property
def left(self):
if not self.isLeftEvaluated:
if random() < 0.5:
self.left = Node(NODE_DATA)
self.isLeftEvaluated = True
return self.left
@property
def right(self):
if not self.isRightEvaluated:
if random() < 0.5:
self.right = Node(NODE_DATA)
self.isRightEvaluated = True
return self.right
def generate():
return Node(NODE_DATA)
|
a72e6635f6b8b8a2d44855fd4ce8a476759c20e1 | alsoamit/Python-IITK-Workshop-Files | /Day1/P14.py | 177 | 3.515625 | 4 | # P14
def main():
s = int(input())
h=s//3600
m=(s%3600)//60
s=(s%3600)%60
print("{}:{}:{}".format(h,m,s))
if __name__ == "__main__":
main() |
5de889cd0b58f66572c510b0199b2df2f36b34f0 | alsoamit/Python-IITK-Workshop-Files | /Day3/P32.py | 455 | 4 | 4 | # P32
def main():
# Take the input
string = input()
# Check if "bad" exists
if string.find("bad") != -1:
# Check if "not" is before "bad"
if string.find("not") < string.find("bad"):
part1 = string.split('not')[0]
part2 = string.split('bad')[1]
print(part1 + "good" + part2)
else:
print(string)
else:
print(string)
if __name__ == "__main__":
main()
|
9cfb3bc8d97e5bed4b0b43f7d2dd9a87f192b889 | alsoamit/Python-IITK-Workshop-Files | /Day4/P44.py | 246 | 3.609375 | 4 | # P44
def RecSum(n):
if n <= 9 and n >= 0:
return n
s = 0
for i in str(n):
s += int(i)
return RecSum(s)
def main():
#take input
n = int(input())
print(RecSum(n))
if __name__ == "__main__":
main() |
2d73419d6d19a82b5d8b254a9ead8f89f3c71662 | alsoamit/Python-IITK-Workshop-Files | /Day4/P42.py | 1,928 | 3.734375 | 4 | # P42
quiz_max, exam_max, assignment_max, project_max = 20, 100, 100, 50
def inputCheck(type, type_max):
# Checking input
if type > type_max:
return ("ERROR: Invalid Marks {} > {}".format(type, type_max))
elif type < 0:
return ("ERROR: Invalid Marks {} < {}".format(type, 0))
def read_marks():
# Take and check inputs for the four assessments
quiz = int(input())
test = inputCheck(quiz, quiz_max)
if test:
print(test)
return
exam = int(input())
test = inputCheck(exam, exam_max)
if test:
print(test)
return
assignment = int(input())
test = inputCheck(assignment, assignment_max)
if test:
print(test)
return
project = int(input())
test = inputCheck(project, project_max)
if test:
print(test)
return
return [quiz, exam, assignment, project]
# computing GPA of the valid marks
def compute_gpa(quiz,exam,assignment,project):
quiz_wei, exam_wei, assignment_wei, project_wei = 15, 40, 20, 25
return ((quiz / quiz_max)*quiz_wei + (exam / exam_max)*exam_wei + (assignment / assignment_max)*assignment_wei + (project / project_max)*project_wei)/10
# assigning grade according to the GPA
def assign_grade(gpa):
if gpa == 10:
return "O"
elif gpa >= 9 and gpa < 10:
return "A"
elif gpa >= 8 and gpa < 9:
return "B"
elif gpa >= 6.5 and gpa < 8:
return "C"
elif gpa >= 5 and gpa < 6.5:
return "D"
elif gpa < 5:
return "F"
def main():
# take input and call functions
inputs = read_marks()
if inputs:
quiz, exam, assignment, project = read_marks()
else:
return
gpa = round(compute_gpa(quiz, exam, assignment, project), 2)
grade = assign_grade(gpa)
print("The GPA IS {}, and the Grade is {}".format(gpa, grade))
if __name__ == "__main__":
main()
|
94f45d00da655948c4efacef3f1918ee06fadc36 | evmaksimenko/python_algorithms | /lesson1/ex9.py | 480 | 4.4375 | 4 | # Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
c = int(input("Введите третье число: "))
r = a
if a < b < c or c < b < a:
r = b
if a < c < b or b < c < a:
r = c
print("Среднее число %d" % r)
|
40c7b3a00d05e1618a7a9bc16543e28d8ca048d0 | evmaksimenko/python_algorithms | /lesson1/ex7.py | 1,096 | 4.40625 | 4 | # По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить,
# является ли он разносторонним, равнобедренным или равносторонним.
a = int(input("Введите первую сторону: "))
b = int(input("Введите вторую сторону: "))
c = int(input("Введите третью сторону: "))
if a < b + c and b < a + c and c < a + b:
if a == b == c:
print("Треугольник равносторонний")
elif a == b or a == c or b == c:
print("Треугольник равнобедренный")
else:
print("Треугольник разносторонний")
else:
print("Треульгольник с такими сторонами не может существовать")
|
8e5c8f5ee8b8540d1c9d91dee38b44d67da57580 | franky-codes/Py4E | /Ex6.1.py | 433 | 4.375 | 4 | #Example - use while loop to itterate thru string & print each character
fruit = 'BANANA'
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
#Exercise - use while loop to itterate thru string backwards
fruit = 'BANANA'
index = -1 # because len(fruit) - 1 is the last index in the string_x
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index - 1
|
0c514c1be8e3fa34e109b2dd0ff7fe1f7c699160 | JoaoPauloPereirax/Python-Study | /Mundo2/WHILE/while011.py | 1,164 | 3.9375 | 4 | '''Faça um programa que jogue par ou ímpar com o computador. O jogo será encerrado quando o jogador PERDER, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo. '''
from random import randint
computador=0
vitorias=0
while True:
jogador=str(input('Par ou ímpar(P/I): ')).upper()
if jogador==('I'):
computador=randint(1,11)
numero=int(input('Digite um número: '))
if (numero+computador)%2==1:
print('Você venceu!\nVocê {} x {} Computador'.format(numero,computador))
vitorias+=1
else:
print('Você perdeu!\nVocê {} x {} Computador'.format(numero,computador))
break
elif jogador=='P':
computador=randint(1,2)
numero=int(input('Digite um número: '))
if (numero+computador)%2==0:
print('Você venceu!\nVocê {} x {} Computador'.format(numero,computador))
vitorias+=1
else:
print('Você perdeu!\nVocê {} x {} Computador'.format(numero,computador))
break
else:
print('Opção inválida!')
print('Total de vitórias consecutivas: {}'.format(vitorias)) |
8e447141bae311f753957bbb453083c485694a0d | JoaoPauloPereirax/Python-Study | /Mundo2/WHILE/while003.py | 1,146 | 4.25 | 4 | '''Crie um programa que leia dois valores e mostre um menu na tela
[1] Somar
[2] Multiplicar
[3] Maior
[4] Novos números
[5] Sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.'''
valor1=int(input('Digite o valor1: '))
valor2=int(input('Digite o valor2: '))
escolha=0
while escolha!=5:
escolha=int(input('ESCOLHA A OPÇÃO DESEJADA\n[1]Somar\n[2]Multiplicar\n[3]Maior\n[4]Novos números\n[5]Sair'))
if escolha==1:
print('\n{}+{}={}\n'.format(valor1,valor2,valor1+valor2))
elif escolha==2:
print('\n{}x{}={}\n'.format(valor1,valor2,valor1*valor2))
elif escolha==3:
if valor1==valor2:
print('São iguais!')
else:
if valor1>valor2:
print('Entre {} e {} o maior é {}'.format(valor1,valor2,valor1))
else:
print('Entre {} e {} o maior é {}'.format(valor1,valor2,valor2))
elif escolha==4:
valor1=int(input('Digite o valor1: '))
valor2=int(input('Digite o valor2: '))
elif escolha==5:
print('Fim do programa!')
else:
print('Opção inválida!')
|
e8309ecf0e484b9ffcffc02dda25e9af28c8cca1 | JoaoPauloPereirax/Python-Study | /Mundo2/WHILE/while001.py | 296 | 4.125 | 4 | '''Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' e 'F'. Caso esteja errado, peça a digitação novamente até ter um valor correto.'''
sexo='a'
while (sexo.upper()!='M' or sexo.upper()!='F'):
sexo=str(input('Digite seu sexo(m/f): '))
print('Fim do programa') |
47553ba19892329d2a81aa710376ab378aee5a20 | JoaoPauloPereirax/Python-Study | /Mundo2/WHILE/while007.py | 304 | 4.09375 | 4 | '''Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros termos de uma sequência de fibonacci.'''
n=int(input('Digite um número: '))
anterior=1
atual = 0
cont=1
while cont!=n:
print(atual)
atual+=anterior
anterior=atual-anterior
cont+=1
print(atual) |
40f3df0f533c2b2102e04bcbcb7987b59b4873df | JoaoPauloPereirax/Python-Study | /Mundo2/IF/ex0007.py | 805 | 3.953125 | 4 | '''
Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu IMC e mostre seu status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do peso.
- Entre 18.5 e 25: Peso ideal.
- Entre 25 e 30: Sobrepeso.
- Entre 30 e 40: Obesidade.
- Acima de 40: Obesidade Mórbida.
'''
peso=float(input('Digite o peso: '))
if peso<0:
print('valor inválido')
else:
altura=float(input('Digite a altura: '))
if altura<0:
print('valor inválido')
else:
imc=peso/(altura**2)
if imc<18.5:
print('Abaixo do peso.')
elif 18.5<=imc<25:
print('Peso ideal.')
elif 25<=imc<30:
print('Sobrepeso')
elif 30<=imc<40:
print('Obesidade')
else:
print('Obesidade Mórbida') |
c958ea3e1169ff4cc63527450ea930bb2c10fecc | JoaoPauloPereirax/Python-Study | /Mundo2/FOR/Estrutura_For.py | 155 | 3.890625 | 4 | for variavel1 in range(1,6,1):#contagem até 5
print(variavel1)
print('\n')
for variavel2 in range(5,0,-1):#contagem ao contrário
print(variavel2) |
3365f9d6d1cece7c83a21e4a34e80030e59c9d81 | cammbyrne/Homework2 | /RetirementTest.py | 729 | 3.53125 | 4 | from RetirementCalc import retirementCalc
import unittest
class RetirementTest(unittest.TestCase):
def retirementCalcTest(self):
agemet = retirementCalc(25, 6500, .5, 150000)
self.assertEqual(agemet, (59.0, False))
agemet = retirementCalc(10, 5, .1, 1000000)
self.assertEqual(agemet,(1481491.0, True))
agemet = retirementCalc(50, 100000, .4, 1500000)
self.assertEqual(agemet,(78.0, False))
agemet = retirementCalc(50, 100000, .4, 2700000)
self.assertEqual(agemet,(100.0, True))
agemet = retirementCalc(50, 100000, .4, 2650000)
self.assertEqual(agemet,(99.0, False))
if __name__ == '__main__':
unittest.main() |
0f2ec4c6c12bbd4f53deca24ba9d265c59e50c31 | iulihardt/pythonCodes | /Pythons/recognize.py | 864 | 3.765625 | 4 | import speech_recognition as sr
#Funcao que converte fala em texto.
def voz_to_text():
microfone = sr.Recognizer() #identifica o microfone
with sr.Microphone() as source:
microfone.adjust_for_ambient_noise(source) #aplica módulo de reduçao de ruido
print("Diga alguma coisa: ") #solicita para falar e ouvir o microfone
audio = microfone.listen(source)
try:
frase = microfone.recognize_google(audio,language="pt-BR") #transcreve o som para Portugues BR
print(frase) #printa na tela a frase
except sr.UnknownValueError:
print("Nao rolou") #ou retorna erro
return frase
voz_to_text()
#proximos passos
"""
1) ler arquivos .mp3, .mp4 ...
2) Converter o audio do arquivo em .csv
3) funçao loop numa pasta com N audios
4) aplicar closterizaçao de textos e ML no csv ou APLICAR num BI
""" |
44e4a9c5c57a9e799d7933573cea95fb3501d884 | ivanakonatar/Homework04 | /zad6.py | 219 | 3.625 | 4 | #za dati broj vratiti listu pozicija na kojima se pojavljuje u proslijedjenom nizu
niz=[1,2,3,4,5,3,7,7]
broj=3
pozicije=[]
for i in range(len(niz)):
if niz[i] == broj:
pozicije.append(i)
print(pozicije) |
542c87a9db36ea07387fec814dd57a0d8a6a73cf | KirillKatranov/hw_python_oop-master | /homework.py | 3,628 | 3.71875 | 4 | import datetime as dt
class Record:
def __init__(self, amount, comment, date=None):
self.amount = amount
self.comment = comment
if type(date) is str:
self.date = dt.datetime.strptime(date, '%d.%m.%Y').date()
else:
self.date = dt.date.today()
class Calculator:
def __init__(self, limit):
self.limit = limit
self.records = []
def add_record(self, record):
"""Add a new record.
Keyword arguments:
record -- object of tipe Record
"""
self.records.append(record)
def get_today_stats(self):
"""Calculate how much money or calories spent today."""
date_today = dt.date.today()
return sum(record.amount for record in self.records
if record.date == date_today)
def get_week_stats(self):
"""Calculate how much money or calories spent last week."""
seven_days_period = dt.timedelta(days=7)
date_today = dt.date.today()
return sum(record.amount for record in self.records
if date_today - seven_days_period <= record.date <= date_today)
def calculate_remaind(self):
"""Calculate remaind for today"""
today_spend = self.get_today_stats()
return self.limit - today_spend
class CaloriesCalculator(Calculator):
def get_calories_remained(self):
"""Determine how many calories can to get today."""
remaind = self.calculate_remaind()
return ('Сегодня можно съесть что-нибудь ещё,'
+ f' но с общей калорийностью не более {remaind} кКал'
if remaind > 0 else 'Хватит есть!')
class CashCalculator(Calculator):
USD_RATE = 76.34
EURO_RATE = 89.90
def convert_remaind(self, currency, remaind):
"""Do currency conversion.
Keyword arguments:
currency -- name currency, may be "rub", "usd" or "eur"
"""
exchange_rates = {
'usd': {'name': 'USD', 'value': self.USD_RATE},
'eur': {'name': 'Euro', 'value': self.EURO_RATE},
'rub': {'name': 'руб', 'value': 1}
}
if currency in exchange_rates:
remaind /= exchange_rates[currency]['value']
name_currency = exchange_rates[currency]['name']
else:
raise NameError('Unknown currency')
return remaind, name_currency
def get_today_cash_remained(self, currency):
"""Determine how many money can to get today.
Keyword arguments:
currency -- name currency, may be "rub", "usd" or "eur"
"""
remaind = self.calculate_remaind()
if remaind == 0:
return 'Денег нет, держись'
remaind, currency = self.convert_remaind(currency, remaind)
if remaind > 0:
round_remaind = round(remaind, 2)
return f'На сегодня осталось {round_remaind} {currency}'
round_remaind = round(abs(remaind), 2)
return ('Денег нет, держись: твой долг - '
+ f'{round_remaind} {currency}')
class Record:
def __init__(self, amount, comment, date=None):
self.amount = amount
self.date = (dt.datetime.strptime(date, '%d.%m.%Y').date()
if type(date) is str else dt.date.today())
self.comment = comment
|
a1d9320dd8b18e908293e154403bf4c631c49b21 | Anushad4/Python-Deeplearning | /ICP1/reversing a string.py | 374 | 4.15625 | 4 | #def reverse(string):
# string = string[::-1]
# return string
#s = "Anusha"
#s = input()
#print(s)
#print(reverse(s[2::]))
lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = input()
lst.append(ele)
a = ""
for j in lst:
a += j
print(a)
def reverse(string):
string = string[::-1]
return string
print(reverse(a[2::]))
|
1d0e46aa84b87da5c2d417517b11bff21a5c1e01 | Anushad4/Python-Deeplearning | /ICP4/2.py | 1,028 | 3.5625 | 4 | #importing data#
import pandas as pd
glass_data = pd.read_csv('glass.csv')
#Preprocessing data
x=glass_data.drop('Type',axis=1)
y=glass_data['Type']
#Splitting Data#
# Import train_test_split function
from sklearn import model_selection
# Split dataset into training set and test set
X_train, X_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.2,random_state=0) # 70% training and 30% test
#Model Generation#
#Import Gaussian Naive Bayes model#
from sklearn.naive_bayes import GaussianNB
#Create a Gaussian Classifier#
model = GaussianNB()
#Train the model using the training sets#
model.fit(X_train, y_train)
#Predict the response for test dataset#
y_pred = model.predict(X_test)
#Evaluating the model#
from sklearn import metrics
# Model Accuracy, how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
print("classification_report\n",metrics.classification_report(y_test,y_pred))
#print("confusion matrix\n",metrics.confusion_matrix(y_test,y_pred)) |
81f95bd75db65db8d3377b220ca0a94f7aea2418 | gpizzigh/aula_git | /Aluno1.py | 201 | 3.875 | 4 | n=int(input("Digite o maximo de numeros:"))
def ler_numeros(n):
l=[]
for i in range(n):
x=float(input("Digite os numeros:"))
#l=[]
l.append(x)
i=i+1
return l
print(ler_numeros(n))
|
9ceb8c4bf65b297a13a57ca2da6196ea34b5dfd7 | 1234doraver/ERGASIES-PYTHON | /ERGASIA1.PY | 1,642 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Ανοιγουμε το αρχειο και αποθηκευουμε ολο το κειμενο σε μια μεταβλητη
import os
fin=open("text.txt","r")
text=fin.read()
fin.close()
#Αφαιρουμε τα πολλαπλα κενα
text=os.linesep.join([s.strip() for s in text.splitlines() if s])
text=" ".join([s.strip() for s in text.split(" ") if s])
#Χωριζουμε το κειμενο σε λεξεις
words=text.split()
#Φτιαχνουμε λιστα που περιεχει τις λεξεις και το μηκος τους και μετα τις ταξινομω με βαση αυτο
w=[(len(wrd),wrd) for wrd in words]
w.sort(reverse=True)
#Τοποθετω σε μεταβλητες τις 5 μεγαλυτερες μαζι με το μηκος τους
a=w[0]
b=w[1]
c=w[2]
d=w[3]
e=w[4]
#Υστερα διατηρω σε μεταβλητες μονο τις λεξεις
A= (a[1])
B= (b[1])
C= (c[1])
D= (d[1])
E= (e[1])
#Αναποδογυριζω τις λεξεις
A=A[::-1]
B=B[::-1]
C=C[::-1]
D=D[::-1]
E=E[::-1]
#Δημιουργω λιστα με τα φωνηεντα
Vowels= ('a', 'e', 'i', 'o', 'u','A','E','I','O','U')
#Για καθε μια απο τις 5 μεγαλυτερες λεξεις αφαιρω τα φωνηεντα που περιεχουν και τις εμφανιζω
for x in A:
if x in Vowels:
A = A.replace(x, '')
print (A)
for x in B:
if x in Vowels:
B=B.replace(x,'')
print (B)
for x in Vowels:
C=C.replace(x,'')
print (C)
for x in Vowels:
D=D.replace(x,'')
print(D)
for x in Vowels:
E=E.replace(x,'')
print(E)
|
4be6ec0e941d20b3dd48ec0716ffada5dacf1ce3 | sianux1209/algorithm_study | /BAEKJOON/music_scale.py | 230 | 3.78125 | 4 | # https://www.acmicpc.net/problem/2920
scale = ["1 2 3 4 5 6 7 8", "8 7 6 5 4 3 2 1"]
input = raw_input()
if input == scale[0]:
print "ascending"
elif input == scale[1]:
print "descending"
else:
print "mixed" |
1a6ff0b59d09d28340cf632ab45ba21c5e55ef41 | DhanyaMohandas/Basic-Python | /sumofseries.py | 74 | 3.546875 | 4 | n=input('Enter a number=')
print 'Sum of Series=' , n + n * n + n * n * n
|
187b7542fb5bdca5f1261a2aacdc5120988e2a44 | mcmk21348/task06.04.2020 | /Task_2.py | 399 | 3.859375 | 4 | """
@Makers
Write a function square_number that
takes in a number and squares it.
"""
def square_number(number):
return number ** 2
#DO NOT remove lines below here, this is designed to test your code.
def test_square_number():
assert square_number(2) == 4
assert square_number(8) == 64
assert square_number(10) == 100
print("YOUR CODE IS CORRECT!")
test_square_number() |
9dcddbcc8d5d3f81e9b43c1b674bb99bf74081e6 | LukazDane/CS-1.3 | /bases/bases.py | 4,209 | 4.25 | 4 | import string
import math
# ##### https://en.wikipedia.org/wiki/List_of_Unicode_characters
# Hint: Use these string constants to encode/decode hexadecimal digits and more
# string.digits is '0123456789'
# string.hexdigits is '0123456789abcdefABCDEF'
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters is ascii_lowercase + ascii_uppercase
# string.printable is digits + ascii_letters + punctuation + whitespace
def decode(digits, base):
decoded = []
"""Decode given digits in given base to number in base 10.
digits: str -- string representation of number (in given base)
base: int -- base of given number
return: int -- integer representation of number (in base 10)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= 36, 'base is out of range: {}'.format(base)
# TODO: Decode digits from binary (base 2)
ndec = 0
digits = digits[::-1]
# if base == 2:
for i in range(len(digits)):
digit = int(digits[i], base=base)
ndec += digit * base ** i
return ndec
# elif base == 16:
# x = int(str(digits), 16)
# print(x)
# else:
# reverse the digits
# digits = digits[::-1]
# # print(digits)
# # variable to hold our answer
# num = 0
# # loop through each index
# for x in range(len(digits)):
# # variable to hold each index while we work it out
# uni = digits[x]
# if uni.isdigit():
# # if already a number (0-9) keep it
# uni = int(uni)
# # print(uni)
# else: # assumes alphabet
# # convert to unicode uppercase val, subtract calue of A and add 10 to get base 10 number
# uni = ord(uni.upper())-ord('A')+10
# # unicode a -> A = 65 | A(65) - A(65) + 10 = 10(a)
# # unicode b -> B = 66 | B(66) - A(65) + 10 = 11(b)
# # print(uni)
# num += uni*(base**x)
# decoded.append(num)
# print(decoded)
print(decode('1110 1100', 2))
print(decode('fff', 16))
print(decode("1a2b", 32))
def encode(number, base):
"""Encode given number in base 10 to digits in given base.
number: int -- integer representation of number (in base 10)
base: int -- base to convert to
return: str -- string representation of number (in given base)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base <= 36, 'base is out of range: {}'.format(base)
# Handle unsigned numbers only for now
assert number >= 0, 'number is negative: {}'.format(number)
# https://stackoverflow.com/questions/1181919/python-base-36-encoding
base_36 = string.digits + string.ascii_uppercase
result = []
while number > 0:
q = number / base
remainder = number % base
sep_q = str(q).split(".")
number = int(sep_q[0])
if 9 < remainder < base:
remainder = base_36[remainder].lower()
result.insert(0, str(remainder))
return "".join(result)
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 36 [0-9a-z]
assert 2 <= base1 <= 36, 'base1 is out of range: {}'.format(base1)
assert 2 <= base2 <= 36, 'base2 is out of range: {}'.format(base2)
decoded = decode(digits, base1)
return encode(decoded, base2)
def main():
"""Read command-line arguments and convert given digits between bases."""
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 3:
digits = args[0]
base1 = int(args[1])
base2 = int(args[2])
# Convert given digits between bases
result = convert(digits, base1, base2)
print('{} in base {} is {} in base {}'.format(
digits, base1, result, base2))
else:
print('Usage: {} digits base1 base2'.format(sys.argv[0]))
print('Converts digits from base1 to base2')
if __name__ == '__main__':
main()
|
07f903f617140f237a316552d095f851f9b0666d | jisu0/test1 | /010.py | 488 | 3.984375 | 4 | #! /usr/bin/env python
'''
def mySum(n1: int, n2: int) -> None:
print(f"{n1} + {n2} = {n1+n2}")
mySum(2,3)
mySum(5,7)
mySum(10,15)
'''
def mySum(n1: int, n2: int) -> None:
print(f"{n1} + {n2} = {n1+n2}")
res1 = mySum(2,3)
res2 = mySum(5,7)
res3 = mySum(10,15)
print("---------")
print(res1)
print(res2)
print(res3)
'''
def mySum(n1: int, n2: int) -> int:
return n1 + n2
res1 = mySum(2,3)
res2 = mySum(5,7)
res3 = mySum(10,15)
print(res1)
print(res2)
print(res3)
'''
|
9caff2941c21b054385a6c21789c3e7caa59eeb5 | jisu0/test1 | /003.py | 158 | 3.96875 | 4 | #! /usr/bin/env python
num1 = 3
num2 = 5
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 % num2)
print(num1 ** num2)
|
d7b84a1be3c85a5e7d5d7e502c6fe137e166a846 | Kartik2301/Python-Tkinter | /converter.py | 835 | 3.953125 | 4 | from tkinter import *
window = Tk()
window.title("Mile to Km converter")
window.minsize(width=300, height=150)
window.config(padx=60, pady=30)
miles_input = Entry(width=10)
miles_input.grid(row=0, column=1)
miles_input.grid(padx=10)
miles_input.insert(END, "0")
miles_label = Label(text="Miles")
miles_label.grid(row=0, column=2)
is_equal_to_label = Label(text="is equal to")
is_equal_to_label.grid(row=1, column=0)
km_result_label = Label(text="0")
km_result_label.grid(row=1, column=1)
km_label = Label(text="Km")
km_label.grid(row=1, column=2)
def compute():
value = miles_input.get()
value = float(value)
km_value = value * 1.60934
km_result_label.config(text=f'{km_value}')
calculate_button = Button(text="Calculate", command=compute)
calculate_button.grid(row=2, column=1)
window.mainloop() |
00145c69d8b8f05411e2a21dce8cbbcee8f032c3 | amlalejini/lalejini_checkio_ws | /electronic_station/weak_point/weak_point.py | 2,158 | 3.90625 | 4 | '''
Task:
The durability map is represented as a matrix with digits.
Each number is the durability measurement for the cell.
To find the weakest point we should find the weakest row and column.
The weakest point is placed in the intersection of these rows and columns.
Row (column) durability is a sum of cell durability in that row (column).
You should find coordinates of the weakest point (row and column).
The first row (column) is 0th row (column).
If a section has several equal weak points, then choose the top left point.
'''
LARGE_NUMBER = 999999999
def weak_point(matrix):
row_sums = [sum(row) for row in matrix] # keep track of row sums
col_sums = []
for c in xrange(0, len(matrix[0])): # calculate column sums
col_sum = 0
for r in xrange(0, len(matrix)):
col_sum += matrix[r][c]
col_sums.append(col_sum)
min_row = 0 # Keep track of minimum row number
min_col = 0 # Keep track of minimum col number
# Search for minimum row
for r in xrange(0, len(row_sums)):
if row_sums[r] < row_sums[min_row]:
min_row = r
# Search for minimum column
for c in xrange(0, len(col_sums)):
if col_sums[c] < col_sums[min_col]:
min_col = c
# Weakest point is at the intersection of the min row and min col
weakest_point = [min_row, min_col]
return weakest_point
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert isinstance(weak_point([[1]]), (list, tuple)), "The result should be a list or a tuple"
assert list(weak_point([[7, 2, 7, 2, 8],
[2, 9, 4, 1, 7],
[3, 8, 6, 2, 4],
[2, 5, 2, 9, 1],
[6, 6, 5, 4, 5]])) == [3, 3], "Example"
assert list(weak_point([[7, 2, 4, 2, 8],
[2, 8, 1, 1, 7],
[3, 8, 6, 2, 4],
[2, 5, 2, 9, 1],
[6, 6, 5, 4, 5]])) == [1, 2], "Two weak point"
assert list(weak_point([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])) == [0, 0], "Top left"
|
4ec00b56f34cdfbcc64241c4a8ea12bd8bbc3d3d | 1aaronscott/Graphs | /projects/ancestor/ancestor.py | 1,311 | 4.09375 | 4 | ''' Find the earliest ancestor of a node '''
from graph import Graph
def earliest_ancestor(ancestors, starting_node):
''' Input: list of ancestor tuples and a starting point.
First value in tuple is the parent, remainder are children.
Output: longest graph path from given starting node. '''
# make a list of verts for later traversal
vert = list(set([y for x in ancestors for y in x]))
# build a graph
g = Graph()
for tup in ancestors:
parent = tup[0]
child = tup[1]
g.add_vertex(parent)
g.add_vertex(child)
g.add_edge(child, parent)
# hold all the paths we find
paths = []
for vertex in vert:
# if we're not at start node and a path exists, add the path
if vertex != starting_node and g.dfs(starting_node, vertex):
paths.append(g.dfs(starting_node, vertex))
if len(paths) < 1: # no paths were found
return -1
else:
# sort all the paths and return the last value
return max(paths, key=len)[-1]
if __name__ == '__main__':
ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7),
# (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
(11, 5), (11, 8), (8, 9), (4, 8), (10, 1)]
print(earliest_ancestor(ancestors, 9))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.