blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ed5b9a4432de26637ecbfc6e2fd3fdecc4ce7617
MjrLandWhale/StatisticsCalc
/range_test.py
1,006
3.71875
4
import unittest from range import RangeCalc # test for range with list of numbers class RangeTest(unittest.TestCase): def test_range_list(self): range_num = RangeCalc() number_list = [10, 6, 4, 2, 4, 7] # list of numbers for test expected_output = 8 # expected output for number_list actual_output = RangeCalc.calculate_range(range_num, number_list) # calculated value for number_list self.assertEqual(expected_output, actual_output, 'range = %d' % actual_output) # test for range with one number in list def test_range_one_num(self): range_num = RangeCalc() number_list = [7] # number_list for test (length = 1) expected_output = None # expected output for number_list actual_output = RangeCalc.calculate_range(range_num, number_list) # calculated value for number_list self.assertEqual(expected_output, actual_output, 'range = %s' % actual_output) if __name__ == '__main__': unittest.main()
0de66b65d8d8e7731542c613d35eae6f98704a37
cryjun215/c9-python-getting-started
/python-for-beginners/08 - Handling conditions/add_else.py
479
3.859375
4
price = input('how much did you pay? ') price = float(price) if price >= 1.00: # $1.00 이상의 비용은 모두 7%의 세금이 부과됩니다. # 들여 쓰기(indent)된 모든 구문은 price >= 1.00 인 경우에만 실행됩니다. tax = .07 print('Tax rate is: ' + str(tax)) else: # 그 외에는 세금을 부과하지 않습니다. # 들여 쓰기된 모든 구문은 가격이 $1 미만인 경우에 실행됩니다. tax = 0 print('Tax rate is: ' + str(tax))
353c8a980f132f1c58edde0bc9805648fe3225d2
sangloo/Data-Science-Learning-Path
/Dataquest Learning/python-programming-intermediate/Challenge_ Modules, Classes, Error Handling, and List Comprehensions-186.py
1,210
3.90625
4
## 2. Introduction to the Data ## import csv data = csv.reader(open("nfl_suspensions_data.csv")) nfl_suspensions = list(data) nfl_suspensions = nfl_suspensions[1:] years = {} for item in nfl_suspensions: year = item[5] if year in years: years[year] += 1 else: years[year] = 1 print(years) ## 3. Unique Values ## teams = [row[1] for row in nfl_suspensions] unique_teams = set(teams) print(unique_teams) games = [row[2] for row in nfl_suspensions] unique_games = set(games) print(unique_games) ## 4. Suspension Class ## class Suspension(): def __init__(self, row): self.name = row[0] self.team = row[1] self.games = row[2] self.year = row[5] third_suspension = Suspension(nfl_suspensions[2]) ## 5. Tweaking the Suspension Class ## class Suspension(): def __init__(self,row): self.name = row[0] self.team = row[1] self.games = row[2] try: self.year = int(row[5]) except Exception: self.year = 0 def get_year(self): return self.year missing_year = Suspension(nfl_suspensions[22]) twenty_third_year = missing_year.get_year()
c51a98098abc77ddb7aaedec0bc163b7c2ad1879
PrVrSs/tng
/projects/py_projects/pvs/pvs/errors.py
1,266
3.828125
4
"""Custom Exception""" class ItemAlreadyStored(Exception): pass class ItemNotStored(Exception): pass class CutterException(Exception): """General Cutter exception occurred.""" class CMDException(Exception): """General Cmd exception occurred.""" class ArgumentValidationError(ValueError): """ Raised when the type of an argument to a function is not what it should be. """ def __init__(self, arg_num: int, func_name: str, accepted_arg_type: str): super().__init__() self.error: str = f'The {arg_num} argument of {func_name}() is not a {accepted_arg_type}' def __str__(self) -> str: return self.error class InvalidArgumentNumberError(ValueError): """ Raised when the number of arguments supplied to a function is incorrect. Note that this check is only performed from the number of arguments specified in the validate_accept() decorator. If the validate_accept() call is incorrect, it is possible to have a valid function where this will report a false validation. """ def __init__(self, func_name): super().__init__() self.error: str = f'Invalid number of arguments for {func_name}()' def __str__(self) -> str: return self.error
60dba71446796ccb51a43adffdb82d0dbb034816
mrob95/MR-caster
/caster/lib/latex/book_citation_generator.py
4,807
3.5625
4
# -*- coding: utf-8 -*- try: from bs4 import BeautifulSoup except: pass from urllib2 import Request, urlopen, quote from caster.lib.dfplus.actions import Key, Text from caster.lib.dfplus.clipboard import Clipboard import re # takes URL, returns beautiful soup def request_page(url): header = {'User-Agent': 'Mozilla/5.0'} request = Request(url, headers=header) response = urlopen(request) html = response.read() htmlsoup = BeautifulSoup(html, features="lxml") return htmlsoup # Returns url of first result from goodreads def goodreads_results(searchstr): searchstr = '/search?q=' + quote(searchstr) url = "https://www.goodreads.com" + searchstr htmlsoup = request_page(url) links_list = [] refre = re.compile(r'/book/show/.*\?from_search=true') for link in htmlsoup.find_all("a"): link_url = link.get("href") if type(link_url) is str: if refre.search(link_url): links_list.append("https://www.goodreads.com" + link_url) return links_list ''' get_book_data is the main scraping function. It takes a goodreads book url and returns a dict with the following fields: title authors (list) authors_string (string, author names separated with " and ") edition pub_date (often of the form 29th May 2006) pub_year (the last word of pub_date, hopefully the year) publisher first_published (for old books, this is often different to the edition date) ''' def get_book_data(url): htmlsoup = request_page(url) data = {} data["authors"] = [] for link in htmlsoup.find_all("a", { "class": "authorName" }): for span in link.find_all("span", { "itemprop": "name"}): data["authors"].append(span.text) data["authors_string"] = " and ".join(data["authors"]) heading1 = htmlsoup.find("h1", {"id":"bookTitle"}) data["title"] = heading1.text.replace("\n", "").strip() details = "" for row in htmlsoup.find_all("div", {"class":"row"}): edition_span = row.find("span", {"itemprop":"bookEdition"}) if edition_span is not None: data["edition"] = edition_span.text details = details + row.text pub_date_match = re.search(r'Published\n(.*)\n', details) if pub_date_match: data["pub_date"] = pub_date_match.group(1).strip() data["pub_year"] = data["pub_date"].split(" ")[-1] else: data["pub_date"] = "" data["pub_year"] = "" publisher_match = re.search(r'by\ (.*)\n', details) if publisher_match: data["publisher"] = publisher_match.group(1).strip() else: data["publisher"] = "" first_published_match = re.search(r'first\ published\ (.*)\)', details) if first_published_match: data["first_published"] = first_published_match.group(1).strip().split(" ")[-1] else: data["first_published"] = "" return data ''' Takes the dict from get_book_data and builds a bibTeX-style citation which can be appended directly to a .bib file. Example citations: @book{wedgwood1938thirty, title={The Thirty Years War}, author={C.V. Wedgwood and Anthony Grafton}, year={1938}, publisher={New York Review of Books}, note={2005} } @book{russell2006like, title={Like Engend'ring Like: Heredity and Animal Breeding in Early Modern England}, author={Nicholas Russell}, year={2006}, publisher={Cambridge University Press} } ''' def build_citation(data): # create strings for building a bibtex tag - last name of first author, first word of title first_name = data["authors"][0].lower().split(" ")[-1] first_title = data["title"].lower().replace("the ", "").split(" ")[0] # If the year first published is not the same as the year the returned edition was published, # format the year as first published/edition published note = "" if data["first_published"] == "": tag = first_name + data["pub_year"] + first_title year = data["pub_year"] elif data["pub_year"] == "": tag = first_name + data["first_published"] + first_title year = data["first_published"] else: tag = first_name + data["first_published"] + first_title note = ",\n note={%s}" % data["pub_year"] year = data["first_published"] ref = u"""@book{%s, title = {%s}, author = {%s}, year = {%s}, publisher = {%s}%s } """ % (tag, data["title"], data["authors_string"], year, data["publisher"], note) return ref ''' Searches a given book name, builds citation from the first result, if any ''' def citation_from_name(book_name): search_results = goodreads_results(book_name) if search_results == []: print("No results found on goodreads") ref = "" else: url = search_results[0] data = get_book_data(url) ref = build_citation(data) return ref
9bbd83a4689c875ee5a6dce967abbc61e133eeb9
salvador-dali/algorithms_general
/interview_bits/level_6/06_greedy/03_bulbs.py
317
3.75
4
# https://www.interviewbit.com/problems/bulbs/ def bulb(arr): if not len(arr): return 0 prev, arr2 = -1, [] for i in arr: if i != prev: arr2.append(i) prev = i if arr2[0] == 1: return len(arr2) - 1 return len(arr2) print bulb([1, 1, 1, 0, 1, 1])
6d6f9092a91ac220daf0c4ef0a67b04ed4fc76c4
Jill1627/lc-notes
/isComplete.py
1,336
4.125
4
""" 问题: 问一棵树是否完全 思路:使用队列 Queue装入所有TreeNode,pop掉所有尾端的None,然后逐个检查,一旦中间有None,false 1. 将root装进queue 2. 用指针index,记录queue中的元素 3. 当index未达到队列长度时,意味着队列中还有实际的元素,就先测试该元素的左右儿子是否存在,然后加入队列 4. 加入完毕后,将靠后的None元素全部pop掉,会停止在一个实际元素的位置 5. for所有当前队列中的元素,任何是否出现空,都false,其他true。因为现在出现的None元素,就是树中间的,而不是尾后的 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ class Solution: """ @param root, the root of binary tree. @return true if it is a complete binary tree, or false. """ def isComplete(self, root): if not root: return True q = [root] index = 0 while index < len(q): if q[index]: q.append(q[index].left) q.append(q[index].right) index += 1 while not q[-1]: q.pop() for node in q: if not node: return False return True
760c87e0819c71c4679e9a35bfc3e3ab6c117aac
djanlm/Curso-Em-V-deo---Python
/Mundo 2/ex058_JogoDaAdivinhacao2.py
486
3.609375
4
from random import randint comp = randint(0, 10) print('\033[1;33m=-'*20) print('\033[1;32m{:^40}'.format('JOGO DA ADIVINHAÇÃO')) print('\033[1;33m=-'*20+'\033[m') guess = int(input("Qual número entre 0 e 10 eu pensei? ")) tentativas = 1 while guess != comp: print("\033[1;34mO número que pensei não foi esse, tente novamente.\033[m") guess = int(input("Qual número entre 0 e 10 eu pensei? ")) tentativas += 1 print("Após {} tentativas você ACERTOU!!! ".format(tentativas))
d77a4d51d56dda9fbd7337872ed3e8374ecbc33d
apatelCSE/pyprojects
/buzzfeedquiz.py
1,080
4.0625
4
while True: print("Tell Us Which of These Movies Made You Cry and We'll Guess Your Favorite Food") counter = 0 titanic = input("Did you cry during Titanic?") print(titanic) if "y" in titanic: counter += 1 up = input("Did Up make you cry?") print(up) if "y" in up: counter += 1 notebook = input("Did you cry during The Notebook?") print(notebook) if "y" in notebook: counter += 1 helps = input("Did The Help make you cry?") print(helps) if "y" in helps: counter += 1 insideout = input("Did you cry during Inside Out?") print(insideout) if "y" in insideout: counter += 1 wonder = input("Did Wonder make you cry?") print(wonder) if "y" in wonder: counter += 1 if counter <=2: print("Your favorite food is cold soup, you heartless scumbag.") elif counter <=4: print("Your favorite food is mac and cheese.") elif counter <=6: print("Your favorite food is pizza. Warm and wonderful like your heart! <3") endans = input("Wanna take the quiz again?") if "y" in endans: continue else: break
da5b82a6ba953974d1f1c7bf2b7fe0602a8f9b35
salvador-dali/algorithms_general
/training/02_implementation/the_grid_search.py
1,074
3.71875
4
# https://www.hackerrank.com/challenges/the-grid-search def find_all(a_str, sub): arr, start = [], 0 while True: start = a_str.find(sub, start) if start == -1: break arr.append(start) start += len(sub) return arr def tryPattern(positions, M, sM, line): l = len(sM[0]) for pos in positions: exist = 1 for i in xrange(len(sM)): if sM[i] != M[i + line][pos:pos + l]: exist = 0 break if exist: return 1 return 0 def submatrix_search(M, sM): for i in xrange(len(M)): line = M[i] positions = find_all(line, sM[0]) if positions: if tryPattern(positions, M, sM[1:], i + 1): return 1 return 0 for i in xrange(input()): a, b = map(int, raw_input().split()) M = [raw_input() for j in xrange(a)] a, b = map(int, raw_input().split()) sM = [raw_input() for j in xrange(a)] if submatrix_search(M, sM): print 'YES' else: print 'NO'
63131207928d367b6bd0b2656aa4b3a8b6c135ee
lasya02/comp110-21ss1-workspace
/lessons/quiz01.py
517
3.6875
4
def main() -> None: b: list[str] = a print(b) f(a) print(b) print("6") g() print(b) print("4") print(b[0]) return None def f(c: list[str]) -> None: c[0] = "p" print(c) c = ['m','j'] print(c) print("0") return None def g() -> None: global a a[1] = "y" print(a) print("7") a = ["k","g"] print(a) print("1") return None a: list[str] = ["w", 'u'] if __name__ == "__main__": main() print(a) print("2")
89ec863c50a51ab2df25d938f689096f88e402a2
knunura/TCP-Client-Server-Centralized-Network
/client/client.py
2,874
3.5625
4
####################################################################### # File: client.py # Author: Kevin Nunura and Jose Ortiz # Purpose: CSC645 Assigment #1 TCP socket programming # Description: Template client class. You are free to modify this # file to meet your own needs. Additionally, you are # free to drop this client class, and add yours instead. # Running: Python 2: python client.py # Python 3: python3 client.py # ######################################################################## import socket import pickle from client_helper import ClientHelper class Client(object): """ The client class provides the following functionality: 1. Connects to a TCP server 2. Send serialized data to the server by requests 3. Retrieves and deserialize data from a TCP server """ def __init__(self): # Creates the client socket # AF_INET refers to the address family ipv4. # The SOCK_STREAM means connection oriented TCP protocol. self.clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_id = 0 self.client_name = None def get_client_id(self): return self.client_id def set_client_id(self): data = self.receive() # deserialized data client_id = data['clientid'] # extracts client id from data self.client_id = client_id # sets the client id to this client print("Successfully connected to server: " + self.server_ip_address + "/" + str(self.server_port)) print("Your client info is:\nClient Name: " + self.client_name + "\nClient ID: " + str(self.client_id) + "\n") def connect(self): self.server_ip_address = input("Enter the server IP Address: ") self.server_port = int(input("Enter the server port: ")) self.client_name = input("Your id key (i.e your name): ") self.clientSocket.connect((self.server_ip_address, self.server_port)) self.set_client_id() data = {'client_name': self.client_name, 'clientid': self.client_id} self.send(data) self.run_helper() self.close() def run_helper(self): client_id = self.receive() # get rid of first message to use menu from now on client_helper = ClientHelper(self) client_helper.run() def send(self, data): data = pickle.dumps(data) # serializes the data self.clientSocket.send(data) def receive(self, MAX_BUFFER_SIZE=4096): raw_data = self.clientSocket.recv(MAX_BUFFER_SIZE) return pickle.loads(raw_data) # deserializes the data from server def close(self): self.clientSocket.close() if __name__ == '__main__': server_ip_address = None server_port = 0 client = Client() client.connect()
c9f734a2a56e30d8449a84d211d48c7cd4938fab
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/khstsa004/question1.py
161
4.03125
4
x=eval(input("Enter a year:\n")) if x%400==0 or x%4==0 and x%100!=0 : print(x, "is a leap year.") else: print(x, "is not a leap year.")
5c22038c133b8f3c714c3b2644bcbb8bf1e94f51
ryanriccio1/prog-fund-i-repo
/main/labs/lab3/ryan_riccio_lab3b.py
8,403
3.765625
4
# this program will calculate the gross pay for a given employee and return # it as a pay stub # declare constants BASE_SALARY = 2000 MAX_VACATION_DAYS = 3 MAX_VACATION_DEDUCTION = 200 BONUS_THRESH = 3 BONUS_0 = 0.0 BONUS_1 = 0.0 BONUS_2 = 1000.0 BONUS_3 = 5000.0 GREATER_3_BONUS = 100000.0 LONG_TIME_MONTH = 60 LONG_TIME_BONUS = 1000 LONG_TIME_THRESH = 100000 RANGE_0_MAX = 10000 RANGE_1_MAX = 100000 RANGE_2_MAX = 500000 RANGE_3_MAX = 1000000 RANGE_0_COMMISSION = 0.0 RANGE_1_COMMISSION = 0.02 RANGE_2_COMMISSION = 0.15 RANGE_3_COMMISSION = 0.28 GREATER_3_COMMISSION = 0.35 # create class to store data from user class PaycheckData(object): # initialize and compute def __init__(self, name, months_worked, vacation_days, sales): self._name = name self._months_worked = months_worked self._vacation_days = vacation_days self._sales = sales # will assign _commission (%) and _bonus ($) based on range # if it is in range 0 (between 0 and less than RANGE_0_MAX) if self._sales < RANGE_0_MAX: self._commission = RANGE_0_COMMISSION self._bonus = BONUS_0 # if it is in range 1 elif RANGE_0_MAX <= self._sales <= RANGE_1_MAX: self._commission = RANGE_1_COMMISSION self._bonus = BONUS_1 # if it is in range 2 elif RANGE_1_MAX < self._sales <= RANGE_2_MAX: self._commission = RANGE_2_COMMISSION self._bonus = BONUS_2 # if it is in range 3 elif RANGE_2_MAX < self._sales <= RANGE_3_MAX: self._commission = RANGE_3_COMMISSION self._bonus = BONUS_3 # if not in other ranges it is > range 3 (> GREATER_3_MAX ) else: self._commission = GREATER_3_COMMISSION self._bonus = GREATER_3_BONUS # if not worked for set amount of time, no bonus if self._months_worked < BONUS_THRESH: self._bonus = 0.0 # if they are over their vacation days, deduction is assigned if self._vacation_days > MAX_VACATION_DAYS: self._deduction = MAX_VACATION_DEDUCTION # if not, deduction is zero else: self._deduction = 0.0 # if worked for set amount of time and sales hit threshold, add bonus if self._months_worked >= LONG_TIME_MONTH and self._sales > LONG_TIME_THRESH: self._additional_bonus = LONG_TIME_BONUS # if not, no add. bonus else: self._additional_bonus = 0.0 # calculate commission as money self._commission = self._sales * self._commission # add commission, bonus, add. bonus, salary, subtract deduction self._gross_pay = (self._commission + self._bonus + self._additional_bonus - self._deduction + BASE_SALARY) # function to print data def print_paycheck(self): print('\n', PaycheckData.stub_format('NAME', self._name, 'l'), # add label at end before calculating len() PaycheckData.stub_format('TIME', f'{self._months_worked}' + 'm', 'l'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('SALARY', f'${BASE_SALARY:,.2f}', 'l'), '\n', PaycheckData.stub_format('NAME', self._name, 'v'), # add label at end before calculating len() PaycheckData.stub_format('TIME', f'{self._months_worked}' + 'm', 'v'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('SALARY', f'${BASE_SALARY:,.2f}', 'v'), '\n\n', # format as money with 2 floating points before calculating len() PaycheckData.stub_format('COMMISSION', f'${self._commission:,.2f}', 'l'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('BONUS', f'${self._bonus:,.2f}', 'l'), '\n', # format as money with 2 floating points before calculating len() PaycheckData.stub_format('COMMISSION', f'${self._commission:,.2f}', 'v'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('BONUS', f'${self._bonus:,.2f}', 'v'), '\n\n', # format as money with 2 floating points before calculating len() PaycheckData.stub_format('ADD. BONUS', f'${self._additional_bonus:,.2f}', 'l'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('DEDUCTIONS', f'-${self._deduction:,.2f}', 'l'), '\n', # format as money with 2 floating points before calculating len() PaycheckData.stub_format('ADD. BONUS', f'${self._additional_bonus:,.2f}', 'v'), # format as money with 2 floating points before calculating len() PaycheckData.stub_format('DEDUCTIONS', f'-${self._deduction:,.2f}', 'v'), '\n\n', # display gross pay (no need to format to table as only 1 line) f'GROSS PAY\n${self._gross_pay:,.2f}\n', sep='') # static function to add consistent spaces to format pay stub # 3 strings are passed in, the difference of the string lengths # is evaluated to make sure that there is 4 spaces after the # longest string. Extra spaces are added to shorter one to make # it line up. option is to decide whether to return the label # or the variable @staticmethod def stub_format(label, variable, option): # convert var to str variable = str(variable) # get length of variables label_length = len(label) var_length = len(variable) # see which option was selected if option == 'l': # see which is the longest, if var is less, # set it to 4 (min amount of spaces) if var_length < label_length: spaces = 4 # if var is longer, find the difference, add # 4 spaces else: spaces = var_length - label_length + 4 formatted_label = label + (' ' * spaces) return formatted_label # see which option was selected elif option == 'v': # see which is the longest, if label is less, # set it to 4 (min amount of spaces) if var_length > label_length: spaces = 4 # if label is longer, find the difference, add # 4 spaces else: spaces = label_length - var_length + 4 formatted_label = variable + (' ' * spaces) return formatted_label # if no option selected, return nothing else: pass def main(): # so that user can repeat if wanted keep_going = 'y' while keep_going == 'y': # get name of employee name = input('Enter name of employee: ') # get time worked at company (years, months) years_worked = int(input('Enter years worked (do not include months): ')) months_worked = int(input('Enter months worked (do not include years): ')) # calculate total months months_worked = years_worked * 12 + months_worked # get vacation days taken this month vacation_days = int(input('Enter number of days taken off this month: ')) # get sales for month sales = float(input('Enter sales for the month: ')) # write data to class paycheck_data = PaycheckData(name, months_worked, vacation_days, sales) # print data paycheck_data.print_paycheck() # check to make sure following input is valid, if not repeat prompt valid = False while not valid: keep_going = input('Do you want to do another (y/n): ').lower() # if not valid, tell user and repeat if keep_going != 'y' and keep_going != 'n': print('That was not a valid input') valid = False # if y, restart program elif keep_going == 'y': valid = True print('\n') main() # if valid, and !=y, thank the user and exit else: print('\nThank you, goodbye!') valid = True main()
9b6962477e16fe96e6f7dde2b572dec31458e865
CreateCodeLearn/data-science-track
/Workshop_Coding/temperature_module.py
507
4
4
def kelvin_to_celsius(temperature_K): ''' Function to compute Celsius from Kelvin ''' rv = temperature_K - 273.15 return rv def fahrenheit_to_celsius(temperature_F): ''' Function to compite Celsius from Fahrenheit ''' temp_K = fahrenheit_to_kelvin(temperature_F) temp_C = kelvin_to_celsius(temp_K) return temp_C def fahrenheit_to_kelvin(a): """ Function to compute Fahrenheit from Kelvin """ kelvin = (a-32.0)*5/9 + 273.15 return kelvin
b1f81701c48a5d3efdcfd5712f9911c77e9033ae
cvitanovich/course_projects
/CIS313/assignment2/cvitanovich/problem2-1.py
895
3.734375
4
# Dictionaries for A and B Tiers A_tier = {} B_tier = {} # Read Text File And Store Each Address In Correct Dictionary import sys data = (line.rstrip('\n') for line in open(sys.argv[1])) nAddresses = int(next(data)) for lineNo in range(0,nAddresses): line = next(data).split(' ') # split line by whitespace if(line[1] == "A"): A_tier[line[0],lineNo] = int(line[2]) elif(line[1] == "B"): B_tier[line[0],lineNo] = int(line[2]) # Heap Sorting import heapq as hq # Push A Tier Addresses Onto heapA heapA = [] for key,value in A_tier.items(): hq.heappush(heapA, (value, key[1], key[0])) # Push B Tier Addresses Onto heapB heapB = [] for key,value in B_tier.items(): hq.heappush(heapB, (value, key[1], key[0])) # Print Heapsorted A Tier Addresses while heapA: top = hq.heappop(heapA) print top[2] # Print Heapsorted B Tier Addresses while heapB: top = hq.heappop(heapB) print top[2]
6d64a565735cb69cc39417777fa468e9c960c331
Stewie4848/CP1404_Practicals
/prac_05/word_occurrences.py
353
3.96875
4
text = input("Text: ") words = text.split(" ") words.sort() word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 max_length = max((len(word) for word in words)) for word in sorted(list(word_count.keys())): print("{:{}} = {}".format(word, max_length, word_count[word]))
56f75189a3546b846f2a27434cfdcc0bb2fbb7b0
Foroozani/rasta
/rasta/process_geo_data.py
1,468
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Holds some static method which can be used to process GPS data. @author: ikespand """ import math class ProcessGeoData: """Some methods to post process geospatial data""" @staticmethod def get_distance_from_df(data): """Returns the distance for each row in a df.""" # Find the approx distance from the GPS dist = [0] for i in range(0, len(data) - 1): d = ProcessGeoData.calculate_distance( data["latitude"][i], data["longitude"][i], data["latitude"][i + 1], data["longitude"][i + 1], ) dist.append(d) return dist @staticmethod def calculate_distance(lat1, lon1, lat2, lon2): """Using the haversine formula, which is good approximation even at small distances unlike the Shperical Law of Cosines. This method has ~0.3% error built in. """ dLat = math.radians(float(lat2) - float(lat1)) dLon = math.radians(float(lon2) - float(lon1)) lat1 = math.radians(float(lat1)) lat2 = math.radians(float(lat2)) a = math.sin(dLat / 2) * math.sin(dLat / 2) + ( math.cos(lat1) * math.cos(lat2) * math.sin(dLon / 2) * math.sin(dLon / 2) ) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) d = 6371 * c return d
e2eb64ac37273b26c96c061717179f45abee9fc6
zois-tasoulas/algoExpert
/easy/palindromeCheck.py
642
4.28125
4
def is_palindrome(string): if string is None: raise Exception("Empty string passed to function is_palindrome") end_index = len(string) - 1 # For odd length strings, the middle letter will not be checked for index in range(0, len(string) // 2): if string[index] != string[end_index - index]: return False return True def main(): strings = ["abba", "banana", "d", "asdfdsa", "zxcvbxz"] for word in strings: if is_palindrome(word): print(word, "is a palindrome") else: print(word, "is not a palindrome") if __name__ == "__main__": main()
113f8ca21b3a9aaaba6e49bb2cae403e2daf8a42
JMCSci/Introduction-to-Programming-Using-Python
/Chapter 13/13.4/readwrite/ReadWrite.py
1,128
3.828125
4
''' Chapter 13.4 ''' import random, os.path def main(): filename = input("Enter a filename: ") pathExists = os.path.exists(filename) # check if file exists if(pathExists == False): fileOutput = open(filename, "a") for i in range(0, 100): value = random.randint(0, 200) fileOutput.write(str(value) + " ") fileOutput.close() a = readFile(filename) sortList(a) printValues(a) else: print("The file already exists") def readFile(filename): lst = [] fileInput = open(filename, "r") values = fileInput.read() elements = values.split() lst = [eval(x) for x in elements] fileInput.close() return lst def sortList(a): temp = 0 size = len(a) for i in range(0, size - 1): for j in range(0, size - 1): if(a[j] > a[j + 1]): temp = a[j + 1] a[j + 1] = a[j] a[j] = temp def printValues(a): size = len(a) for i in range(0, size): print(a[i], end = " ") if __name__ == "__main__": main()
7640c6d480b18748a83c8b73c401ea800e7abb89
alferovyuriy/geekbrains
/Python(Basic)/home_work_5/task3.py
673
3.640625
4
""" Определяет, кто из сотрудников имеет оклад менее 20 тыс., выводит фамилии этих сотрудников. Выполняет подсчет средней величины дохода сотрудников. """ try: with open('employees.txt', 'r') as file: sum_salery = 0 counter = 0 for i, employee in enumerate(file.readlines(), 1): surname, salary = employee.split() if salary.isdigit() and int(salary) < 20000: print(f'employee with salary < 20000: {surname}') sum_salery += int(salary) counter += 1 print(f'average salary: {sum_salery/counter}') except IOError as e: print(e)
092fc50a686e9712d05f3de8b7db099b28ed5e0a
christy951/programming-lab
/c01/co1 q5.py
183
3.640625
4
lit=[] n= int(input("Enter the number")) for i in range(0,n): ele= int(input()) if(ele<100): lit.append(ele) else: lit.append("over"); print(lit)
8ba6f57a90e12ae912a83a00f15183850036767b
plelukas/TK
/zad4/AST.py
4,060
3.625
4
#!/usr/bin/python class Node(object): def accept(self, visitor): return visitor.visit(self) def __init__(self): self.children = () class BinExpr(Node): def __init__(self, op, left, right, line): self.line = line self.op = op self.left = left self.right = right class Const(Node): def __init__(self, value, line): self.value = value self.line = line class Integer(Const): pass class Float(Const): pass class String(Const): pass class Variable(Node): def __init__(self, name, line): self.name = name self.line = line class Program(Node): def __init__(self, declarations, fundefs, instructions): self.declarations = declarations self.fundefs = fundefs self.instructions = instructions class Declarations(Node): def __init__(self): self.declarations = [] def addDeclaration(self, declaration): self.declarations.append(declaration) class Declaration(Node): def __init__(self, type, inits): self.type = type self.inits = inits class Inits(Node): def __init__(self): self.inits = [] def addInit(self, init): self.inits.append(init) class Init(Node): def __init__(self, id, expression, line): self.id = id self.expression = expression self.line = line class Instructions(Node): def __init__(self): self.instructions = [] def addInstruction(self, instruction): self.instructions.append(instruction) class PrintInstruction(Node): def __init__(self, expressions, line): self.expressions = expressions self.line = line class LabeledInstruction(Node): def __init__(self, id, instruction, line): self.id = id self.instruction = instruction self.line = line class AssignmentInstruction(Node): def __init__(self, id, expression, line): self.id = id self.expression = expression self.line = line class ChoiceInstruction(Node): def __init__(self, condition, instruction, instruction2=None): self.condition = condition self.instruction = instruction self.instruction2 = instruction2 class WhileInstruction(Node): def __init__(self, condition, instruction): self.condition = condition self.instruction = instruction class RepeatInstruction(Node): def __init__(self, instructions, condition): self.instructions = instructions self.condition = condition class ReturnInstruction(Node): def __init__(self, expression, line): self.expression = expression self.line = line class ContinueInstruction(Node): def __init__(self, line): self.line = line class BreakInstruction(Node): def __init__(self, line): self.line = line class CompoundInstuction(Node): def __init__(self, declarations, instructions): self.declarations = declarations self.instructions = instructions class Expressions(Node): def __init__(self): self.expressions = [] def addExpression(self, expr): self.expressions.append(expr) class NamedExpression(Node): # wywolanie funkcji def __init__(self, id, expressions, line): self.id = id self.expressions = expressions self.line = line class Fundefs(Node): def __init__(self): self.fundefs = [] def addFundef(self, fundef): self.fundefs.append(fundef) class Fundef(Node): # type is return type def __init__(self, type, id, args, compound_instr, line): self.id = id self.type = type self.args = args self.compound_instr = compound_instr self.line = line class Arguments(Node): def __init__(self): self.args = [] def addArgument(self, arg): self.args.append(arg) class Argument(Node): def __init__(self, type, id, line): self.type = type self.id = id self.line = line
1a4a19808a4b00b8465cc2b88d0c9659bf1ac04a
mcxu/code-sandbox
/PythonSandbox/src/leetcode/lc241_diff_ways_to_add_parenthesis.py
1,363
3.546875
4
# https://leetcode.com/problems/different-ways-to-add-parentheses/ class Solution: def __init__(self): self.eval = { '+' : lambda a,b: a+b, '-' : lambda a,b: a-b, '*' : lambda a,b: a*b } self.m = {} def diffWaysToCompute(self, input: str) -> [int]: return self.ways(input) def ways(self, input): if input in self.m.keys(): return self.m[input] ans = [] for i,ch in enumerate(input): if ch in self.eval.keys(): leftSubstr = input[:i] rightSubstr = input[i+1:] #print("leftSubstr: {}, rightSubstr: {}".format(leftSubstr, rightSubstr)) leftWays = self.ways(leftSubstr) rightWays = self.ways(rightSubstr) #print("leftWays: {}, rightWays: {}".format(leftWays, rightWays)) for a in leftWays: for b in rightWays: if a and b: res = self.eval[ch](int(a),int(b)) ans.append(str(res)) if not ans: ans.append(input) #print("input: {}, ans: {}".format(input, ans)) self.m[input]=ans #print("map: ", self.m) return self.m[input]
5ecb23519722924a031f0bd491bec60cebee024d
jrpfaff/PythonNetworkFlows
/main.py
6,934
3.703125
4
from math import inf from collections import deque ''' Ford-Fulkerson implementation and general network flow solver base class. Implemented based on William Fiset youtube video: https://www.youtube.com/watch?v=LdOnanfc5TM&list=PLDV1Zeh2NRsDj3NzHbbFIC58etjZhiGcG&index=1 ''' class Edge: def __init__(self, start: int, to: int, capacity: float) -> None: ''' Simple class for directed edges with a capacity associated to them. :param start: Starting index of the edge. :param to: Ending index of the edge. :param capacity: Capacity of the edge. ''' self.start = start self.to = to self.capacity = capacity self.flow = 0 def isResidual(self) -> bool: return self.capacity == 0 def remainingCapacity(self) -> float: return self.capacity - self.flow def augment(self, bottleneck: float) -> None: ''' After finding an augmenting path, the edge (and its residual edge) update by the bottleneck value of the path. :param bottleneck: The bottleneck value found on the path. :return: None ''' self.flow += bottleneck ''' Note that residual is not created in the Edge initialization, rather it is created when adding the edge to the solver graph. ''' try: self.residual.flow -= bottleneck except AttributeError: print('The residual edge was not found. This is likely due to running the augment method outside the solver class.') def toString(self): return f'Edge {self.start} -> {self.to} | flow = {self.flow:>5} | capacity = {self.capacity:>5} | is residual: {self.isResidual()}' class SolverBase: def __init__(self, n, s, t): ''' This underlying solver can be extended to use different methods for finding augmenting paths. In particular, the solver method is left unimplemented to allow the user to choose a method for finding the paths. :param n: The number of edges in the network, indexed by integers from 0 to n-1. :param s: The index of the starting node. :param t: The index of the target node. ''' self.MaxFlow = 0 self.n = n self.s = s self.t = t self.initializeEmptyFlowGraph() self.visited = [0 for _ in range(n)] self.visitedToken = 1 self.solved = False def initializeEmptyFlowGraph(self): self.graph = [[] for _ in range(self.n)] def addEdge(self, start, to, capacity): ''' Adds an edge to the graph. Creates its residual edge and adds that as well. :param start: :param to: :param capacity: :return: ''' E1 = Edge(start, to, capacity) E2 = Edge(to, start, 0) E1.residual = E2 E2.residual = E1 self.graph[start].append(E1) self.graph[to].append(E2) def visit(self, i): ''' Updates the node with a visited token, denoting which augmenting path it was last a part of. It is used to check if there is a cycle when creating the augmenting paths. :param i: :return: ''' self.visited[i] = self.visitedToken def getGraph(self): self.execute() return self.graph def getMaxFlow(self): self.execute() return self.MaxFlow def execute(self): if self.solved: return self.solved = True self.solve() def getSolution(self): self.execute() for node in self.graph: for edge in node: print(edge.toString()) def solve(self): #This will be overriden in the subclass that extends this class. pass def markNodesAsUnvisited(self): self.visitedToken += 1 class FordFulkersonDFSSolver(SolverBase): ''' Extends the SolverBase method to use a depth first search method for finding the augmenting paths. A link for depth first search can be found here: https://www.youtube.com/watch?v=AfSk24UTFS8&t=2407s ''' def __init__(self, n: int, s: int, t: int): super().__init__(n,s,t) def solve(self) -> None: ''' Repeatedly finds augmenting paths until there are none left (this is when the flow f is equal to 0) :return: None ''' f = -1 while f != 0: f = self.dfs(self.s, inf) self.visitedToken += 1 self.MaxFlow += f def dfs(self, node: int, flow: float): ''' A depth first search along valid paths, :param node: :param flow: :return: the bottleneck value along the augmenting path is returned ''' #if at sink node, return the flow along the augmenting path if node == self.t: return flow # self.visit(node) for edge in self.graph[node]: if edge.remainingCapacity() > 0 and self.visited[edge.to] != self.visitedToken: bottleNeck = self.dfs(edge.to, min(flow, edge.remainingCapacity())) if bottleNeck > 0: edge.augment(bottleNeck) return bottleNeck return 0 class EdmondsKarpSolver(SolverBase): def __init__(self, n, s, t): super().__init__(n, s, t) def solve(self): f = -1 while f != 0: self.markNodesAsUnvisited() f = self.bfs() self.MaxFlow += f def bfs(self): q = deque() self.visit(self.s) q.append(self.s) prev = [None for _ in range(self.n)] while q: node = q.popleft() if node == self.t: break for edge in self.graph[node]: cap = edge.remainingCapacity() if cap > 0 and (not self.visited[edge.to] == self.visitedToken): self.visit(edge.to) prev[edge.to] = edge q.append(edge.to) if prev[self.t] is None: return 0 bottleNeck = inf edge = prev[self.t] while edge is not None: bottleNeck = min(bottleNeck, edge.remainingCapacity()) edge = prev[edge.start] edge = prev[t] while edge is not None: edge.augment(bottleNeck) edge = prev[edge.start] return bottleNeck n = 7 s, t = 0, 6 solver = EdmondsKarpSolver(n, s, t) solver.addEdge(s, 1, 9) solver.addEdge(s, 3, 12) solver.addEdge(1, 2, 6) solver.addEdge(1, 3, 9) solver.addEdge(1, 4, 4) solver.addEdge(1, 3, 5) solver.addEdge(2, 3, 2) solver.addEdge(2, 4, 6) solver.addEdge(2, 5, 3) solver.addEdge(3, 2, 4) solver.addEdge(3, t, 7) solver.addEdge(4, 5, 2) solver.addEdge(4, t, 8) solver.addEdge(5, t, 5) print(solver.getMaxFlow()) solver.getSolution()
6f0f67cf205923a88e4af0ab47ba00307e894198
juanall/Informatica
/TP2.py/2.1.py
545
4.03125
4
#INTRO. A PYTHON PARTE 2: #Ejercicio 1 #Creá un programa que lea una cadena por teclado y compruebe si la primer letra es mayúscula o minúscula. def mayus (cadena): if (cadena[0]).isupper() == True: print ("la primer letra esmayuscula") else: print("la primer letra es minuscula") print(mayus("computadora")) cadena = str(input("dame una palabra:")) def es_mayus(palabra): if palabra[0] >= "a" and palabra[0] <= "z": print("es minuscula") else: print("es mayuscula") print(es_mayus(cadena))
ba445e0fcbf182279a43330a86752602eeca1cb0
tonydelanuez/python-ds-algos
/probs/merge-integer-ranges.py
958
3.671875
4
def merge_ranges(input_range_list): #check for null or 1 list if (len(input_range_list) <= 1 or input_range_list == None): return input_range_list output = [] i = 1 previous = input_range_list[0] while i < len(input_range_list): current = input_range_list[i] #overlap exists if(previous.upper_bound >= current.lower_bound): #make a new merged range merged = Range(previous.lower_bound, max(previous.upper_bound, current.upper_bound)) previous = merged else: #only append when we can no longer merge output.append(previous) previous = current i += 1 output.append(previous) return output class Range(object): def __init__(self): self.lower_bound = -1 self.upper_bound = -1 def __init__(self,lower_bound,upper_bound): self.lower_bound = lower_bound self.upper_bound = upper_bound def __str__(self): return "["+str(self.lower_bound)+","+str(self.upper_bound)+"]"
48494013345d258fb17e1ba214f143b778a1f3bb
PNeekeetah/Leetcode_Problems
/Reverse_Words_in_a_String.py
683
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 29 22:17:09 2021 @author: Nikita """ """ Took me less than 10 minutes to code this. It beats 42% in terms of runtime and 0% in terms of memory. 4th time submission sucessful. The fact that I could have multiple white spaces tripped me. """ class Solution: def reverseWords(self, s: str) -> str: words_list = s.split(" ") valid_words = [word for word in words_list if word != ""] reversed_words = "" for i in range (len(valid_words)-1,0,-1): reversed_words += valid_words[i] + " " else: reversed_words += valid_words[0] return reversed_words
b4058abfb2cc246e722d17fdd6b0c17863528b76
hrawson79/Algorithms
/Trees/binary_search_tree.py
3,063
4.03125
4
# BinarySearchTree Class from Trees.tree_node import TreeNode class BinarySearchTree(object): # Constructor def __init__(self): self.root = None # Method to insert a new item into the tree def insert(self, item): self.root = self._subtree_insert(self.root, item) # Helper method to insert a new item recursively def _subtree_insert(self, root, item): # root is None if (root is None): return TreeNode(item) # item is equal to root if (item == root.data): raise ValueError("Inserting duplicate item") # item is less than root if (item < root.data): root.left = self._subtree_insert(root.left, item) # item is greater than root if (item > root.data): root.right = self._subtree_insert(root.right, item) return root # Method to find an item in the tree def find(self, item): node = self.root while (node is not None and not(node.data == item)): if (item < node.data): node = node.left else: node = node.right if (node is None): return None else: return node.data # Method to remove item from the tree def delete(self, item): self.root = self._subtree_delete(root, item) # Helper method to remove item from the tree def _subtree_delete(self, root, item): # Empty tree, nothing to do if root is None: return None # Item is less than root if item < root.data: root.left = _subtree_delete(root.left, item) # Item is greater than root elif item > root.data: root.right = _subtree_delete(root.right, item) else: if root.left is None: root = root.right elif root.right is None: root = root.left else: root.item, root.left = self._subtree_del_max(root.left) return root # Helper method to promot the max def _subtree_del_max(self, root): if root.right is None: return root.item, root.left else: maxVal, root.right = self._subtree_del_max(root.right) return maxVal, root # Method to iterate the tree def __iter__(self): return self._inorder_gen(self.root) # Helper method to iterate inorder the tree def _inorder_gen(self, root): if root is not None: for item in self._inorder_gen(root.left): yield item yield root.get_data() for item in self._inorder_gen(root.right): yield item # Helper method to iterate preorder the tree def _preorder_gen(self, root): if root is not None: yield root.get_data() for item in self._preorder_gen(root.left): yield item for item in self._preorder_gen(root.right): yield item
be5fee8ef69cbdd12312868d07b9e0e134a26252
sairam-py/CodeForces-1
/EvenOdds.py
541
3.765625
4
__author__ = 'Devesh Bajpai' ''' http://codeforces.com/problemset/problem/318/A Algorithm: Find the half of the limit number. Check if it lies on the left of the half of it. If so, print the kth odd number. Check if it lies on the right of the half of it. If so, print the kth even number. ''' def solve(n,k): if(n%2==0): half = n/2 else: half = n/2 + 1 if(k<=half): return (2*k)-1 else: return 2*(k-half) if __name__ == "__main__": n,k = map(int,raw_input().split(" ")) print solve(n,k)
c767bc5afd8548ab91cc53ec8003be6d09281ad5
Fahmad920/CSE
/Blackjack.py
338
3.75
4
import random def draw_hit(): return random.randint(1, 10) def total_value(): return card1 = draw_hit() card2 = draw_hit() print(card1 + card2) print("Your cards are %s" % card1, card2) turn = input("Do you want to hit or stay? ") if "hit": print("You got %s." % draw_hit()) print("Your total is now %s" % (value))
428a709fcf92f5045413648f16869b12534f33bb
dtliao/Starting-Out-With-Python
/chap.5/25 p.231 ex.15.py
1,188
4.09375
4
def calc_average(): average=(firstScore + secondScore + thirdScore + fourthScore + fifthScore)/5 return average def determine_grade(x): if x>=90 and x<=100: return 'A' elif x>=80: return 'B' elif x>=70: return 'C' elif x>=60: return 'D' else: return 'F' firstScore = int(input('Enter the first score:')) secondScore = int(input('Enter the second score:')) thirdScore = int(input('Enter the third score:')) fourthScore = int(input('Enter the fourth score:')) fifthScore = int(input('Enter the fifth score:')) x=calc_average() y=determine_grade(x) print(y) print('Score', '\t\t', 'Grade', '\t', 'Letter Grade') print('----------------------------------------------------') print('Score 1:\t', firstScore, '\t\t', determine_grade(firstScore)) print('Score 2:\t', secondScore, '\t\t', determine_grade(secondScore)) print('Score 3:\t', thirdScore, '\t\t', determine_grade(thirdScore)) print('Score 4:\t', fourthScore, '\t\t', determine_grade(fourthScore)) print('Score 5:\t', fifthScore, '\t\t', determine_grade(fifthScore)) print('----------------------------------------------------') print ('Average:\t', x, '\t\t', y)
452c8102267ccf119f35b22b06a6455f9ebb770d
AbdullahEsha/Python
/basics/BIDIRECTIONAL.py
1,330
3.84375
4
import queue class Node: def __init__(self, value): self.value = value self.neighbors = None self.visited_right = False self.visited_left = False self.parent_right = None self.parent_left = None def bidirectional(s, t): def extract_path(node): node_copy = node path = [] while node: path.append(node.value) node = node.parent_right path.reverse() del path[-1] while node_copy: path.append(node_copy.value) node_copy = node_copy.parent_left return path q = queue.Queue() q.put(s) q.put(t) s.visited_right = True t.visited_left = True while not q.empty(): n = q.get() if n.visited_left and n.visited_right: return extract_path(n) for node in n.neighbors: if n.visited_left == True and not node.visited_left: node.parent_left = n node.visited_left = True q.put(node) if n.visited_right == True and not node.visited_right: node.parent_right = n node.visited_right = True q.put(node) return False n0 = Node(0) n1 = Node(1) n2 = Node(2) n3 = Node(3) n0.neighbors = [n1, n2] n1.neighbors = [n2] n2.neighbors = [n3] n3.neighbors = [n1, n2] print(bidirectional(n0, n3))
e2fb14778e064b003116eb55b510709a3d59f071
edeng/CodeEval
/Easy/FizzBuzz.py
679
3.71875
4
# Eden Ghirmai, 2/18/14, www.codeeval.com # prints out the the pattern generated by such a scenario given the values of # 'A'/'B' and 'N' which are read from an input text file. import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: if test: split = test.split(" ") first = int(split[0]) second = int(split[1]) third = int(split[2]) result = "" for x in range (1, third + 1): if x % first == 0 and x % second == 0: result += "FB " elif x % first == 0: result += "F " elif x % second == 0: result += "B " else: result += str(x) + " " print result.strip() test_cases.close()
6e14cbcd144e3de7c1e05d77abdd187e81ddca36
Gaterny/PythonTechnical
/algorithm/冒泡排序
431
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 时间复杂度:O(n^2) # 稳定性:稳定 def bubble_sort(alist): # 遍历次数 for i in range(len(alist)-1): # 每次遍历比较次数呈递减 for j in range(len(alist)-1-i): # 比较前后位置的大小,并交换位置 if alist[j] > alist[j+1]: alist[j], alist[j+1] = alist[j+1], alist[j] return alist
b4dcd1486de6280afc20f968f50f42e8e70c3bf0
ZeroxZhang/pylearning
/except.py
248
4.21875
4
#代码报错时,自定义错误输出内容 try: print(10/0) except: print("0 cannot be divided~") #标准的数据 try: print(10/8) print(10+"0") except ArithmeticError as e: print(e) except TypeError as t: print(t)
fe60b86ca377e8697e0bddd0a01bfab487c68154
raymonddtrt/Design-Pattern
/Strategy/2-1.py
711
3.984375
4
#生成cashier類別 class Cashier: #建構式 def __init__(self,price,amount): self.price = price self.amount = amount #用來顯示的方法 def total(self): return Calculator(self.price,self.amount).calculate() #簡麗calculate物件。用來計算,繼承Cashier class Calculator(Cashier): #建構式,繼承Cashier才能把參數傳進來 def __init__(self,price,amount): self.price = price self.amount = amount #計算 def calculate(self): return self.price * self.amount def main(): price = input("請輸入單價:") amount = input("請輸入數量:") print(Cashier(int(price),int(amount)).total()) main()
aa7647dd4a117b8553569668e23efa58cc8f60e8
rafaelperazzo/programacao-web
/moodledata/vpl_data/49/usersdata/98/17379/submittedfiles/pico.py
358
3.703125
4
# -*- coding: utf-8 -*- from __future__ import division #def pico(lista): #CONTINUE... n = input('Digite a quantidade de elementos da lista: ') #CONTINUE... a=[] for i in range(0,n,1): a.append(input('Digite um valor: ')) posicao=0 for i in range(0,len(a)-1,1): if a[i]>a[i+1]: posicao=i break print posicao
8f384bceefe2e1758c9697738639b5fb3adee2d3
Armando101/Programaci-n-Concurrente
/17-Eventos.py
1,401
3.546875
4
import time import logging import threading logging.basicConfig(level=logging.DEBUG, format='%(threadName)s : %(message)s') """ Un evento internamente contiene una bandera, verdadero o falso Por default la bandera comienza en falso Una vez la bandera cambia a verdadero se dispara una señal Todos los threads que se encuentren a la espera de esa señal van a reanudar su ejecución Podemos conocer si la señal fue dada através del método is_set() Podemos establecer la bandera neuvamente en false con el método clear """ def thread_1(event): logging.info('Hola, soy el thread número uno') logging.info('Estoy a la espera de la señal') # Con event wait indicamos que se detenga el thread # Se reanudará cuando reciba una señal event.wait() logging.info('La señal fue dada, la bandera es True') def thread_2(event): while not event.is_set(): logging.info('A la espera de la señal') time.sleep(0.5) if __name__ == '__main__': event = threading.Event() # Bandero = True o False thread1 = threading.Thread(target=thread_1, args=(event, )) thread2 = threading.Thread(target=thread_2, args=(event, )) thread1.start() thread2.start() # Simulamos que el thread principal está relizando un tarea compleja time.sleep(3) # Con el método set envíamos la señal para que el thread continue event.set() # Podemos volver a colocar la bandera en True # event.clear()
6d4502fab466787f0e51ec6bf342719a0ef94692
KaiserSamrat/left-rotation-array-solution
/left-rotation.py
422
3.875
4
def rotateLeft(a, d,n): length = len(a) newArray = [0 for x in a] # Initialize 0 in an array of size 5. for i in range(n): newElement = i-d newArray[newElement]=str(a[i]) result = " ".join(newArray) return result def main(): arr = [1,2,3,4,5] d = 4 n = 5 result = rotateLeft(arr, d,n) print(result) if __name__ == "__main__": main()
f135bf627f4f64964a4b5c09c7c4147419236f74
IvayloSavov/Programming-basics
/loops_part_2_exercise/vacation_my.py
746
3.828125
4
needed_money = float(input()) available_money = float(input()) days_spend = 0 total_days = 0 spend_5_days = False while available_money < needed_money: type_command = input() money_spend_save = float(input()) total_days += 1 if type_command == "save": days_spend = 0 available_money += money_spend_save elif type_command == "spend": days_spend += 1 if money_spend_save > available_money: money_spend_save = available_money available_money -= money_spend_save if days_spend >= 5: spend_5_days = True break if spend_5_days: print(f"You can't save the money.") print(f"{total_days}") else: print(f"You saved the money for {total_days} days.")
4adfd5d86e17b37017f0205ee46898af43d9dd45
Atul-Nambudiri/AIMPS
/cs440_pacman/dfs.py
2,879
3.953125
4
from stack import stack import copy def dfs(maze, start, end, walls): """ This function runs DFS on the maze to find a path from start to end """ m_stack = stack() #Inits a stack to store nodes in visited = copy.deepcopy(walls) prev = copy.deepcopy(maze) #Keeps track of the previous for a particular node opened = 0 m_stack.push(start) #Put in start into the stack prev[start[0]][start[1]] = None #Iterate until the stack is empty while not m_stack.isEmpty(): opened += 1 current = m_stack.pop() #Remove a node from the stack if visited[current[0]][current[1]] == False: visited[current[0]][current[1]] = True if current[0] == end[0] and current[1] == end[1]: #If you have reached the end, return break else: #This checks all neighbors, top, right, bottom, left, to see if we can move there if not (current[0] - 1) < 0 and not visited[current[0] -1][current[1]]: prev[current[0] -1][current[1]] = [current[0], current[1]] #Set the previous for the neighbor to be the current node m_stack.push([current[0] -1 , current[1]]) #Push it onto the stack if not (current[1] + 1) >= len(walls[0]) and not visited[current[0]][current[1] + 1]: prev[current[0]][current[1] + 1] = [current[0], current[1]] m_stack.push([current[0], current[1] + 1]) if not (current[0] + 1) >= len(walls) and not visited[current[0] + 1][current[1]]: prev[current[0] + 1][current[1]] = [current[0], current[1]] m_stack.push([current[0] + 1 , current[1]]) if not (current[1] - 1) < 0 and not visited[current[0]][current[1] - 1]: prev[current[0]][current[1] - 1] = [current[0], current[1]] m_stack.push([current[0] , current[1] - 1]) path = copy.deepcopy(maze) current = end steps = 0 while maze[current[0]][current[1]] != 'P': #Go to the end point, and build out the solution path back to the start by following the previous values for each node current = prev[current[0]][current[1]] path[current[0]][current[1]] = '.' steps += 1 #Keep track of the number of steps you have taken path[start[0]][start[1]] = 'P' return path, steps, opened #Return the path, solution cost, and number of nodes expanded if __name__ == "__main__": maze = [['%', '%', '%', '%', '%'], ['%', '%', '%', '%', '%', '%'], ['%', '', '', '', '', '%'], ['%', '', '%', '', '%', '%'], ['%', '.', '%', '', 'P', '%'], ['%', '%', '%', '%', '%', '%']] walls = [[True, True, True, True, True, True], [True, True, True, True, True, True], [True, False, False, False, True, True], [True, False, True, False, True, True], [True, False, True, False, False,True], [True, True, True, True, True, True]] path, steps, opened = dfs(maze, (4, 1), (4, 4), walls) for line in path: print(line) print("Steps: %s" % (steps)) print("Nodes Visited: %s" % (opened))
7fbecea1be4d4e5bd272eabdd8442b8a25154264
guyman575/CodeConnectsJacob
/semester2/lesson7/linkedlist.py
740
3.984375
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp != None: print(temp.data) temp = temp.next # here temp is None def pushFront(self, newData): newNode = Node(newData) temp = self.head self.head = newNode newNode.next = temp def pushBack(self, newData): newNode = Node(newData) temp = self.head if temp == None: self.head = newNode else: while temp.next != None: temp = temp.next temp.next = newNode
59c975c02cdfd2d9ce0c2fce771afbf8379a5086
xudalin0609/leet-code
/DataStructure/dataStream.py
1,906
3.671875
4
""" 960. 数据流中第一个独特的数 II 中文English 我们需要实现一个叫 DataStream 的数据结构。并且这里有 两 个方法需要实现: void add(number) // 加一个新的数 int firstUnique() // 返回第一个独特的数 样例 例1: 输入: add(1) add(2) firstUnique() add(1) firstUnique() 输出: [1,2] 例2: 输入: add(1) add(2) add(3) add(4) add(5) firstUnique() add(1) firstUnique() add(2) firstUnique() add(3) firstUnique() add(4) firstUnique() add(5) add(6) firstUnique() 输出: [1,2,3,4,5,6] 注意事项 你可以假设在调用 firstUnique 方法时,数据流中至少有一个独特的数字 """ class DataStream: def __init__(self): self.dummy = ListNode(0) self.tail = self.dummy self.num_to_prev = {} self.duplicates = set() """ @param num: next number in stream @return: nothing """ def add(self, num): if num in self.duplicates: return if num not in self.num_to_prev: self.push_back(num) return # find duplicate, remove it from hash & linked list self.duplicates.add(num) self.remove(num) def remove(self, num): prev = self.num_to_prev.get(num) del self.num_to_prev[num] prev.next = prev.next.next if prev.next: self.num_to_prev[prev.next.val] = prev else: # if we removed the tail node, prev will be the new tail self.tail = prev def push_back(self, num): # new num add to the tail self.tail.next = ListNode(num) self.num_to_prev[num] = self.tail self.tail = self.tail.next """ @return: the first unique number in stream """ def firstUnique(self): if not self.dummy.next: return None return self.dummy.next.val
53367ea1b19756b89e3591b154c37862c84011a6
venkataniharbillakurthi/python-lab
/ex-8.py
245
4.25
4
word=input('Enter the word') status=Flase for i in "aeiouAEIOU": status=True if status==True: print("word contains vowels") else: print("word doesn't contains vowels") #output #Enter the word:why #word contains vowels
a322062a7f59c37313aea7cd4da1975ea7e16cde
lucasdealmeidadev/Python
/Composição/Exemplo - 1/main.py
404
3.546875
4
from classes import Motor, Carro; carro01 = Carro(1, 'Honda Civic', '4 cilindros'); print('\n-------------------MOTOR-------------------\n'); print('Id do motor = ',carro01.getIdMotor()); print('Modelo do motor = ',carro01.getMotor()); print('\n-------------------CARRO-------------------\n'); print('Id do carro = ',carro01.getId()); print('Modelo do carro = ',carro01.getModelo());
9d4e17cacb3b15af3e7e27022e17485bc652e45d
ColorfulCodes/Algo-Grind
/JerAguilon/CoinChange/Coins/__init__.py
387
3.90625
4
def coinChange(coins, amount): need = [0] + [amount + 1] * amount if len(coins) == 0: raise ValueError('Must insert a list of coin types') for c in coins: for a in range(c, amount+1): need[a] = min(need[a], need[a - c] + 1) if need[-1] <= amount: return need[-1] else: return -1 coinChange([1, 2, 5],11) coinChange(0,11)
e1669201384c661bd649077dc7cd54ef2c6b178b
aktersabina122/CSI-31-Academic-Project-
/CSI 31 (Introduction of Python)/Project 2 (Average of n integer).py
576
4.03125
4
#CSI 31 Sabina Akter Avg.py #This program calculates the average of n integers def main(): print( "This program computes the average of n integers. ") print() n = eval(input("How many? ")) sum = 0 for i in range(n): a = eval(input("Enter a number? ")) sum = sum + a avg = sum/n print() print("The average is", round(avg,4)) main() """ This program computes the average of n integers. How many? 4 Enter a number? 10 Enter a number? 2 Enter a number? 3 Enter a number? 5 The average is 5.0 """
a7ac77a3056340362cb484e74dcb8c8c5fd8ccfc
mmankt2/CodingDojo
/Python/OOP/users-w-bankaccounts.py
2,150
4.28125
4
#!/usr/bin/python3 class User: # here's what we have so far def __init__(self, name, email): self.name = name self.email = email self.account = BankAccount(int_rate = 0.02,balance =0) # adding the deposit method def make_deposit(self, amount): # takes an argument that is the amount of the deposit self.account.deposit(amount) #call the BankAccount deposit method return self def make_withdrawal(self, amount): #taks an argument that is the amount of the withdrawal self.account.withdraw(amount) #call the BankAccount withdraw method return self def display_user_balance(self): #print the user's name and account balance print("{}: ${}".format(self.name,self.account.balance)) return self class BankAccount: def __init__(self,int_rate,balance): # don't forget to add some default values for these parameters! # your code here! (remember, this is where we specify the attributes for our class) # don't worry about user info here; we'll involve the User class soon self.int_rate = 0.01 self.balance = 0 def deposit(self, amount):#increases the account balance by the given amount # your code here self.balance += amount return self def withdraw(self, amount):#decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5 # your code here if self.balance < amount: print("Insufficient funds: Charging a $5 fee.") self.balance = self.balance - 5 return self else: self.balance = self.balance - amount return self def display_account_info(self):#print to the console: eg. "Balance: $100" # your code here print("Balance: ${}".format(self.balance)) return self def yield_interest(self):#ncreases the account balance by the current balance * the interest rate (as long as the balance is positive) # your code here self.balance = self.balance + self.balance * self.int_rate return self melissa = User("Melissa Littleton","[email protected]") melissa.make_deposit(50).make_withdrawal(25).display_user_balance()
25568ea2097de0f9c7e256145c4831a433f2175c
Industrial-Functional-Agent/cs231n
/Assignment1/doogie/numpy_prac/Scipy_prac.py
4,358
3.71875
4
# Scipy # Numpy provides a high-performance multidimensional array and # basic tools to compute with and manipulate these arrays. # Scipy builds on this, and provides a large number of functions # that operate on numpy arrays and are useful for different types # of scientific and engineering applications. # Image operations # Scipy provides some basic functions to work with images. # For example, it has functions to read images from disk # into numpy arrays, to write numpy arrays to disk as images, # and to resize images. Here is a simple example that # showcases these functions: from scipy.misc import imread, imsave, imresize from scipy.spatial.distance import pdist, squareform import numpy as np import matplotlib.pyplot as plt # Read an JPEG image into a numpy array img = imread('assets/cat.jpg') print img.dtype, img.shape # Prints "uint8 (400, 248, 3)" # We can tint the image by scaling each of the color channels # by a different scalar constant. The image has shape (400, 248, 3); # we multiply it by the array [1, 0.95, 0.9] of shape (3,); # numpy broadcasting means that this leaves the red channel unchanged, # and multiplies the green and blue channels by 0.95 and 0.9 # respectively. img_tinted = img * [1, 0, 0.9] # Resize the tinted image to be 300 by 300 pixels. img_tinted = imresize(img_tinted, (300, 300)) # Write the tinted image back to disk imsave('assets/cat_tinted.jpg', img_tinted) # MATLAB files # The functions scipy.io.loadmat and scipy.io.saveamat allow you # to read and write MATLAB files. # Distance between points # Scipy defines some useful functions for computing distance # between sets of points # The function scipy.spatial.distance.pdist computes the distance # between all pairs of points in a given set: # Create the following array where each row is a point in 2D space: # [[0 1] # [1 0] # [2 0]] x = np.array([[0, 1], [1, 0], [2, 0]]) print x # Compute the Euclidean distance between all rows of x. # d[i, j] is the Euclidean distance between x[i, :] and x[j, :], # and d is the following array: # [[0. 1.414 2.236] # [1.414 0. 1. ] # [2.236 1. 0. ]] d = squareform(pdist(x, 'euclidean')) print d # Matplotlib # Matplotlib is plotting library. In this section give a brief # introduction to the matplotlib.pyplot module, which provides # a plotting system similar to that of MATLAB. # Plotting # The most important function in matplotlib is plot, which # allows you to plot 2D data. Here is a simple example: # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) # Plot the points using matplotlib plt.figure(1) plt.plot(x, y) # plt.show() # You must call plt.shoe() to make graphics appear. # With just a little bit of extra work we can easily plot # multiple lines at once, and add a title, legend, and axis labels: # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Plot the points using matplotlib plt.figure(2) plt.plot(x, y_sin) plt.plot(x, y_cos) plt.xlabel('x axis label') plt.ylabel('y axis label') plt.title('Sine and Cosine') plt.legend(['Sine', 'Cosien']) # plt.show() # Subplots # You can plot different things in the same figure using the subplot # functions. Here is an example: # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.figure(3) plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title('Sine') # Set the second subplot as acitve, and make the second plot. plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # Show the figure # plt.show() # Images # You can use the imshow functions to show images. # Here is an example: img = imread('assets/cat.jpg') img_tinted = img * [1.5, 1.5, 1.5] # Show the original image plt.figure(4) plt.subplot(1, 2, 1) plt.imshow(img) print img_tinted.dtype # Show the tinted image plt.subplot(1, 2, 2) # A slight gotcha with imshow is that it might five strange results # if presented with data that is not uint8. To work around this, we # explicitly cast the image to uint8 before displaying it. plt.imshow(np.uint8(img_tinted)) plt.show()
8b134e6c561840709e6fc8e1952cfe8d0f7a63cc
VerstraeteBert/algos-ds
/test/vraag4/src/isbn/15.py
1,699
3.734375
4
def isISBN13(code): if not( isinstance(code, str) and # input moet string zijn len(code) == 13 and # moet lengte 13 hebben code.isdigit() # moet numeriek zijn ): return False # als vorige 3 voorwaarden niet waar zijn return False if code[:3] not in {'978', '979'}: # eerste 3 digits moet 978 of 979 zijn return False # als eerste 3 digits niet 978 of 979 zijn return False controle = 0 for i in range(12): # check controlecijfer if i%2: controle += 3 * int(code[i]) else: controle += int(code[i]) controlecijf = controle % 10 controlecijf = (10 - controlecijf) % 10 return controlecijf == int(code[-1]) def overzicht(codes): groepen = {} # aanmaken groepen list for i in range(11): # opvullen met 0 groepen[i] = 0 for code in codes: if not isISBN13(code): groepen[10] += 1 # tel 1 bij Fouten else: groepen[int(code[3])] += 1 # als wel geldig ISBN dan tel bij grpoup gelijk aan 4de cijfer in code print('Engelstalige landen: {}'.format(groepen[0] + groepen[1])) # uitprinten print('Franstalige landen: {}'.format(groepen[2])) print('Duitstalige landen: {}'.format(groepen[3])) print('Japan: {}'.format(groepen[4])) print('Russischtalige landen: {}'.format(groepen[5])) print('China: {}'.format(groepen[7])) print('Overige landen: {}'.format(groepen[6] + groepen[8] + groepen[9])) print('Fouten: {}'.format(groepen[10]))
dde024fe9258df419e7a7eba953f6f43dd120fa0
SurekshyaSharma/Variables
/ftoc.py
321
3.96875
4
def f2c(fahr): Celsius = (fahr - 32) * 5 / 9 # Fahrenheit = 9.0/5.0 * Celsius + 32 rounded_Celsius = round(Celsius, 2) result = rounded_Celsius return result def main(): value = float(input("Enter the temperature in degree F: ")) print(value, "degree F is",f2c(value),"degree C") main()
ce0f78e1097e21437c7facc26e30fdd382d23210
orffen/cepheus
/dice.py
1,254
4.09375
4
# dice.py -- Dice class definition and related functions # # Copyright (c) 2020 Steve Simenic <[email protected]> # # This file is part of the Cepheus Engine Toolbox and is licensed # under the MIT license - see LICENSE for details. from typing import List import math import random import sys class Dice(object): def __init__(self): self.result: int = 0 self.rolls: List[int] = [] def __str__(self): return "Last roll: {} = {}".format(self.rolls, self.result) def roll(self, number: int = 2) -> int: """Roll a number of dice (2 by default) and return the result Also stores the result in self.result, and each individual die roll in self.rolls. Keyword arguments: number -- number of dice to roll (default 2) """ self.rolls = [] for _ in range(number): self.rolls.append(random.randint(1, 6)) self.result = sum(self.rolls) return self.result def roll_dice(number: int = 2): """Roll a number of dice (2 by default) and return the result""" d = Dice() return d.roll(number) if __name__ == "__main__": try: number = int(sys.argv[1]) except: number = 2 d = Dice() d.roll(number) print(d)
f1c5cd2927fbad1285ad79bca2cc3994cb7eda7c
Divya-vemula/methodsresponse
/strings/tuplefunction.py
101
3.765625
4
def is_even(n): return n%2==0 num=[1,5,2,8,9,7,6,4] even =list(filter(is_even,num)) print(even)
1163709041df658771b26f1f8a63fdd3013800f8
Avaneesh-tech/Atm
/atm.py
306
3.625
4
class Atm(object): def __init__(self,name,pin,): self.name=name self.pin=pin def info(self): print("Account name is : "+self.name) print("card pin is : "+self.pin) Atm1=Atm("Avaneesh Sawant","2364") Atm2=Atm("Sanjana Sawant","3018") Atm1.info()
f470df288a6b4826f56472f6a3a17618e5446851
jessimk/SklearncomPYre
/SklearncomPYre/split.py
2,876
3.625
4
# coding: utf-8 # In[ ]: from sklearn.model_selection import train_test_split import numpy as np import pandas as pd def split(X, y, ptrain, pvalid, ptest): """ The function splits the training input samples X, and target values y (class labels in classification, real numbers in regression) into train, test and validation sets according to specified proportions. The function Outputs four array like training, validation, test, and combined training and validation sets and four y arrays. Inputs: X data set, type: Array like Y data set, type: Array like proportion of training data , type: float proportion of test data , type: float proportion of validation data, type: float Outputs: X train set, type: Array like y train, type: Array like X validation set, type: Array like y validation, type: Array like X train and validation set, type: Array like y train and validation, type: Array like X test set, type: Array like y test, type: Array like Examples: # Splitting up datasets into 40% training, 20% vaildation, and 40% tests sets. X_train, y_train, X_val, y_val, X_train_val, y_train_val, X_test, y_test = split(X,y,0.4,0.2,0.4) See README for examples-- https://github.com/UBC-MDS/SklearncomPYre/blob/Jes/README.md """ #testing that X and y are both either dataframe or array types # if (type(X) != type(np.array(X)) and type(X) != type(pd.DataFrame(X))) or \ # (type(y) != type(np.array(y)) and type(y) != type(pd.DataFrame(y))) or \ # X.shape[0] != len(y): # raise TypeError("X or y are not the right type. X and Y should be the \ # same length and they should be either arrays or dataframes.\ # See documentation and try again ¯\_(ツ)_/¯ ") if type(X) != type(np.array([2,2])) and type(X) != type(pd.DataFrame([2,2])): raise TypeError("X isn't the right type. Make sure it's a dataframe or array ¯\_(ツ)_/¯ ") elif type(y) != type(np.array([2,2])) and type(y) != type(pd.DataFrame([2,2])): raise TypeError("y isn't the right type. Make sure it's a dataframe or array ¯\_(ツ)_/¯ ") #testing that X and y have the same number of rows and have at least 3 rows elif (X.shape[0] != len(y)) and (len(y) < 3): raise TypeError("X & y lengths don't match. Both X & y need to have at least 3 rows. Try again ¯\_(ツ)_/¯ ") else: X_train_validation, X_test, y_train_validation, y_test = train_test_split(X, y, test_size= ptest) validation_ratio = round(pvalid/(ptrain + pvalid),2) X_train, X_validation, y_train, y_validation = train_test_split(X_train_validation, y_train_validation, test_size=validation_ratio) return X_train,y_train,X_validation, y_validation,X_train_validation,y_train_validation,X_test,y_test
e568187a893786a4ecec8c486e58951cc31301ae
loudbrightraj/Chain_reaction_Python_Version_1
/src/core/Game_controller.py
812
3.828125
4
''' Created on Sep 17, 2015 @author: H141517 ''' from Grid import Grid from Player import Player def main(): ''' Controller which starts the game. ''' possible_color = ['red','blue','green','yellow','orange','brown','black'] grid_size = 8 players = [] no_of_players = input("How many players") if no_of_players < 7 and no_of_players >1: count = 0 while count < no_of_players: color = possible_color[count] name = 'Player_'+str(count) print 'color',color,'name',name players.append(Player(color,name)) count += 1 grid = Grid(grid_size,players) grid.play() else: print (" That no of players are not permitted") if __name__ == '__main__': main()
5a3de4465748ae156f5eb7b8aa4814d38a1eae20
erik-hasse/pidrive
/pidrive/abstract/car.py
1,064
3.625
4
from abc import ABC class Car(ABC): def __init__(self, drive_motors, turning_motors): self._drive_motors = drive_motors self._turning_motors = turning_motors self.velocity = 0 self.angle = 0 def stop(): self.speed = 0 @property def angle(self): return self._angle @angle.setter def angle(self, new): for m in self._turning_motors: m.angle = new self._angle = new @property def speed(self): return self._drive_motors[0].speed @speed.setter def speed(self, new): for m in self._drive_motors: m.speed = new @property def velocity(self): return self._drive_motors[0].velocity @velocity.setter def velocity(self, new): for m in self._drive_motors: m.velocity = new @property def direction(self): return self._drive_motors[0].direction @direction.setter def direction(self, new): for m in self._drive_motors: m.direction = new
dec540503746546a5d69fbabd2870c3eaa8d77c9
gtenorio10/Codecademy_DS
/Python/Carly_Clippers.py
814
3.71875
4
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] prices = [30, 25, 40, 20, 20, 35, 50, 35] last_week = [2, 3, 5, 8, 4, 4, 6, 2] total_price = 0 for cost in prices: total_price+=cost print(total_price) average_price = total_price/len(prices) print("Average Haircut Price:", "$"+str(round(average_price, 2))) new_prices = [cost - 5 for cost in prices] print(new_prices) total_revenue = 0 for i in range(len(hairstyles)): total_revenue += prices[i] * last_week[i] print("Total Revenue:" "$"+ str(total_revenue)) average_daily_revenue = total_revenue/7 print("Average daily revenue: ", "$" + str(round(average_daily_revenue, 2))) cuts_under_30 = [hairstyles[i] for i in range(len(hairstyles)) if new_prices[i] < 30] print("Hairstyles under $30:",cuts_under_30)
c3f4ea1dc2d1a1fc19e553f146c0c8d053d4985f
marajput123/caesar-encryption
/caesar_encryption/password_decoder.py
6,820
4.34375
4
# ///This program will decode the password using the provided key # This is the key list. it will be used to dencode the passcode keyList = ["A","B","C","D","E","F","G","H","I","J",\ "K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] # This function will ask the the user to input the password def inputPassword(): password = input("\n\n\n\n------------\ -----------\nPlease provide a code to be decoded.\nCode: ") for i in password: if i.upper() not in (keyList or " "): print("\n\t--Error--\n--Please enter alphabet only--") return -1 else: return password # This function will ask for the user to input the key def inputKey(): # To check if the key is between 1-26 key = input("\nWhat is the key number from 1-26? \nKey: ") if key.lower() == 'back': return -2 elif int(key) not in range(0,27): print("\n\t---Error---\n--Please enter the correct key or type 'back' to go back--") return -1 else: return int(key) # This function takes in the password from inputPassword() and converts it into index def passwordToIndex(inputPassword): # the parameter is set equal to the variable password password = inputPassword # This is the list to which the index of each alphabet in the password will be appended to encodedIndex = [] # The for loop iterates through each unique alphabet in the password for alphabet in password: # this if statment checks if the alphabet is a space if alphabet != " ": # The for loop iterates through each alaphabet index in the key list for keyListAlphabet in range(0,len(keyList)): # this if statment will check if the alphabet is equal to the alphabet in the key list # if yes, the index of the alphabet in the key list is appended to the indexList # else, it continues to iterate through each alphabet in password, and thorugh the # index of each alphabet in the key list if alphabet.upper() == keyList[keyListAlphabet]: encodedIndex.append(keyListAlphabet) # if the alphabet is space, it is appended to the indexList as space elif alphabet == " ": encodedIndex.append(" ") # if the password is set to nothing, the function will return nothing else: return None return encodedIndex # This function will decode the encoded index from the passwordToIndex() # it takes in the encoded index and the key provided in inputKey() function def decodeIndex(encodedIndex, key): # This is the list to which the decoded index will be appended to decodedIndex = [] # The loop goes through each index in the function encodedIndex() for index in encodedIndex: # /*if the index equals space if index !=" ": # /*if the index-key is less than 0: if (index-key) < 0: # the index is set equal to 26 added to the negative number produced by # index-key. The index is then is appended to decodedIndex index = 26+(index-key) decodedIndex.append(index) # /*if the (index - key) is greater than 0, elif (index-key) >= 0: # index is set to (index-key), and is appended to decodedIndex index-=key decodedIndex.append(index) # /*if the index is equal to space, it is appended elif index == " ": decodedIndex.append(" ") else: return None return decodedIndex # This function takes in the decodedIndex and returns the decoded password as a string def indexToString(decodeIndex): # the string to which the decoded alphabets will be appended to string = "" # the for loop iterates through index in the decodeIndex for index in decodeIndex: # /*if the index does not equal space: if index != " ": # the index is passed into keylist, which outputs the decoded alphabet # then it is added to the string alphabet = keyList[index] string+=alphabet # /*if the index does equal space elif index == " ": # the space is added to the string string+= index return string # this fuction checks if the alphabet is meant to be lower case or uppercase def checkCase(decodedPassword, encodedPassword): # The string to which the correctly cased decoded password will be appended to string="" # the for loop goes through alpahbet index in the decodedPassword variable for index in range(0,len(decodedPassword)): # if the alphabet at index in encodedPassword is equal to the its lowercase alpahbet if encodedPassword[index]==encodedPassword[index].lower(): # the alphabet at index in decodedPassword is converted to lowercase and # appended to the string string+=decodedPassword[index].lower() # if the alphabet at index in encodedPassword is not equlal to its lowercase # alphabet, or the the alphabet at index is actually a space. The alphabet is not # changed and appended to the string else: string+=decodedPassword[index] return string # Main screen def mainScreen(): try: while True: # This asks for the user input (1 or 2) and returns userInput = int(input("\n\n\n\n---Security Cipher---\n1.) Decode\n2.) Quit\nChoose Navigation number: ")) if userInput in (1,2): return userInput else: print("Invalid Input") except: print("Invalid input") def control(): input("Back to Main Menu") return # Main Method def main(): while True: userInput = mainScreen() if userInput == 1: controlCheck1 = inputPassword() if controlCheck1 == -1: control() continue while True: controlCheck2 = inputKey() if controlCheck2 == -1: continue elif controlCheck2 == -2: break else: enIndex = passwordToIndex(controlCheck1) deIndex = decodeIndex(enIndex, controlCheck2) string = indexToString(deIndex) final = checkCase(string, controlCheck1) print("\nDecoded test: {}".format(final)) control() break if userInput == 2: print("\n\n\n\n\nThank you.") break if __name__ == "__main__": main()
360fc692c900021341c9c10e5a975ee6c19be57e
win911/UT_class
/for_pytest/exercises/1/my_math.py
117
3.671875
4
# my_math.py def is_multiples_of_three(num): if num % 3 == 0: return True else: return False
ff0aaee034f8848353b361e6c06514b2b0734726
udayt-7/Python-Assignments
/Assignment_1_Basic_Python/s1p17.py
278
4.25
4
# to count no of vowels in string str1= input("Enter string:") vowels=0 for i in str1: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels=vowels+1 print("Number of vowels are:", vowels)
7810cc3bff3d4d7f68148b9e27252dde2166363a
grivanov/python-basics-sept-2021
/IV.11-clever-lilly.py
546
3.5
4
lilly_years = int(input()) wm_price = float(input()) toy_price = int(input()) money_received = int() toys_received = int() even_birthdays = 0 for num in range(1, lilly_years + 1): if num % 2 == 0: money_received += num * 5 even_birthdays += 1 else: toys_received += 1 money_received -= even_birthdays toy_money = toys_received * toy_price total_saved_money = money_received + toy_money diff = total_saved_money - wm_price if diff >= 0: print(f"Yes! {diff:.2f}") else: print(f"No! {abs(diff):.2f}")
e91f4e8727e2204b859e074c988835d3bb7eaf04
p4thakur/PythonScripts
/drawCircleUsingRectangle.py
471
3.796875
4
import turtle def drawSquare(some_turtle): for i in range(0,4): some_turtle.forward(100) some_turtle.right(90) def drawRect(): window=turtle.Screen() window.bgcolor("red") brad=turtle.Turtle() brad.shape("turtle") # this mean my drawing tool will lokk like a turtle brad.color("green") brad.speed(2) for i in range(0,36): #drwaw a square and let rotate it by 10 degree drawSquare(brad) brad.right(10) #window.exitonclick() drawRect()
328ea03c58336cb6e7241cb9dc109115c0b60e03
aryamangoenka/c-98
/c-98/countingwords.py
261
4.15625
4
def countwords(): test1=input("enter the file name ") words=0 file=open(test1,"r") for line in file: word=line.split() print(word) words=words+len(word) print("no. of words ") print(words) countwords()
5b6337d85519db6267d3e417ace054d8fe831e2a
avrahamm/python-bootcamp-062020
/lesson19/ex4/ex4.py
629
3.796875
4
import sys from collections import defaultdict # Well done - loved it def build_anagrams_dict(): filename = sys.argv[1] # words anagrams_dict = defaultdict(set) with open(filename, "r") as f: for word in f: clean_word = word.strip() key = (''.join(sorted(clean_word))) anagrams_dict[key].add(clean_word) return anagrams_dict try: anagram_sets = build_anagrams_dict() except Exception: print("Illegal input file name") exit(1) for anagram_words in anagram_sets.values(): anagrams_list = list(anagram_words) print(' '.join(anagrams_list))
b1d428cbcae752e7a46db5713c0d58042bda0724
pdxgitit/python_class
/teaching/11.py
332
3.671875
4
# You will be provided with an initial list (the first argument # in the destroyer function), followed by one or more arguments. # Remove all elements from the initial array that are of the same # value as these arguments. def destroyer(first, *argv): return print(destroyer([1, 2, 3, 1, 2, 3], 2, 3)) # should return [1, 1]
be81acb668da2dc8f26ad6979109153838c7644a
Araym51/Ostroumov_Egor_DZ
/Lesson_2/Task_2_1.py
401
4.09375
4
# Задание 1 # Выяснить тип результата выражений: # 15 * 3 # 15 / 3 # 15 // 2 # 15 ** 2 a = 15 * 3 b = 15 / 3 c = 15 // 2 d = 15 ** 2 print('тип переменной a = 15 * 3', type(a)) print('тип переменной b = 15 / 3', type(b)) print('тип переменной c = 15 // 2', type(c)) print('тип переменной d = 15 ** 2', type(d))
c7cf7bf4c90aded76c7590b217d506c7385637fa
hseritt/idea-sandbox
/using_dicts_switch_case/demo1.py
179
3.75
4
#!/usr/bin/env python def subtract(num1, num2): return num1 - num2 func = { '-': subtract, } if __name__ == '__main__': diff = func['-'](6, 3) print(diff)
0435d7048f2045dff873f0c51e6f06661559289f
tylors1/Leetcode
/Problems/jewels.py
180
3.609375
4
J = "aA" S = "aAAbbbb" def jewels(J, S): count = 0 j_set = set([letter for letter in J]) for char in S: if char in j_set: count += 1 return count print jewels(J, S)
f18a126e62df6b105fb9dcdcbec2936f7c60cf7c
CARLOSC10/T06_LIZA.DAMIAN-ROJAS.CUBAS
/LIZA_DAMIAN_CARLOS/SIMPLES/condicionales_simples07.py
828
3.75
4
#CONDICIONAL SIMPLE QUE CALCULA EL AREA DE TRAPECIO import os Base_mayor,Base_menor,altura=0,0,0 #ARGUMENTOS Base_mayor=int(os.sys.argv[1]) Base_menor=int(os.sys.argv[2]) altura=int(os.sys.argv[3]) #PROCESSING area_trapecio=((Base_mayor+Base_menor)/2*altura) #OUTPUT print("##########################################") print("# AREA DEL TRAPECIO #") print("##########################################") print("# BASE MAYOR: ",Base_mayor," ") print("# BASE MENOR: ",Base_menor," ") print("# ALTURA: ",altura," ") print("# AREA TRAPECIO: ",area_trapecio," ") print("##########################################") #CONDICIONAL SIMPLE #SI EL AREA DEL TRAPECIO ES >150 if (area_trapecio > 150): print(" EL AREA DEL TRAPECIO ES MAYOR QUE 150") #fin_if
ec7861c62e3a4c2897aa0d8e5b2f72f585c62251
eLtronicsVilla/Miscellaneous
/Python/fundamental/test3.py
59
3.578125
4
iterable = [1,2,3,4] for item in iterable: print(item)
a525a8871b9a9eb10b27570d79851c83b72d273f
hyro64/Python_growth
/Day 8/Exercises/8-7Album.py
292
3.8125
4
def make_album(artist, album, tracks = ''): """Returns a dictionary of albums""" completed_album = {"Artist: ": artist, "Album: ": album} if tracks: completed_album['tracks'] = tracks return completed_album completed = make_album("jimi","Voodoo Child", tracks = 12) print(completed)
d217bac5f6d7f1e31f3b7a74f18c1f3e8cc1560a
KevinPautonnier/MachineLearning
/cours5.1.py
1,112
3.53125
4
""" Premier exercice de notre cinquième cours de machine learning. Le but était d'utiliser surprise pour prédire la note que donnerai un utilisateur spécifique pour un film en fonction de ses notes sur d'autres films. Surprise nous fournis les données nécessaires. """ from surprise import SVD from surprise import Dataset from surprise.model_selection import train_test_split import matplotlib.pyplot as plt def main(): """ ... """ #get data from surprise data = Dataset.load_builtin('ml-100k') trainset, testset = train_test_split(data, test_size=.25) algo = SVD() # Train the algorithm on the trainset, and predict ratings for the testset algo.fit(trainset) predictions = algo.test(testset) #calculate the delta x = [elem[2] - elem[3] for elem in predictions] #number of column in the graph clmnNb = 69 plt.hist(x, clmnNb, facecolor='b', alpha=0.75) plt.xlabel('Delta values') plt.ylabel('Number of same delta') plt.title('Delta of rating') plt.show() if __name__ == "__main__": main()
966fffddd0fb7a3a660c209198e707e5fe3bd621
JoseEscudero07/Archivos-Python
/ejercicio_6.py
153
3.671875
4
peso = float(input("Digite su peso en [kg]: ")); Estatura = float(input("Digite su Estatura en [cm]: ")); imc = peso/pow(Estatura,2); print("IMC: ",imc)
adf5e47ef4d4049b55a035be8569b7389f016392
ranafge/all-documnent-projects
/scrapy_file/python_re_details.py
595
3.546875
4
# You may use a Negative Lookahead (?!...) to ensure that content following the # digit is not a letter you set # # Here an example where all digits followed by any of there char GJK are not concerned by the suppression import re sentenc = "On 11 December 2008, India entered the 3G arena 1A 3J 5K" print(re.sub(r"\d(?![GJKA])", "",sentenc )) print(re.sub(r"\d(?![GJK])", '' ,sentenc )) # On December , India entered the 3G arena A 3J 5K sentence ="{\"data\":{\"correlation_id:\"51g0d88f-3ab8-4mom-betb-b31ed6e1662z\",\"u_originator_uri" print(re.search(r"correlation_id:(.*\W+)",sentence))
ddc2dd587144bb2c53824011368091552efd5c3f
anusha4999/anusha
/python/tasks/loops/l1.py
159
3.671875
4
num=int(input('enter a number')) sum=0 n=num while n>0: rem=n%10 sum=sum+rem*rem*rem #n//=10 n=n//10 if num==sum: print('ams') else: print('not a ams')
b24a38e00ddf62eb3ed1f7129197857d299e2f43
Jmwas/Hangman
/Hangman.py
1,219
3.984375
4
""" Word guessing game based on hangman. You get seven tries to guess a letter. """ import random from dictionary import dict while True: question = input("Do you want to continue? Y/N: ") question.lower() if question not in ('y', 'n'): print("Please select y or n") continue elif question == 'y': word = random.choice(dict) # generates a random word from the dictionary word1 = word tries = 7 choice = '' print('You have %s tries' % tries) while tries != 0 and word1 != '': a = input("Please guess a letter: ") if a in word1: print('%s is in the word' % a) word1 = word1.replace(a, '') choice += str(a) else: print('wrong, %s is not in the word' % a) choice += str(a) tries -= 1 print('you have %s tries remaining' % tries) if word1 == '': print('\nGame over. You win!! \nThe word is %s \nYou choice letters are %s' % (word, choice)) else: print('\nGame over. You lose!! \nThe word is %s \nYou choice letters are %s' % (word, choice)) break
e1db1e1c7bc20877b6f396fd89236880828b08ea
MBras/AOC2020
/15/part2.py
1,750
3.828125
4
def playgame(inp): if len(inp) % 10000 == 0: print "size: " + str(len(inp)) #print "input: " + str(inp) last = inp.pop() search = 1 searchinp = inp[::-1] #print "looking for " + str(last) + " in " + str(searchinp) inp.append(last) try: search = searchinp.index(last) #print "Looking for: " + str(last) + ", found: " + str(search) inp.append(search + 1) except ValueError: #print "Looking for: " + str(last) + ", found nothing" inp.append(0) #==============[ Part 1 ]============== inp = [15,5,1,4,7,0] for x in range(2020 - len(inp)): playgame(inp) #print inp print "Part 1: " + str(inp.pop()) #==============[ Part 2 ]============== def prepinp(inp, numbers): # convert the input to an indexed array for x in range(len(inp)): numbers[inp[x]] = x print numbers inp = [15,5,1,4,7] nextvalue = 0 numbers = {} prepinp(inp, numbers) steps = 30000000 # loop for 30.000.000 steps for turn in range (len(inp), steps - 1): if turn % 1000000 == 0: print "Turn " + str(turn + 1) + " looking for " + str(nextvalue) # check if the next value already exists if nextvalue in numbers: # if yes determine currentstep - value of key (difference) -> nextvalue difference = turn - numbers[nextvalue] #print "Found " + str(nextvalue) + ", " + str(difference) + " steps ago" numbers[nextvalue] = turn nextvalue = difference else: # if no add it as key with value currentstep and proceed to check for 0 (nextvalue) #print "Didn't find " + str(nextvalue) numbers[nextvalue] = turn nextvalue = 0 # print numbers print "Part 2: " + str(nextvalue)
5761e4389371f1291bf97aed3501a669beeb5376
zaarabuy0950/assignm_2
/datatypes/33.py
253
4.125
4
"""33. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys""" n = int(input("Enter the end of list: ")) dict1 = {} for i in range(1,n): dict1[i]=i**2 print(dict1)
94e4cf21536e44dca8b72e43e762c910450a2939
effyhuihui/leetcode
/RectangleCircleProccess/spiralMatrix.py
1,793
4.1875
4
__author__ = 'effy' # -*- coding: utf-8 ''' Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 有一种方法哦,就是每次打印矩形的外面一圈,然后再打印里面一圈,一点点打印到最里面(一圈表示四边) ''' class Solution: # @param {integer[][]} matrix # @return {integer[]} def spiralOrder(self, matrix): res = [] if len(matrix) == 0: return res m,n = len(matrix),len(matrix[0]) def printCircle(start_m,start_n,width,height): ''' start_m, start_n represent the starting coordinate of the current circle width is the width of the circle, height is the height of the circle ''' ## --> right for k in range(width): res.append(matrix[start_m][start_n+k]) ## --> down for k in range(1,height): res.append(matrix[start_m+k][start_n+width-1]) ## --> left if height > 1: for k in range(1,width): res.append(matrix[start_m+height-1][start_n+width-1-k]) ## --> up if width > 1: for k in range(1,height-1): res.append(matrix[start_m+height-1-k][start_n]) start_m,start_n =0,0 while m >0 and n>0: printCircle(start_m, start_n,n,m) start_m += 1 start_n += 1 m-=2 n-=2 return res x = Solution() print x.spiralOrder([[2,5,8],[4,0,-1]]) print x.spiralOrder([[2,3]]) print x.spiralOrder([ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ])
c1e2eba9b3bedfb19991033d2deea033fbe3ce05
MartinWan/ACM-ICPC-Practice
/metaprogramming.py
761
3.703125
4
from fileinput import input namespace = dict() for line in input(): tokens = line.split() if tokens[0] == 'define': value = int(tokens[1]) symbol = tokens[2] namespace[symbol] = value else: # tokens[0] == 'eval' symbol1 = tokens[1] op = tokens[2] symbol2 = tokens[3] if symbol1 not in namespace or symbol2 not in namespace: print 'undefined' else: if op == '<': output = namespace[symbol1] < namespace[symbol2] elif op == '>': output = namespace[symbol1] > namespace[symbol2] else: # op is = output = namespace[symbol1] == namespace[symbol2] print str(output).lower() # convert True into true
4704b19bfbfcd30cb7c21b38f74a76c538210998
lerozhao/pythontest
/0401.py
1,756
3.609375
4
# list1=[1,2,3,4,5,6,7,8,9] # print(list1[1]) # print(list1[0:-1]) # print(list1[1::2]) # list2=["tab","tas"] # list1.extend(list2) # for i in list1: # list2.append(i) # list1.count() # list1.sort() # list1.remove() # i=0 # j=1 # while j<21: # print(j) # i,j=j,i+j # list1=[1,2,4,7] # for i in list1: # for j in list1: # for k in list1: # for l in list1: # if i!=j and i!=k and i!=l and j!=k and j!=l and k!=l: # print(1000*i+100*j+10*k+l) # list3=[] # for i in range(1,10,2): # list3.append(i) # print (list3) # def john(a,b): # # return a*b; # if a*b>10: # print('da') # elif a*b<10: # print('xiao') # else: # print('wrong') # john(3,5) # b=[1:'1',2:'2'] # def plus(b): # return b*10; # print(plus(b)) # print(b) # def sum(q,w): # t=q+w # print('nei',t) # return t; # t=sum(10,20) # print('wai',t) # def printinfo(arg1,*v): # print('shuchu') # print(arg1) # for var in v: # print(var) # return; # printinfo(10); # printinfo(70,60,50); # import sys # def f(a): # if a==1: # return a; # if a>1: # return a+f(a-1) # print(f(999)) # a=lambda x,y:x*x+y # print(a(3,2)) # for i in range(10): # age=i # print(age) # name ='1' # def f1(name): # print(name) # def f2(): # name='2' # f1(name) # f2() # num=input(2*6) # print(num) def make_counter(): count = 0 def counter(): nonlocal count count +=1 return count return counter def make_counter_test(): mc=make_counter() print(mc()) print(mc()) make_counter_test() # mcc=make_counter() print(make_counter) # print(mcc()) # print(mcc())
2ca0e8e0120c9e2e4bfbef8f2710f66aec4f1fb1
hailey1003/Projects
/AVLTree.py
15,158
3.765625
4
import random as r class Node: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'parent', 'left', 'right', 'height' def __init__(self, value, parent=None, left=None, right=None): """ Initialization of a node :param value: value stored at the node :param parent: the parent node :param left: the left child node :param right: the right child node """ self.value = value self.parent = parent self.left = left self.right = right self.height = 0 def __eq__(self, other): """ Determine if the two nodes are equal :param other: the node being compared to :return: true if the nodes are equal, false otherwise """ if type(self) is not type(other): return False return self.value == other.value and self.height == other.height def __str__(self): """String representation of a node by its value""" return str(self.value) def __repr__(self): """String representation of a node by its value""" return str(self.value) class AVLTree: def __init__(self): # DO NOT MODIFY THIS FUNCTION # """ Initializes an empty Binary Search Tree """ self.root = None self.size = 0 def __eq__(self, other): # DO NOT MODIFY THIS FUNCTION # """ Describe equality comparison for BSTs ('==') :param other: BST being compared to :return: True if equal, False if not equal """ if self.size != other.size: return False if self.root != other.root: return False if self.root is None or other.root is None: return True # Both must be None if self.root.left is not None and other.root.left is not None: r1 = self._compare(self.root.left, other.root.left) else: r1 = (self.root.left == other.root.left) if self.root.right is not None and other.root.right is not None: r2 = self._compare(self.root.right, other.root.right) else: r2 = (self.root.right == other.root.right) result = r1 and r2 return result def _compare(self, t1, t2): # DO NOT MODIFY THIS FUNCTION # """ Recursively compares two trees, used in __eq__. :param t1: root node of first tree :param t2: root node of second tree :return: True if equal, False if nott """ if t1 is None or t2 is None: return t1 == t2 if t1 != t2: return False result = self._compare(t1.left, t2.left) and self._compare(t1.right, t2.right) return result ### Implement/Modify the functions below ### def insert(self, node, value): """ Takes a value and inserts it into the tree in the form of a node :param node: the root/subroot of a tree for node to be added :param value: the value to be inserted :return: new root of tree """ the_node = Node(value) if self.root is None: self.root = the_node #self.root.height += 1 self.size += 1 else: if node is None: node = the_node self.size += 1 elif node.value > value: if node.left is None: node.left = the_node node.left.parent = node self.size += 1 else: node.left = self.insert(node.left, value) elif node.value < value: if node.right is None: node.right = the_node node.right.parent = node self.size += 1 else: node.right = self.insert(node.right, value) node.height = 1 + max(self.height(node.left), self.height(node.right)) new_node = self.rebalance(node) return new_node def remove(self, node, value): """ Removes a specific value from the tree :param node: root/subroot of tree to look for value and remove it :param value: Value to be removed from tree :return: new root of tree """ if node is None: return elif value < node.value: return self.remove(node.left, value) elif value > node.value: return self.remove(node.right, value) else: if self.root.value == value and self.root.left is None and self.root.right is None: self.size -= 1 original = self.root self.root = None self.root.parent = original.parent elif node.left is None and node.right is None: self.size -= 1 the_parent = node.parent if node.parent.right is node: node.parent.right = None node = None else: node.parent.left = None node = None the_parent.height = 1 + max(self.height(the_parent.left), self.height(the_parent.right)) self.rebalance(the_parent) elif node.left is None: self.size -= 1 if self.root.value == node.value: original = self.root self.root = node.right self.root.parent = original.parent elif node.parent.right is node: original = node node = node.right node.parent = original.parent node.parent.right = node else: original = node node = node.right node.parent = original.parent node.parent.left = node node.height = 1 + max(self.height(node.left), self.height(node.right)) node.parent.height = 1 + max(self.height(node.parent.left), self.height(node.parent.right)) self.rebalance(node) elif node.right is None: self.size -= 1 if self.root.value == node.value: original = self.root self.root = node.left self.root.parent = original.parent elif node.parent.right is node: original = node node = node.left node.parent = original.parent node.parent.right = node else: original = node node = node.left node.parent = original.parent node.parent.left = node node.height = 1 + max(self.height(node.left), self.height(node.right)) node.parent.height = 1 + max(self.height(node.parent.left), self.height(node.parent.right)) self.rebalance(node) else: replacement = self.max(node.left) node.value = replacement.value if self.root is node: if replacement.left: self.size -= 1 replacement.left.parent = node node.left = replacement.left else: self.remove(replacement, replacement.value) else: self.remove(replacement, replacement.value) node.height = 1 + max(self.height(node.left), self.height(node.right)) #node.parent.height = 1 + max(self.height(node.parent.left), self.height(node.parent.right)) self.rebalance(node) self.rebalance(self.root) return self.root def search(self, node, value): """ Searches for a specific value within the tree :param value: value to search for :param node: root of tree/subtree :return: node where value was found """ if node is None: return None if value < node.value: if node.left is None: return node else: return self.search(node.left, value) elif value > node.value: if node.right is None: return node else: return self.search(node.right, value) else: return node def inorder(self, node): """ Traverses tree with inorder method starting at node :param node: Node to start traversing :return: Generator object of tree traversed """ if node: yield from self.inorder(node.left) yield node yield from self.inorder(node.right) else: return def preorder(self, node): """ Traverses tree with preorder method starting at node :param node: Node to start traversing :return: Generator object of tree traversed """ if node: yield node yield from self.preorder(node.left) yield from self.preorder(node.right) else: return def postorder(self, node): """ Traverses tree with postorder method starting at node :param node: Node to start traversing :return: Generator object of tree traversed """ if node: yield from self.postorder(node.left) yield from self.postorder(node.right) yield node else: return def breadth_first(self, node): """ Traverses tree with breadth first method starting at node :param node: Node to start traversing :return: Generator object of tree traversed """ if node is None: return my_list = [] my_list.append(node) while (len(my_list) > 0): yield my_list[0] node = my_list.pop(0) if node.left is not None: my_list.append(node.left) if node.right is not None: my_list.append(node.right) def depth(self, value): """ Finds the depth of a node with the specific value in the tree :param value: Value to find depth of :return: Depth of value """ node = self.search(self.root, value) if node is None: return -1 elif node.value != value: return -1 else: count = 0 while node.parent: count += 1 node = node.parent return count def height(self, node): """ Finds the height of the tree rooted at the given node :param node: Node to find height of :return: Height of node """ if node: return node.height else: return -1 def min(self, node): """ Finds the minimum value of a tree rooted at the node :param node: Root node of tree/subtree to look for minimum value :return: Minimum node of tree/subtree """ if self.root is None: return None else: if node.left is None: return node else: return self.min(node.left) def max(self, node): """ Finds the maximum value of a tree rooted at the node :param node: Root node of tree/subtree to look for maximum valye :return: Maximum node of tree/subtree """ if self.root is None: return None else: if node.right is None: return node else: return self.max(node.right) def get_size(self): """ Gets size of tree :return: number of nodes in tree """ return self.size def get_balance(self, node): """ Gets the balance factor of a specific node :param node: Node to calculate balance factor of :return: balance factor of node """ if node: return self.height(node.left) - self.height(node.right) else: return 0 def left_rotate(self, root): """ Performs a left rotation of a tree/subtree rooted at root :param root: Root location of where left rotation will be performed :return: New root of tree/subtree """ y = root.right y.parent = root.parent if y.parent is None: self.root = y else: if y.parent.left is root: y.parent.left = y elif y.parent.right is root: y.parent.right = y root.right = y.left if root.right is not None: root.right.parent = root y.left = root root.parent = y root.height = max(self.height(root.left), self.height(root.right)) + 1 y.height = max(self.height(y.left), self.height(y.right)) + 1 return y def right_rotate(self, root): """ Performs a right rotation of a tree/subtree rooted at root :param root: Root location of where right rotation will be performed :return: New root of tree/subtree """ y = root.left y.parent = root.parent if y.parent is None: self.root = y else: if y.parent.left is root: y.parent.left = y elif y.parent.right is root: y.parent.right = y root.left = y.right if root.left is not None: root.left.parent = root y.right = root root.parent = y root.height = max(self.height(root.left), self.height(root.right)) + 1 y.height = max(self.height(y.left), self.height(y.right)) + 1 return y def rebalance(self, node): """ Rebalances a tree/subtree rooted at node :param node: Node to see if it needs to be rebalanced :return: New root of balanced tree """ if self.get_balance(node) == -2: if self.get_balance(node.right) == 1: self.right_rotate(node.right) return self.left_rotate(node) elif self.get_balance(node) == 2: if self.get_balance(node.left) == -1: self.left_rotate(node.left) return self.right_rotate(node) return node def sum_update(root, total): """ Replaces the keys in the tree with the sum of the keys that are greater than or equal to it, the corrects the tree to be a BST :param root: root of tree to start at :param total: Keeps track of the total keys greater than or equal to root :return: the new updated tree """ if root is None: return sum_update(root.right, total) temp = root.value total += temp root.value = total sum_update(root.left, total)
a67f85b7a39f706c05f234e0622d884a0deaca0c
nsbradford/HorizonCV
/horizoncv/horizon.py
7,571
3.59375
4
""" horizon.py Nicholas S. Bradford """ import cv2 import numpy as np import math DEBUG_VERBOSE = False def printV(text): """ Wrapper allowing for verbosity flag. """ if DEBUG_VERBOSE: print(text) def convert_m_b_to_pitch_bank(m, b, sigma_below): """ Method from original paper: Pitch angle (Theta) = size(ground) / size(ground) + size(sky) Bank angle (Phi) = tan^-1(m) Args: m b sigma_below Returns: pitch bank """ bank = math.degrees(math.atan(m)) pitch = sigma_below return pitch, bank def img_line_mask(rows, columns, m, b): """ Produce a mask used for splitting an image into two parts with a line. Params: rows (int) columns (int) m (double) b (double) Returns: rows x columns np.array boolean mask with True for all values above the line """ mask = np.zeros((rows, columns), dtype=np.bool) for y in range(rows): for x in range(columns): if y >= m * x + b: mask[y, x] = True return mask def split_img_by_line(img, m, b): """ Split image into two parts using a line. Params: m: slope b: y-intercept Returns: (arr1, arr2): two np.arrays with 3 columns (RGB) and N rows (one for each pixel) """ mask = img_line_mask(rows=img.shape[0], columns=img.shape[1], m=m, b=b) assert len(mask.shape) == 2 assert mask.shape[0] == img.shape[0] assert mask.shape[1] == mask.shape[1] segment1 = img[mask] segment2 = img[np.logical_not(mask)] reshape1 = segment1.reshape(-1, segment1.shape[-1]) reshape2 = segment2.reshape(-1, segment2.shape[-1]) assert reshape1.shape[1] == reshape2.shape[1] == 3 if not (segment1.shape[0] > 1 and segment2.shape[0] > 1): print('!! Warning: Invalid hypothesis: ' + str(m) + ' ' + str(b)) return (reshape1, reshape2) def compute_variance_score(segment1, segment2): """ Params: segment1 (np.array): n x 3, where n is number of pixels in first segment segment2 (np.array): n x 3, where n is number of pixels in first segment Returns: F (np.double): the score for these two segments (higher = better line hypothesis) Note that linalg.eigh() is more stable than np.linalg.eig, but only for symmetric matrices. """ assert segment1.shape[1] == segment2.shape[1] == 3 if not (segment1.shape[0] > 1 and segment2.shape[0] > 1): return -1.0 cov1 = np.cov(segment1.T) cov2 = np.cov(segment2.T) assert cov1.shape == cov2.shape == (3,3) evals1, evecs1 = np.linalg.eigh(cov1) evals2, evecs2 = np.linalg.eigh(cov2) det1 = evals1.prod() #np.linalg.det(cov1) det2 = evals2.prod() #np.linalg.det(cov2) score = det1 + det2 + (np.sum(evals1) ** 2) + (np.sum(evals2) ** 2) return score ** -1 def score_line(img, m, b): """ Computes the score of a given line on an image, using the cost function. Params: img m b Returns: scrore (float) """ # print('Score', img.shape, m, b) seg1, seg2 = split_img_by_line(img, m=m, b=b) # print('\tSegment shapes: ', seg1.shape, seg2.shape) score = compute_variance_score(seg1, seg2) return score def score_grid(img, grid): scores = list(map(lambda x: score_line(img, x[0], x[1]), grid)) assert len(scores) > 0, 'Invalid slope and intercept ranges: ' max_index = np.argmax(scores) m, b = grid[max_index] return m, b, scores, grid, scores[max_index] def accelerated_search(img, m, b, current_score): """ Hill-climbing bisection search of the (m, b) space in search for the approximate optimum, given a starting point. """ max_iter = 10 delta_m = 0.25 delta_b = 1.0 delta_factor = 0.75 printV('\tAccel. search begin m: {} b: {}'.format(m, b)) for i in range(max_iter): # print('\tDelta', delta_m, delta_b, 'M&B', m, b) grid = [ (m + delta_m, b), (m - delta_m, b), (m, b + delta_b), (m, b - delta_b), # (m + delta_m, b + delta_b), # (m - delta_m, b - delta_b), # (m - delta_m, b + delta_b), # (m + delta_m, b - delta_b), ] mTmp, bTmp, scores, grid, max_score = score_grid(img, grid) if max_score >= current_score: m = mTmp b = bTmp # else: # print ('Reached a peak?') delta_m *= delta_factor delta_b *= delta_factor printV('\tAccel. search end m: {} b: {}'.format(m, b)) return m, b def get_sigma_below(img, m, b): """ Returns % of image below the horizon line. """ seg1, seg2 = split_img_by_line(img, m, b) return seg1.size / (seg1.size + seg2.size) def optimize_scores(img, highres, slope_range, intercept_range, scaling_factor): """ Searches for the approximate highest-scoring (m, b) parameter pair. Params: img: highres: slope_range: intercept_range: scaling_factor: Returns: Answer: Tuple of (m, b) Scores: list of np.double scores corresponding to grid elements Grid: list of (m, b) tuples that were examined pitch: pitch angle bank: bank angle """ print(img.shape) printV('Optimize... img shape {} highres shape {}'.format(img.shape, highres.shape)) grid = [(m, b) for b in intercept_range for m in slope_range] print(len(grid)) m, b, scores, grid, max_score = score_grid(img, grid) m2, b2 = accelerated_search(img, m, b * scaling_factor, max_score) b2 /= scaling_factor pitch, bank = convert_m_b_to_pitch_bank(m=m2, b=b2, sigma_below=get_sigma_below(img, m2, b2)) print('\tPitch: {0:.2f}% \t Bank: {1:.2f} degrees'.format(pitch * 100, bank)) return (m2, b2), scores, grid, pitch, bank def optimize_global(img, highres, scaling_factor): """ Search an entire image for the horizon. """ printV('optimize_global()') return optimize_scores(img, highres, slope_range=np.arange(-4, 4, 0.25), #0.25 intercept_range=np.arange( 1, img.shape[0] - 2, 0.1), #0.5 scaling_factor=scaling_factor) def optimize_local(img, highres, m, b, scaling_factor): """ Search around a local space. """ printV('optimize_local()') return optimize_scores(img, highres, slope_range=np.arange(m - 0.5, m + 0.5, 0.1), intercept_range=np.arange(max(1.0, b - 4.0), min(img.shape[0], b + 4.0), 0.5), scaling_factor=scaling_factor) def optimize_real_time(img, highres, m, b, scaling_factor): """ Begin by searching globally for the horizon, and then optimize by continuing the search in only the area around the previously detected horizon. Note that the original paper discourages this due to the potential for serious issues upon miscalibration or a few bad frames; this should be rectified with a Kalman filter and periodic Global checks. """ return (optimize_global(img, highres, scaling_factor) if not m or not b else optimize_local(img, highres, m, b, scaling_factor))
369ade678d1d640d0dd86dfb1cabd79e946ffb92
ayman-shah/Python-CA
/Python 1/21.3.py
297
4.03125
4
print("-------- Loop 1 -------") for i in range(0, 7): print(i) print("-------- Loop 2 -------") for i in range(1, 11): print(i) print("-------- Loop 3 -------") for i in range(20, 28): print(i) print("-------- Your loop -------") for i in range(5, 18): print(i)
52842707ba3e154a43fae090445ef8717dbac930
yoriaantje-dev/AutoKitten
/AutoKittenTerminal.py
3,388
3.515625
4
import ctypes import datetime import os import shutil import time import urllib.error import urllib.request def select_option(options): _opt = -1 flag2 = True while flag2: print("\nWhat would you like to do?") for num, _opt in options.items(): print(f"{num}. {_opt}") try: _opt = float(input("Choose one of the above numbers: ")) except TypeError: print("Please type only numbers!\n") except ValueError: print("Please type only numbers!\n") if _opt != -1 and _opt in options.keys(): return _opt elif _opt not in options.keys(): print(f"The option {_opt} is not aviable, please try again!") else: print("Please type only numbers!\n") def get_image(): date = datetime.date.today() print(f"\nLoading kitten background from {date}\n" f"And saving file as 'kitten {date}.jpg'") # Download kitten+date.jpg try: urllib.request.urlretrieve("https://placekitten.com/1920/1080", "images/kitten " + str(date) + ".jpg") time.sleep(1) except FileNotFoundError: os.mkdir("images/") urllib.request.urlretrieve("https://placekitten.com/1920/1080", "images/kitten " + str(date) + ".jpg") time.sleep(1) except urllib.error.URLError: print("Something Strange went wrong, do you have an active internetconnection?") # Download currentKitten.jpg try: os.remove("images/currentKitten.jpg") time.sleep(1) urllib.request.urlretrieve("https://placekitten.com/1920/1080", "images/currentKitten.jpg") except FileNotFoundError: time.sleep(1.5) urllib.request.urlretrieve("https://placekitten.com/1920/1080", "images/currentKitten.jpg") except urllib.error.URLError: print("Something Strange went wrong, do you have an active internetconnection?") def set_background(): time.sleep(1.5) abs_path = os.path.abspath("images/currentKitten.jpg") ctypes.windll.user32.SystemParametersInfoW(20, 0, abs_path, 0) print("Welcome to the AutoKitten function!") options_dict = { 0: "Close program", 1: "Run the AutoKitten Function and update my background", 2: "Open the folder with the images", 3: "Prune all the images in general" } opt = select_option(options_dict) while True: if opt == 0: print("Sorry to see you go, thanks for using!") exit() elif opt == 1: get_image() set_background() print("Done, check your desktop ;)") exit() elif opt == 2: os.startfile(os.path.abspath("images/")) opt = select_option(options_dict) elif opt == 3: confirm = str(input("Are you sure? ")).lower() if confirm == "y": try: shutil.rmtree(os.path.abspath("images/")) print("Succesfully removed directory!\n") except FileNotFoundError: print("Directory is already removed!\n") elif confirm == "n": print("Okay, glad you cancelled!\n") opt = select_option(options_dict) else: print("Confirmation is wrong, going to main menu\n") opt = select_option(options_dict) else: print("Option not found, showing main menu\n") opt = select_option(options_dict)
acedb0c143b0fc7a237f21926dfc972f0d005e78
GustavoR0dr1gu3z/Full_Python
/SentenciaIF_Python/sentencia_if_else.py
486
3.984375
4
condicion = 10 if condicion == True: print("La condicion es verdadera") elif condicion == False: print("La condicion es falsa") else: print("xd") numero = int(input("Digite un numero entre 1 y 3: ")) if numero == 1: numeroTexto = "Numero Uno" elif numero == 2: numeroTexto = "Numero Dos" elif numero == 3: numeroTexto = "Numero Tres" else: numeroTexto = "Numero Fuera de Rango" print("Numero proporcionado: {}".format(numeroTexto))
9967dc201c936cf35947edd66c88532098e9a0b4
Mehr2008/summer-of-qode
/Python/2021/Class 2/Student Code/Daksh Leekha/ass5.py
177
4.1875
4
age = int(input("Enter age: ")) if age >= 18: print("Eligible to drive") elif age <= 0: print("You are not born yet!") else: print("Not eligible to drive")
852d5bdf9fac7614f2092ac8febde976b0c1fef1
narasimha7854/qazi
/LambdaEx1.py
298
4.34375
4
#program to find smaller of two numbers using lambda def small(a,b): if(a<b): return a else: return b sum = lambda x,y : x+y diff = lambda x,y : x-y #pass lambda function as argument to regular function print('Smaller of two numbers',small(sum(-3,-2),diff(-1,2)))
9a0ef705b424c9ea4b6a1f1fb9d3a539e4846120
telegrace/Python3
/Ex_5_Day_2_a.py
546
4.34375
4
my_name = "Grace" my_age = 45 # yes it is a lie my_weight = 60 # kg my_height = 165 # cm my_eyes = "brown" my_teeth = "tanned" print(f"Lets talk about {my_namee}.") print(f"She's {my_age} old.") print("But we all know that's a lie.") print(f"She weighs {my_weight} kg.") print(f"She is {my_height} cm tall.") print(f"She has {my_eyes} eyes and her teeth are '{my_teeth}'.") total = my_height / my_weight + my_age print(f"If I divide {my_name}'s height, {my_height}, by her weight, {my_weight}, and then add her {my_age} the total is {total}.")
7bbf8eb3f5779e6b2b9cc7f0f15d6a55c24862f9
Linar468/ProjectForJob
/28. Python (Introduction)/ClassesAndObjects.py
504
3.671875
4
class Person(): def __init__(self, name, surname, age, salary): self.name = name self.surname = surname self.age = age self.salary = salary def getInfo(self): info = "Name: " + self.name + ", surname: " + self.surname + ", age: " + str(self.age) + ", salary " + str(self.salary) print(info) def salaryUp(self): self.salary += 1000 person1 = Person("Linar", "Latypov", 27, 1500) person1.getInfo() person1.salaryUp() person1.getInfo()
0197d4ff4d60baee9987d93b55de0429c93b7454
kaustav19pgpm025/Python-for-Everybody-EdX
/typefunction.py
208
4.0625
4
# type() in Python str = raw_input("Enter a string: ") print type(str) n = int(raw_input("Enter an integer: ")) print type(n) f = float(raw_input("Enter a floating point value: ")) print type(f)
072e810842987339e30e9e3e851503548d8c9c72
pawarspeaks/Hacktoberfest-2021
/Python/quicksort.py
700
3.625
4
def partition (a, s, e): i = (s - 1) pivot = a[e] for j in range(s, e): if (a[j] <= pivot): i = i + 1 a[i], a[j] = a[j], a[i] a[i+1], a[e] = a[e], a[i+1] return (i + 1) def quick(a, s, end): if (s < end): p = partition(a, s, end) quick(a, s, p - 1) quick(a, p + 1, end) def printArr(a): for i in range(len(a)): print (a[i], end = " ") a = [68, 1003, 10, 9, 508, 121,524,138,687] print("Before sorting array elements are - ") printArr(a) quick(a, 0, len(a)-1) print("\nAfter sorting array elements are - ") printArr(a)
1584d333cd37f925eb7da1f037c3690e17d196c7
gschen/where2go-python-test
/1906101059王曦/11月/day20191111/11.3.py
327
3.75
4
#3. 使用“冒泡排序”的方法对列表里面的元素由大到小进行排序,ls=[10,9,13,5,25,70,2] def wxsort(ls): for n in range(len(ls)-1): for i in range(len(ls)-n-1): if ls[i]>ls[i+1]: ls[i],ls[i+1]=ls[i+1],ls[i] return ls ls = [10,9,13,5,25,70,2] print(wxsort(ls))
0fdcb34f5d7c6087a32e0e9da36cefaa85fc2d15
AmeyVanjare/PythonAssignments
/Assignmentq5.py
332
3.828125
4
print("*"*10,"Q5","*"*10) num=int(input("Enter length of list : ")) lst1=[] lst2=[] for i in range(0,num): ele=input("Enter list elements") lst1.append(ele) for j in range(0,len(lst1)+1): lst2.append(-1) for position,data in enumerate(lst1): lst2.insert(int(data),position) print(lst2)
e585a889078bb786bfb9299c5262d987322321be
obetsa/python_basic_hw
/hw8/hw8/practice/reverse_brackets.py
1,318
3.96875
4
""" Реверс подстроки в () Таким образом, чтоб: [in] "(bar)" [out] "rab" [in] "foo(bar)baz" [out] "foorabbaz" [in] "foo(bar)baz(blim)" [out] "foorabbazmilb" [in] "foo(bar(baz))blim" [out] "foobazrabblim" так как "foo(bar(baz))blim" -> "foo(barzab)blim" -> "foobazrabblim" Данные примеры можете использовать для написания тестов. """ import re # Solutions # 1 def reverse_brackets(s: str) -> str: end = s.find(")") start = s.rfind("(", 0, end) if end == -1: return s return reverse_brackets( s[:start] + s[start + 1 : end][::-1] + s[end + 1 :] ) # 2 def reverse_brackets(s: str) -> str: search_result = re.search(r"\(\w*\)", s) if search_result: before = search_result.group() after = before.replace("(", "").replace(")", "")[::-1] return reverse_brackets(s.replace(before, after)) return s # 3 def reverse_brackets(s: str) -> str: for i in range(len(s)): if s[i] == "(": start = i if s[i] == ")": end = i return reverse_brackets( s[:start] + s[start + 1 : end][::-1] + s[end + 1 :] ) return s
53bfb78a397709d76217a88035f6179d50ece64d
YarikGn/YaroslavGnatenkoA2
/main.py
9,517
4.09375
4
""" Name: Yaroslav Gnatenko Date: 29 September Brief Project Description: This project is the modified version on the Assignment 1 that is implemented on the app.kv file. In terms of how the program works, the "Required Books" shows the buttons for the Required Books list and when the button on the required book object is clicked, the button will mark the book as completed, which makes the button disappeared and moved to the completed books button list. In terms of the how "Completed Books" works, the button on the completed button object is clicked and show the description of the Book object(return value of the class). On the other one, "Add Button" button occurs when the inputs in the text fields are reasonable, which shows the error messages when the inputs in the text fields shows otherwise. In the "Clear" button, the button is used for clearing all the inputs in the text fields. GitHub URL: https://github.com/YarikGn/YaroslavGnatenkoA2 """ from kivy.app import App from kivy.app import Builder from book import Book from booklist import BookList from kivy.uix.button import Button class ReadingListApp(App): def __init__(self, **kwargs): """This function is to construct the class""" super(ReadingListApp, self).__init__(**kwargs) book_lists = BookList()#calling the BookList class book_object = Book()#calling the Book class self.book_lists = book_lists self.book_object = book_object self.book_lists.load_books("books.csv")#loading the book in order to get the list of the Book objects def on_start(self): """This function is used for initialise the program/when the user start to run the program""" #initialised state self.create_books(mode='required') self.root.ids.required_book_button.state = 'down'#state is to determine whether the button is on the pressed state or not self.root.ids.completed_book_button.state = 'normal' def create_books(self, mode): """This function is used for creating the book button in the entriesBox widget""" self.clear_books() if mode == "required": # creating the button based on the books that is required for book in range(len(self.book_lists.booklists)): if self.book_lists[book].status == 'r': temp_button = Button(text=self.book_lists[book].title)#text that will be generated on the button temp_button.bind(on_release=self.click_required_books)#binding the button to the function when clicked page_check = self.book_object.long_pages(self.book_lists[book].pages)#to determine the background color for the button, which is by checking the book object pages if page_check == True:#when page on the book object is more than 500(long) temp_button.background_color = 0, 1, 1, 1#blue color when the book is long else: temp_button.background_color = 0.8, 0.8, 0, 1#yellow color when the book is short self.root.ids.entriesBox.add_widget(temp_button)#adding the button in entriesBox widget total_required_pages = self.book_lists.counting_required_pages()#calling the method to display total required pages from the BookList() class self.root.ids.bookPages.text = total_required_pages #the variable on the method to call counting_required_pages() method, which is the returned value of the method self.root.ids.bookMsg.text = "Click book to mark them as completed"#Initialise the message when clicking "Required books" elif mode == "completed": #creating the button based on the books that is completed for book in range(len(self.book_lists.booklists)): if self.book_lists[book].status == 'c': temp_button = Button(text=self.book_lists[book].title) temp_button.bind(on_release=self.click_completed_books) temp_button.background_color = 0.37,0.37,0.37,1 self.root.ids.entriesBox.add_widget(temp_button) total_completed_pages = self.book_lists.counting_completed_pages() self.root.ids.bookMsg.text = "Click book to show the description"#Initialise the message when clicking "Completed books" self.root.ids.bookPages.text = total_completed_pages def press_required_books(self): """the function runs when "Required books" is pressed""" self.create_books(mode='required')#to get the required book buttons self.root.ids.required_book_button.state = 'down' self.root.ids.completed_book_button.state = 'normal' def press_completed_books(self): """the function runs when "Completed books" is pressed""" self.create_books(mode='completed')#to get the completed book buttons self.root.ids.required_book_button.state = 'normal' self.root.ids.completed_book_button.state = 'down' def add_books(self, text_title, text_author, text_pages): """This function is to add books on the list of Book object, which occurs when "Add Item" is clicked """ try:#try the code of the add_books method book_pages = int(text_pages) if text_title=="" or text_author=="" or text_pages=="": self.root.ids.bookMsg.text = "All fields must be completed" elif book_pages < 0: self.root.ids.bookMsg.text = "Pages must be positive number" self.root.ids.text_pages.text = ""#to empty the fields when text and value = "" self.root.ids.text_pages.value = "" else: self.book_lists.add_book(text_title,text_author,text_pages)#call the method add_book in BookLists() class in order to add book in the booklist self.clear_text()#to clear the input of those three fields after adding the book self.book_lists.sort_books()#sort the books in order to make the button more organised self.on_start()#to reset the state, which is to show the required list button self.root.ids.bookMsg.text = "{} by {}, {} pages is added".format(text_title,text_author,text_pages)#show the message that the books is added(to replace the message on the starting point of the program) except ValueError: if text_title=="" or text_author=="" or text_pages=="":#to make the exception runs when there is at least one of the text field is empty self.root.ids.bookMsg.text = "All fields must be completed"#to show the message when an exception happens else: #it is used when the value in the page text field is not the same type of the input(expected: int, the actual: str) self.root.ids.bookMsg.text = "Please enter a valid number" self.root.ids.text_pages.text = "" self.root.ids.text_pages.value = "" def click_required_books(self, instance): """This function is used for clicking the button for the book that is created based on create_books() in required books""" title = instance.text #instance.text is the text on the Button, which means instance is the Button in the kv file for required_name in self.book_lists.booklists: if required_name.title == title:#to check whether the text button you click match the title of the object in booklists(required_name.title) change_status = self.book_object.mark_completed(required_name.status)#to call method mark_completed() in the Book() class if change_status == True: required_name.status = 'c' self.on_start()#to make the button immediately dissapear after clicking the button on the required books, otherwise the button is still there self.root.ids.bookMsg.text = "{} to be marked as completed".format(required_name.title) def click_completed_books(self,instance): """This function is used for clicking the button for the book that is created based on create_books() in completed books""" title = instance.text for completed_name in self.book_lists.booklists: if completed_name.title == title:#to check whether the text button you click match the title of the object in booklists(completed_name.title) self.root.ids.bookMsg.text = "{} (completed)".format(completed_name)#to show the message after you click the button on a list of completed books def clear_books(self): """This function is to clear the button in order to prevent duplicates in the button""" self.root.ids.entriesBox.clear_widgets() def clear_text(self): """This function is to clear the text field for adding books""" self.root.ids.text_title.text = "" self.root.ids.text_author.text = "" self.root.ids.text_pages.text = "" def build(self): """This function is to load the kv file""" self.title = "Reading List 2.0"#determine the title of the kv file self.root = Builder.load_file("app.kv")#to load the kv file return self.root def on_stop(self): """This function runs when you quit the program""" self.book_lists.save_books('books.csv') ReadingListApp().run()
b81b7a528800e0e625c5d632347d1bb23aea1db2
H33l6ey/python
/Learning/list.py
189
3.75
4
my_list = [ 100, 2, 10, 150, 20, 175, 5, 10, 6, 25 ] total = 0 for ele in range(0, len(my_list)): total = total + my_list[ele] print("The sum of all numbers in this list are ", total)
af93406d971b356ece79171d076316212e6405ed
rubenmejiac/CS101
/Module5Homework1.py
1,700
4.03125
4
# Module5Homework1: Functions # Collect information from the user hoursworked = int(input("Please enter your work hours: ")) hourlyrate = int(input("Please enter your hourly rate: ")) state = input("Please enter your state of resident: ") maritalstatus = input("Please enter your marital status: ") def calculatewages(hoursworked, hourlyrate): wages = hoursworked * hourlyrate return wages def calculatefedtax(maritalstatus, wages): taxpercent=0 if (maritalstatus == "Married"): taxpercent=0.2 elif (maritalstatus == "Single"): taxpercent=0.25 else : taxpercent=0.22 fedtax = wages * taxpercent return fedtax def calculatestatetax(wages, state): statepercent=0 if (state == "CA") or (state == "NV") or (state == "SD") or (state == "WA") \ or (state == "AZ"): statepercent=0.08 elif (state == "TX") or (state == "IL") or (state == "MO") or (state == "OH") \ or (state == "VA"): statepercent=0.07 elif (state == "NM") or (state == "OR") or (state == "IN"): statepercent=0.06 else : statepercent=0.05 statetax = (wages * statepercent) return statetax def calculatenet(wages, fedtax, statetax): netwages = (wages - fedtax - statetax) return netwages Wag = calculatewages(hoursworked, hourlyrate) Ftx = calculatefedtax(maritalstatus, Wag) Stx = calculatestatetax(Wag, state) Nwg = calculatenet(Wag, Ftx, Stx) print ("**********") print("Your wage is: $" + str(Wag)) print("Your federal tax is: $" + str(Ftx)) print("Your state tax is: $"+str(Stx)) print("Your net wage is: $"+str(Nwg)) print ("**********")