blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
37539f498abd469a45e14f8f7d47822b27909a9e
MaggieWensiLyu/csc1002
/03.py
162
3.984375
4
nums = [] n1 =int( input('write n1:')) n2 =int( input('write n2:')) n3 = int(input('write n3:')) nums.append(n2) nums.append(n1) nums.append(n3) print(nums)
3cef25cade36b7fdf17bc6100f2412d42c6eb733
prem0023/Python
/Binary_search.py
539
3.703125
4
pos = 0 def search(list, n): i = 0 u = len(list)-1 while i <= u: mid = (i + u) // 2 if list[mid] == n: global pos pos = mid return True else: if list[mid] > n: u = mid else: i = mid list = [1, 3, 5, 7, 8, 9, 10, 11, 15, 22,25,29,35,36,39,42,48,52,59,66] print(list) n = int(input("Enter the number to search from the list: ")) if search(list,n): print("Found ", pos + 1) else: print("Not Found")
6af38c36599d96b74a55075e3a475fbd34dd8630
gendo7985/Coding-Practice
/Programmers/level_2/sequential_number.py
255
3.640625
4
# 숫자의 표현 def solution(n): while n % 2 == 0: n //= 2 d = 3 answer = 1 while n > 1: cnt = 1 while n % d == 0: cnt += 1 n //= d answer *= cnt d += 2 return answer
de61fdb68ffc8147a34dc964343bcfea92183047
AndrewJAHogue/Python-Learning
/smallest_numbers.py
901
4.1875
4
import math import array as arr # take in the four real numbers input_number1 = float(input("Enter the first number: ")) input_number2 = float(input("Enter the second number: ")) input_number3 = float(input("Enter the third number: ")) input_number4 = float(input("Enter the fourth number: ")) array_float = arr.array('f',[0,1,2,3]) array_float = [input_number1,input_number2,input_number3,input_number4] input_method = input("Which method would you like, A or B: ") #method A is what I devised, a simple array iteration to compare numbers if input_method == "A": # compare all of them together n = 3 smallest = array_float[0] for i in range(0, n): if (array_float[i] < smallest): smallest = array_float[i] print(smallest) # B uses the function min() that I just found out exists elif input_method == "B": smallest = min(array_float) print("the smallest number is %s " %smallest)
092e59eadef101589d4096e9ddb18293c6cf470a
mike03052000/python
/Training/HackRank/Sorting/quicksort.py
740
3.6875
4
from random import * def quick_sort(lst): if len(lst) == 1: return lst for i in range(1, len(lst)): temp = lst[i] #print("i = %d, temp = %d, lst = %r" %(i,temp,lst)) j = i - 1 while j >= 0 and temp < lst[j]: lst[j + 1] = lst[j] j -= 1 #print(lst) lst[j + 1] = temp return lst def qsort(arr): if len(arr) <= 1: return arr else: return qsort([x for x in arr[1:] if x < arr[0]]) + [arr[0]] + qsort([x for x in arr[1:] if x >= arr[0]]) a= [randint(1,100000) for i in range(1000)] #a=[7,5,6,33,45,23,67,3,2,1,12,34,654,3,56,34,22,893,126] print(a) print("quick_sort =",quick_sort(a)) #print("qsort =",qsort(a))
c1f7343e755e99748922ae05d8f5c11e2d84c8f7
priyankasin/201451045
/Q1.py
1,765
4.09375
4
# Implementation of find out the sum of all the nodes which are leaf nodes # A Binary tree node class Node: def __init__(self, key): self.key = key self.left = None self.right = None # function to check if a given node is leaf or not def isLeaf(node): if node is None: return False if node.left is None and node.right is None: return True return False def leftLeavesSum(root): left_sum= 0 # Update result if root is not None if root is not None: # If left of root is None, then add key of left child if isLeaf(root.left): left_sum += root.left.key else: # Else iterate for left child of root left_sum += leftLeavesSum(root.left) # iterate for right child of root and update left_sum left_sum += leftLeavesSum(root.right) return left_sum def rightLeavesSum(root): right_sum = 0 # Update result if root is not None if root is not None: # If right of root is None, then add key of right child if isLeaf(root.right): right_sum += root.right.key else: # otherwise iterate for right child of root right_sum += rightLeavesSum(root.right) # iterate for left child of root and update right_sum right_sum += rightLeavesSum(root.left) return right_sum # constrcut the Binary Tree shown in the above function root = Node(10) root.left = Node(5) root.right = Node(15) root.right.right = Node(8) root.right.right.left = Node(5) root.left.left = Node(10) root.left.right = Node(12) root.left.right.left = Node(6) a=leftLeavesSum(root)+rightLeavesSum(root) print("Sum of all the nodes which are leaf nodes is: ", a)
ce3a5e87032aea89245ae2f51aaef6f0725a4577
jawid-mirzad/python
/bank.py
2,261
3.84375
4
user = "jawid mirzad" userName = (input("skriva dit användarenam:")) if user != userName: exit() bank = "Nordia" bankName = (input("skriv ditt bank")) if bank != bankName: exit() pin = 1234 # Det är en integer som innehåler heltal och en variabel. userPin = int(input("Skriv in din pinkod: ")) # Det är en integer som innehåler heltal och en funktion som man kan skriva sitt pinkod. if pin != userPin: # if "om", vilkorsats för om. pin är inte lika med userPin. exit() # stänga av try: # "försök" try är en undantaghantering som testar ett block av kod för fel. with open("balance.txt", "r") as balancefile: # Är en string som öppner balancefilen och kan läsa. try: #försök och testar ett block av kod för fel. balance = balancefile.readline() # variabel som försökar läsa balancefilen. balance = float(balance) # variabel och datatyp för decimaal tal. except (ValueError): # undantag att avbryta körning. print("ValueError") # köra programet. balance = 0.0 # variabel och fload decimaltal. except (FileNotFoundError): # undantag att avbryta körning. balance = 0.0 #variabel lika och fload decimaltal. menu = 0 # variabel lika med. # menu 1 insättning # menu 2 uttag # menu 3 avsluta while menu != 3: #loop som kan köra vidare print("Ditt saldo är: ", balance) # en funktion som kör programet. menu = int(input("Skriv ditt val[1,2,3]: ")) # Det är en integer som innehåler heltal och en funktion som man kan skriva en sifra. if menu == 1: # vilkor sats för om, om menu är lika med 1. balance = balance + float(input("Gör en insättning: ")) # tilldelningsoperator, datatyp och funktion som vi kan sätta mera sifror. elif menu == 2: # annars om, om det fungerar inte kan hoppa till nästa steg. balance = balance - float(input("Gör en utag: ")) # tilldelning, datatyp och funtion som man kan ta ut prngar. else: print("fel eller avslut") try: with open("balance.txt","w")as balancefile: # skriva balance.txt om det finns annars skapar en fil med hjälp av "w". balancefile.write(str(balance)) except(FileNotFoundError): print("ingen fil")
2d6c6ca49e75f339a7e94fe497f327305f790e4d
vlad-bezden/py.checkio
/electronic_station/restricted_sum.py
799
3.984375
4
"""Restricted Sum Our new calculator is censored and as such it does not accept certain words. You should try to trick by writing a program to calculate the sum of numbers. Given a list of numbers, you should find the sum of these numbers. Your solution should not contain any of the banned words, even as a part of another word. The list of banned words are as follows: sum import for while reduce Input: A list of numbers. Output: The sum of numbers. Precondition: The small amount of data. Let's creativity win! """ from typing import List def checkio(data: List[int]) -> int: return 0 if not data else data.pop() + checkio(data) if __name__ == "__main__": assert checkio([1, 2, 3]) == 6 assert checkio([1, 2, 3, 4, 5, 6]) == 21 assert checkio([2, 2, 2, 2, 2, 2]) == 12
1daee2dddcc011b14d5dba78e073140167380345
mgallegos13/Codewars_Exercises
/Python/Even or Odd - Which is Greater?/solution.py
612
4.21875
4
def even_or_odd(s): #split and convert string to intergers a_list = list(s) map_object = map(int, a_list) list_of_integers = list(map_object) #even and odd variables evens = 0 odds = 0 #traverse thru list and adde them to count for i in list_of_integers: if i % 2 == 0: evens += i else: odds += i #return phrase if evens > odds: return "Even is greater than Odd" elif odds > evens: return "Odd is greater than Even" elif evens == odds: return "Even and Odd are the same"
0084ae016d92be53fb72b04d3d45b8f28afa9726
nimbol/euler
/problem052.py
531
3.640625
4
''' It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' d = 3 go = True while go: start = int('1234567890'[:d]) stop = int('1666666666'[:d]) for x in xrange(start, stop): coll = set(''.join(sorted(str(x * i))) for i in range(1, 7)) if len(coll) == 1: go = False break else: d += 1 print x
017decc7e9e1b53d7d1d4d8456200ed1b9c9a70d
yasirabd/udacity-ipnd
/stage_3/lesson_3.3_classes/a_draw_turtles/mindstorms.py
2,751
4.75
5
# Lesson 3.3: Use Classes # Mini-Project: Draw Turtles # turtle is a library we can use to make simple computer # graphics. Kunal wants you to try drawing a circles using # squares. You can also use this space to create other # kinds of shapes. Experiment and share your results # on the Discussion Forum! import turtle # Your code here. window = turtle.Screen() window.bgcolor("white") brow = turtle.Turtle() brow.shape("turtle") brow.speed(20) brow.ht() def draw_square(length, color): brow.color(color) for counter in range(4): brow.forward(length) brow.right(90) def draw_circle(radius, color): brow.color(color) brow.circle(radius) def draw_triangle(cor1, cor2, color): brow.color(color) brow.goto(cor1) brow.goto(cor2) brow.goto(0,0) def draw_art(): brow.color("red") j = 0 angle = 360 rotate = 5 while j < angle: draw_square(150, "red") j += rotate brow.right(rotate) window.exitonclick() def draw_flower(): pen1 = turtle.Turtle() pen2 = turtle.Turtle() pen3 = turtle.Turtle() pen1.color("yellow") pen1.speed(20) pen2.color("red") pen2.speed(20) pen2.pensize(5) pen3.color("green") pen3.speed(20) pen3.pensize(5) for i in range(0, 360, 10): pen1.down() pen1.home() # move to origin pen1.right(i); pen1.forward(70) pen1.up() pen1.right(45); pen1.forward(70) pen1.right(135); pen1.forward(70) pen2.up() pen2.home() pen2.right(i); pen2.forward(70) pen2.down() pen2.right(45); pen2.forward(70) pen2.right(135); pen2.forward(70) pen1.ht() pen1.up(); pen2.up(); pen3.up() pen3.home(); pen3.goto(0, -100) pen3.down(); pen3.goto(0, -150) pen3.right(10); pen3.forward(70) pen3.right(45); pen3.forward(70) pen3.right(135); pen3.forward(70) pen3.goto(0, -150) pen3.goto(0, -300) pen3.right(80) window.exitonclick() def draw_initial(): me = turtle.Turtle() me.shape("turtle") me.pensize(10) me.up() me.color("red") me.goto(-100,100) me.down() me.goto(-50,50) me.goto(0,100) me.goto(-50,50) me.goto(-50,0) me.up() me.color("brown") me.goto(0,0) me.down() me.goto(50,100) me.goto(100,0) me.up() me.goto(50,40) me.down() me.goto(78,40) me.goto(23,40) me.ht() me.up() me.pensize(5) me.color("black") me.goto(0,-100) me.down() me.circle(150) window.exitonclick() # draw_square(100, "red") # draw_circle(100, "green") # draw_triangle((150,50), (-50, -150), "blue") # draw_art() # draw_flower() draw_initial() # window.exitonclick()
039ceafe83dde21d4a550390cd0fadd5be12d5c7
Sturmtiger/PythonCourse1
/ex13.py
417
3.703125
4
#ПЕРВЫЙ ВАРИАНТ # count = 0 # while True: # num = int(input()) # count += num # if num == 0: # print(count) # break #ВТОРОЙ ВАРИАНТ # s, n =0, int(input("")) # while n: #Если n != 0(False), тогда n == True(бесконечный цикл). Любое число, кроме 0 - True # s, n = s + n, int(input("")) # print(s)
0364dad500feeaeb8307a68cefc3e7cee136216f
krismanaya/Algorithmic_Toolbox
/python/majority_element.py
709
3.640625
4
#python2 import sys n = int(input()) arr = map(int,raw_input().strip().split(' ')) def majority_element_naive(arr,n): arr_n = sorted(arr) for i in range(0,len(arr_n)-1): if arr.count(arr[i]) > n // 2: return 1 return 0 def majority_element(arr,low=0,high=None): new_arr = sorted(arr) high = len(arr)-1 if high is None else high mid = (low+high)/2 while low <= high: mid = (low+high)/2 if new_arr.count(new_arr[low]) > len(arr)/2: return 1 if new_arr.count(new_arr[high]) > len(arr)/2: return 1 else: low+=mid high-=mid return 0 sol = majority_element(arr) print sol
e1817a8a855e53b663005a6bbdc784aafd7f4537
jtgeballe/AppMonitor
/validatorlib/timer.py
744
3.90625
4
"""The RepeatTimer type executes code on a calculated cadence.""" from threading import Timer class RepeatTimer: def __init__(self, interval, function): self.__interval = interval self.__function = function self.__timer = self._create_timer() def _run(self): """Execute this code every time the timer expires.""" self.__function() self.__timer = self._create_timer() self.__timer.start() def _create_timer(self): """Calculate the new time interval and set the timer.""" next_interval = self.__interval() return Timer(next_interval, self._run) def start(self): self.__timer.start() def cancel(self): self.__timer.cancel()
38c35ba0d8d3188243131124e0710d5fb0b148c3
DimitrYo/LoanCalculator
/creditcalc.py
3,888
3.90625
4
import math import argparse parser = argparse.ArgumentParser(description="Loan calculator") parser.add_argument("--type", choices=["annuity", "diff"]) parser.add_argument("--payment") parser.add_argument("--principal") parser.add_argument("--periods") parser.add_argument("--interest") args = parser.parse_args() what_calculate_msg = """What do you want to calculate? type "n" - for number of monthly payments, type "a" for annuity monthly payment amount, type "p" for loan principal:\n""" enter_pricipal_msg = "Enter the loan principal:\n" payment_msg = "Enter the monthly payment:\n" interest_msg = "Enter the loan interest:\n" annuity_msg = "Enter the annuity payment:\n" periods_msg = "Enter the number of periods:\n" res_principal_msg = "Your loan principal = {}!" res_payment_msg = "Your monthly payment = {}!" overpayment_msg = "Overpayment = {}" repay_time_msg = "It will take {} years and {} months to repay this loan!" repay_time_years_msg = "It will take {} years to repay this loan!" incorrect_par_msg = "Incorrect parameters" monthly_payment_msg = "Month {}: payment is {}" def int_rate(): if args.interest is None: print_error() interest_percent = float(args.interest) return interest_percent / (12 * 100) def get_periods(): if args.periods is None: print_error() return int(args.periods) def get_pricipal(): if args.principal is None: print_error() return int(args.principal) def rate_ann(rate, n): temp = math.pow(1 + rate, n) return (rate * temp) / (temp - 1) def annuity(rate, n, principal): return principal * rate_ann(rate, n) def print_error(): print(incorrect_par_msg) exit() def invalid_payment(): if args.payment is not None: print_error() exit() def empty_principal(): if args.principal is None: if args.payment is None: print_error() payment = int(args.payment) interest_rate = int_rate() periods = get_periods() principal = math.ceil(payment / rate_ann(interest_rate, periods)) print(res_principal_msg.format(principal)) print(overpayment_msg.format("%.f" % (payment * periods - principal))) exit() def empty_periods(): if args.periods is None: if args.payment is None: print_error() payment = int(args.payment) interest_rate = int_rate() principal = get_pricipal() months = math.ceil(math.log(payment / (payment - interest_rate * principal), 1 + interest_rate)) years = months // 12 final_month = months - years * 12 if (final_month == 0): print(repay_time_years_msg.format(years)) else: print(repay_time_msg.format(years, final_month)) print(overpayment_msg.format("%.f" % (payment * months - principal))) exit() if __name__ == '__main__': calculate_type = args.type if calculate_type == "annuity": empty_principal() empty_periods() principal = get_pricipal() periods = get_periods() interest_rate = int_rate() payment = math.ceil(annuity(interest_rate, periods, principal)) print(res_payment_msg.format("%.f" % payment)) print(overpayment_msg.format("%.f" % (payment * periods - principal))) elif calculate_type == "diff": invalid_payment() principal = get_pricipal() periods = get_periods() interest_rate = int_rate() total = 0 for i in range(1, periods + 1): montly_payment = math.ceil(principal / periods + interest_rate * (principal - principal / periods * (i - 1))) total += montly_payment print(monthly_payment_msg.format(i, montly_payment)) print() print(overpayment_msg.format("%.f" % (total - principal))) else: print_error()
2ca578e37f2fbc468f41f68e7c79190bc52bb286
jonas-programming/programming_language
/Übungen/Übung 9/task15.py
864
3.703125
4
from re import fullmatch # Define regEx reg = r"\(([\+\-\*\/][0-9]{2,}|[0-9]+)\)" # Test again and again while True: # Get phrase to check phrase = input("Your phrase to check:\n").replace(" ", "") # Check input agains regEx if satisfy grammar result = fullmatch(reg, phrase) print("Correct:", result is not None) if result is not None: # If operand is in front calculate with this operand if result[1] in ('+', '-', '*', '/'): # Catch zero division exception try: result = eval(result[1].join(result[2:-1])) except ZeroDivisionError: result = None # default result is content of brackets else: result = int(phrase.strip("()")) # Print result print("Result:", result) # New line print()
ae7f9e7b1f1c4a73438397993f2cfc5ab2f21f01
ViktoriaKirillova/21v-pyqt
/unit_06/table2.py
560
3.65625
4
import sqlite3 db = sqlite3.connect("myshop.db") with db: cursor = db.cursor() cursor.execute('''insert into Customer values(3, "Nic","Adam","2 Pillow Street","London","BB3 2YU","04567 467888")''') cursor.execute('''insert into Customer values(4, "Ann","McDonald","55 Flowers Street","Glasgj","DB3 2YU","04567 466666")''') cursor.execute('''insert into Customer values(5, "Tom","Adams","2 Django Street","Dublin","CE3 2YU","04567 467777")''') db.commit() cursor.execute('SELECT * FROM Customer') print cursor.fetchall() cursor.close()
b68b99360ed41f3fd9445a942e863ce186a28f04
William-Thomson/CP1404_Practicals
/prac_09/cleanup_files.py
1,421
3.640625
4
""" CP1404/CP5632 Practical Demos of various os module examples """ import os def main(): """Process all subdirectories using os.walk().""" os.chdir('Lyrics') for directory_name, subdirectories, filenames in os.walk('.'): print("Directory:", directory_name) print("\tcontains subdirectories:", subdirectories) print("\tand files:", filenames) print("(Current working directory is: {})".format(os.getcwd())) # renames the files as the program walks for filename in filenames: old_name = os.path.join(directory_name, filename) new_name = os.path.join(directory_name, get_fixed_filename(filename)) print("Renaming {} to {}".format(old_name, new_name)) os.rename(old_name, new_name) def get_fixed_filename(filename): """Return a 'fixed' version of filename.""" new_name = filename.replace(" ", "_").replace(".TXT", ".txt") for i, current_character in enumerate(new_name): previous_character = new_name[i - 1] if current_character.isupper() and previous_character.islower(): new_name = new_name.replace("{}{}".format(previous_character, current_character), "{}_{}".format(previous_character, current_character)) print(previous_character, current_character) print(filename, new_name) return new_name main()
8d23a8a1a0bfd64364857f1ecd1623639b8f4cb5
khzaw/algorithms
/hackerrank/algorithms/graph-theory/bfsshortreach.py
1,146
3.578125
4
#!/bin/python from collections import deque class Node: def __init__(self, value): self.value = value self.adjacentNodes = [] self.visited = False def breadth_first_traversal(start, graph): q = deque([start]) start.visited = True while len(q) > 0: node = q.pop() for neighbour in node.adjacentNodes: if not neighbour.visited: q.appendleft(neighbour) graph[neighbour.value] = 6 + graph[node.value] if graph[node.value] > 0 else 6 neighbour.visited = True t = int(raw_input().strip()) for g in xrange(t): n, m = map(int, raw_input().strip().split(' ')) graph = {} nodes = [] for i in xrange(n): nodes.append(Node(i)) graph[i] = -1 for _ in xrange(m): m1, m2 = map(int, raw_input().strip().split(' ')) nodes[m1-1].adjacentNodes.append(nodes[m2-1]) nodes[m2-1].adjacentNodes.append(nodes[m1-1]) s = int(raw_input().strip()) breadth_first_traversal(nodes[s-1], graph) del graph[s-1] distance = ' '.join(str(x) for x in graph.values()) print distance
c8e5314835dee01f6ef2224af12efab19962a713
ArturPalko/-colloquium
/30.py
585
3.984375
4
'''30. Обчислити середнє арифметичне значення тих елементів одновимірного масиву, які розташовані за першим по порядку мінімальним елементом.''' import numpy as np import random b=[random.randint(1,10) for i in range(10)] a=np.array(b) print(a) print(f'Індекс мінімального елементу:{b.index(a.min())}') c=np.array(b[b.index(a.min()):]) print(f'Зріз:{c}') print(f'Середнє значення елементів зрізу:{c.mean()}')
f69d40b46c97a72688b32a38de195e4555b9c5c2
matheussmachado/sel_aprend
/aula_06/ex05.py
1,368
3.640625
4
""" OBJETIVO: ENQUANTO FOR PEDIDO, PREENCHER O FORMULÁRIO ESPECÍFICO - criar entradas de nome e para os formulários - são 4 formulários, portanto por 4 vezes são pedidos - buscar a referência do formulário no span - buscar o form cuja classe tenha no seu valor um match com a referência - desse form, enviar no input cujo atributo name='nome' a entrada nome - desse form, clicar no input cujo atributo type='submit' """ from time import sleep from selenium.webdriver import Chrome url = 'https://selenium.dunossauro.live/exercicio_05.html' entradas = [ {'nome': 'Primeiro', 'senha': '1senha'}, {'nome': 'Segundo', 'senha': '2senha'}, {'nome': 'Terceiro', 'senha': '3senha'}, {'nome': 'Quarto', 'senha': '4senha'}, ] browser = Chrome() browser.get(url) for vezes in range(4): sleep(4) referencia = browser.find_element_by_css_selector('span').text formulario = browser.find_element_by_css_selector(f"form[class$='{referencia}']") sleep(2) input_nome = formulario.find_element_by_css_selector("input[name='nome']") input_senha = formulario.find_element_by_css_selector('input[name="senha"]') input_nome.send_keys(entradas[vezes]['nome']) input_senha.send_keys(entradas[vezes]['senha']) sleep(1) formulario.find_element_by_css_selector('input[type="submit"]').click()
de5ae86a428978a141a632417ef4c05e942e23c8
julencosme/python_programs
/prompt_if_elif_else_movie_tickets.py
509
4.0625
4
# Movie ticket information: # If a person is under the age of 3, the ticket is free. # If they are between 3 and 12, the ticket is $10. # If they are over age 12, the ticket is $15. prompt = "What is your age?\n" prompt += "Once you have entered your age, we will state your admission fee: " while True: age = int(input(prompt)) if age <= 3: print("Free admission") elif age > 3 and age <= 12: print("Ten dollars, please.") else: print("Fifteen dollars, please.")
9328811d0cfc9f86eb4819269f2eda853e958520
kdeberk/advent-of-code
/python2016/day17.py
2,234
3.828125
4
# 2016, Day 17. # A maze of 4x4 rooms. Each pair of adjacent rooms is separated by a door that can # be locked. Whether the door is locked is determined by the path that our hero took # to reach the room with that door. # # Part 1: Find the shortest path to the bottom-right door. # We use a heap to quickly find a single path, and then only focus on the remaining # paths with a shorter length than the best found. # Part 2: Find the length of the longest path that leads to the bottom-right door. # Simple BFS using a queue. NAME = "Day 17: Two Steps Forward" from heap import MinHeap from md5 import md5 def parseInput(stream): return stream.read().strip() UP = lambda x, y: (x, y - 1) DOWN = lambda x, y: (x, y + 1) LEFT = lambda x, y: (x - 1, y) RIGHT = lambda x, y: (x + 1, y) VALID = set(["b", "c", "d", "e", "f"]) def openDoors(prefix, path): a, b, c, d = md5(prefix+path)[:4] doors = [] if a in VALID: doors.append(('U', UP)) if b in VALID: doors.append(('D', DOWN)) if c in VALID: doors.append(('L', LEFT)) if d in VALID: doors.append(('R', RIGHT)) return doors def part1(input): dist = lambda x, y: (3 - x) + (3 - y) shortest = None h = MinHeap() h.push(("", (0, 0)), dist(0, 0)) while h.any(): path, (x, y) = h.pop() if shortest is not None and len(shortest) <= len(path): continue for (n, door) in openDoors(input, path): nx, ny = door(x, y) if nx == 3 and ny == 3 and (shortest is None or len(path+n) < len(shortest)): shortest = path+n elif 0 <= nx and nx < 4 and 0 <= ny and ny < 4: h.push((path + n, (nx, ny)), dist(nx, ny)) return shortest def part2(input): longest = None q = [("", (0, 0))] while 0 < len(q): path, (x, y) = q.pop(0) for (n, door) in openDoors(input, path): nx, ny = door(x, y) if nx == 3 and ny == 3: if (longest is None or len(path+n) > longest): longest = len(path+n) elif 0 <= nx and nx < 4 and 0 <= ny and ny < 4: q.append((path + n, (nx, ny))) return longest
434ae616d94f70158be980d1bedfd2096d209b2c
FaisalWant/ObjectOrientedPython
/Threading/DerekExamples/newBankThread.py
1,038
3.5625
4
import threading import time import random class BankAccount(threading.Thread): acctBalance=100 def __init__(self,name,moneyRequest): threading.Thread.__init__(self) self.name= name self.moneyRequest=moneyRequest def run(self): threadLock.acquire() BankAccount.getMoney(self) threadLock.release() @staticmethod def getMoney(customer): print("{} tries to withdrawl ${} at {}".format(customer.name, customer.moneyRequest, time.strftime("%H,%M,%S",time.gmttime()))) if BankAccount.acctBalance-customer.moneyRequest >0: BankAccount.acctBalance-=customer.moneyRequest print("New account Balance:${}".format(BankAccount.acctBalance)) else: print("Not enought money in account") print("Current balance: ${}".format(BankAccount.acctBalance)) time.sleep(3) threadLock= threading.Lock() doug=BankAccount("Doug",1) Faisal=BankAccount("Faisal",100) sally=BankAccount("sally",50) doug.start() Faisal.start() sally.start() doug.join() Faisal.join() sally.join() print("Execution Ends")
17567f0bdcc984551780b2a1b7c66b0519ff52e9
pvelardea/curso-python-datos
/scripts/code01.py
348
3.8125
4
# -*- coding: utf-8 -*- """ Codigo 01 "Sumar dos números10" @author: pvelarde """ # Almacenar numeros num1 = input('Introducir primer número: ') num2 = input('Introducir segundo número: ') # Sumar los dos números sum = float(num1) + float(num2) # Mostrar la su,a print('La suma de {0} y {1} is {2}'.format(num1, num2, sum))
73c52a2cc0a9b5c7e821656831bf8f6bf024b705
veb-101/Coding-Practice-Problems
/CodeSignal Arcade/Core/problem_01.py
442
4.125
4
# https://app.codesignal.com/arcade/code-arcade/intro-gates/wAGdN6FMPkx7WBq66 ''' You are given a two-digit integer n. Return the sum of its digits. Example For n = 29, the output should be addTwoDigits(n) = 11. ''' def addTwoDigits(n): return n // 10 + n % 10 # def addTwoDigits(n): # total = 0 # while n > 0: # total += n % 10 # n //= 10 # return total print(addTwoDigits(29)) print(addTwoDigits(99))
3390445dcd297e67f5dcfb4ef643a9ac692a19d6
manas5110/topcoder
/7.py
158
3.515625
4
x,y=int(input()),int(input()) out=[] for i in range(x): inter=[] for j in range(y): inter.append(i*j) out.insert(i,inter) print(out)
8ed3a6113b16325023702179f4073fee2c756198
WojciechMat/LightRacers
/src/Game.py
7,335
3.671875
4
import tkinter import turtle import common from Player import Player import time class Game: def __init__(self): self.win_size = common.win_size self.win_size = common.win_size self.pen = turtle.Turtle() self.pen.speed(0) self.pen.color("white") self.pen.hideturtle() self.pen.penup() var_file = open("variables", 'r') variables = var_file.read().splitlines() var_file.close() self.player1 = Player("stop", -1 * self.win_size / 2 + 70, "red", self.win_size, variables[0]) self.player2 = Player("stop", self.win_size / 2 - 70, "blue", self.win_size, variables[1]) self.init_delay = float(variables[2]) self.delay = self.init_delay self.player1.hideturtle() self.player2.hideturtle() self.started = False self.aborted = False self.style = ("Courier", 12, "normal") def __del__(self): # catching an exception which occurs when closing the program during a main game-loop try: self.player1.hideturtle() self.player2.hideturtle() self.player1.restart() self.player2.restart() self.started = False self.pen.clear() self.aborted = True del self except tkinter.TclError: pass def draw_scores(self): self.pen.clear() self.pen.color("red") self.pen.goto(-200, 280) self.pen.write("{} : {}".format(self.player1.name, self.player1.score), align="center", font=self.style) self.pen.color("blue") self.pen.goto(200, 280) self.pen.write("{} : {}".format(self.player2.name, self.player2.score), align="center", font=self.style) if self.aborted: self.pen.clear() def tie(self): self.pen.goto(0, 0) self.pen.clear() self.pen.color("white") self.pen.write("Tie!", align="center", font=("Courier", 50, "normal")) time.sleep(1) self.pen.clear() def first_wins(self): self.pen.goto(0, 0) self.pen.clear() self.pen.color("white") self.pen.write("{} wins!".format(self.player1.name), align="center", font=("Courier", 50, "normal")) time.sleep(1) self.pen.clear() self.player1.score += 1 def second_wins(self): self.pen.goto(0, 0) self.pen.clear() self.pen.color("white") self.pen.write("{} wins!".format(self.player2.name), align="center", font=("Courier", 50, "normal")) time.sleep(1) self.pen.clear() self.player2.score += 1 # countdown before starting main game loop def countdown(self): # catching an exception which occurs when closing the program during a countdown try: if not self.started and not self.aborted: self.started = True self.pen.clear() cd = turtle.Turtle() cd.speed(0) cd.color("purple") cd.hideturtle() cd.penup() cd.goto(0, 0) cd.write("3", align="center", font=("Courier", 50, "normal")) time.sleep(0.5) cd.clear() cd.write("2", align="center", font=("Courier", 50, "normal")) time.sleep(0.5) cd.color("white") cd.clear() cd.write("1", align="center", font=("Courier", 50, "normal")) time.sleep(0.5) cd.color("green") cd.clear() cd.write("GO!", align="center", font=("Courier", 50, "normal")) time.sleep(0.5) cd.clear() self.draw_scores() self.player2.direction = "down" self.player1.direction = "up" self.main() if self.aborted: self.pen.clear() except tkinter.TclError: pass # starting game-screen def begin(self): if self.aborted: return self.delay = self.init_delay self.pen.penup() self.pen.hideturtle() self.player1.showturtle() self.player2.showturtle() common.window.update() common.window.bgcolor("black") self.pen.clear() self.draw_scores() self.started = False self.pen.goto(0, 0) self.pen.color("purple") if not self.aborted: self.pen.write("Press enter to start", align="center", font=self.style) if not self.started and not self.aborted: common.window.listen() common.window.onkeypress(self.countdown, "Return") if self.aborted: self.pen.clear() def main(self): if self.aborted: return # controls common.window.listen() common.window.onkeypress(self.player1.go_up, "Up") common.window.onkeypress(self.player1.go_down, "Down") common.window.onkeypress(self.player1.go_left, "Left") common.window.onkeypress(self.player1.go_right, "Right") common.window.onkeypress(self.player2.go_up, "w") common.window.onkeypress(self.player2.go_down, "s") common.window.onkeypress(self.player2.go_left, "a") common.window.onkeypress(self.player2.go_right, "d") self.draw_scores() # main game loop while self.started is True and not self.aborted: delay_changer = 0.0 common.window.update() self.player1.clicked = False self.player2.clicked = False first_wins_var = False second_wins_var = False if self.player1.isOut(): second_wins_var = True if self.player2.isOut(): first_wins_var = True self.player1.move_all() self.player2.move_all() if len(self.player1.segments) % 10 == 0 and self.delay > 0.0009: self.delay -= 0.0008 for segment in self.player1.segments: if segment.distance(self.player2) < 10: first_wins_var = True if segment.distance(self.player1) < 10: second_wins_var = True for segment in self.player2.segments: if segment.distance(self.player1) < 10: second_wins_var = True if segment.distance(self.player2) < 10: first_wins_var = True if (first_wins_var and second_wins_var) or self.player1.distance(self.player2) < 5: self.tie() time.sleep(1) self.player1.restart() self.player2.restart() self.begin() elif second_wins_var: self.second_wins() time.sleep(1) self.player1.restart() self.player2.restart() self.begin() elif first_wins_var: self.first_wins() time.sleep(1) self.player1.restart() self.player2.restart() self.begin() time.sleep(self.delay)
7b3291e14ea6273e216bae60d43fa8344497e4c8
cyyrusli/hr30dayschallenge
/day17.py
862
4.3125
4
# Day 17 coding challenge - More exceptions # Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and # p, as parameters and returns the integer result of n**p. If either n or p is negative, then the method must throw # an exception with the message: n and p should be non-negative. class Calculator: def power(self, n, p): try: if n < 0: return 'n and p should be non-negative' elif p < 0: return 'n and p should be non-negative' except ValueError: return 'Not an integer' ans = n**p return ans myCalculator=Calculator() T=int(input()) for i in range(T): n,p = map(int, input().split()) try: ans=myCalculator.power(n,p) print(ans) except Exception as e: print(e)
3361aab69bbd9de8f843bcdd30920ea6aef293aa
chrislucas/code-wars-python
/math/theory/CountOneInASegment/solution/CountingOnes.py
840
3.96875
4
''' https://www.codewars.com/kata/596d34df24a04ee1e3000a25/train/python ''' def countOne(left, right): # Your code here! return 0 ''' quando subtraimos 1 de um numero n, todos os bits da direita ate o bit mais significativo a direita sao invertidos exemplo 10 = 1010. 10-1=9=1001 9 = 1001. 9-1=8=1000 n & (n-1) transforma o bit menos significativo de n em 0 se colocarmos isso num loop podemos otimizar a contagem de bits signiticativos ''' def count_ones(n): acc = 0 while n > 0: n &= (n - 1) acc += 1 return acc def is_power_of_2(n): return n & (n - 1) == 0 and n > 0 def test(): for x in range(0, 255): #print("x: %d nbits: %d" % (x, 1 if is_power_of_2(x) else count_ones(x))) print("x: %d nbits: %d" % (x, count_ones(x))) test() if __name__ == '__main__': pass
92ed11a6229042e844eeeaf8b6539d5dd6db18cb
southpawgeek/perlweeklychallenge-club
/challenge-002/paulo-custodio/python/ch-2.py
1,302
4.09375
4
#!/usr/bin/env python # Challenge 002 # # Challenge #2 # Write a script that can convert integers to and from a base35 # representation, using the characters 0-9 and A-Y. Dave Jacoby came up # with nice description about base35, in case you needed some background. import sys def format_digit(n): if n<10: return chr(n+ord('0')) else: return chr(n+ord('A')-10) def format_number(n, base): negative = True if n<0 else False n = abs(n) output = "" while True: d = n % base n = int(n / base) output = format_digit(d) + output if n == 0: break if negative: output = "-" + output return output def scan_digit(str): str = str.upper() if str >= "0" and str <= "9": return ord(str)-ord("0") elif str >= "A" and str <= "Z": return ord(str)-ord("A")+10 else: return -1 def scan_number(str, base): n, negative = 0, False if str[0] == "-": str = str[1:] negative = True while str != "": d = scan_digit(str[0]) str = str[1:] assert d>=0 and d<base n = n*base + d if negative: n = -n return n if sys.argv[1] == "-r": print(scan_number(sys.argv[2], 35)) else: print(format_number(int(sys.argv[1]), 35))
24c67d2590bdc6bc4cda29f2c06928d8118f94c1
Cationiz3r/C4T-Summer
/Session-4/list/for/capPrint.py
120
4.0625
4
print() myList = ["Movies", "Games", "Still-Games", "Games?", "Comics"] for i in myList: print(i.upper()) print()
c3504dff69920d445546129e28d47dbee584dc76
hqhs/devman_challenges
/6_password_strength/password_strength.py
1,417
3.6875
4
import re def check(password, pattern): if re.fullmatch(pattern, password): return 0 else: return 1 def check_for_re_patterns(password): patterns = [ '[0-9]*\Z', '[a-zA-Z]*\Z', '[^@]+@[^@]+\.[^@]+', '[^0-9a-zA-Z]*\Z' ] points = 0 for pattern in patterns: points += check(password, pattern) return points def lenght_check(password): if len(password) < 8: return 1 elif len(password) < 10: return 1.5 elif len(password) < 16: return 2 else: return 2.5 def most_common_check(password): ten_most_popular_passwords = ["password", "12345678", "qwertyui", "123456789", "baseboll", "football", "qwertyuiop", "1234567890", "superman", "1qaz2wsx"] if password in ten_most_popular_passwords: return 0 else: return 1 def get_password_strength(password): passw_str = 1 + lenght_check(password) * most_common_check(password) \ * check_for_re_patterns(password) if passw_str > 10: passw_str = 10 return passw_str if __name__ == '__main__': password = input("Print your password: ") print("Strength of your password is: \n", get_password_strength(password))
a06208c839a3331629c2116f667e73a693dc62a9
chyidl/chyidlTutorial
/root/os/DSAA/DataStructuresAndAlgorithms/python/sort_selection_array_implement.py
1,878
4.34375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # # sort_selection_array_implement.py # python # # 🎂"Here's to the crazy ones. The misfits. The rebels. # The troublemakers. The round pegs in the square holes. # The ones who see things differently. They're not found # of rules. And they have no respect for the status quo. # You can quote them, disagree with them, glority or vilify # them. About the only thing you can't do is ignore them. # Because they change things. They push the human race forward. # And while some may see them as the creazy ones, we see genius. # Because the poeple who are crazy enough to think thay can change # the world, are the ones who do." # # Created by Chyi Yaqing on 02/18/19 16:16. # Copyright © 2019. Chyi Yaqing. # All rights reserved. # # Distributed under terms of the # MIT """ Selection Sort: The selection sort algorithm sorts an array by repeatedly finding the minimum element(considering ascending order)from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The Subarray which is already sorted 2) Remaining subarray which is unsorted In every iteration of selection sort, the minimum element (considering ascendin order) from the unsorted subarray is picked and moved to the sorted subarray """ # Python program for implementation of Selection Sort def selectionSort(arr): for i in range(len(arr)): # Find the minimum element in remaining unsorted array min_idx = i for j in range(i+1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j # Swap the found minimum element with the first element arr[i], arr[min_idx] = arr[min_idx], arr[i] # Driver code to test above arr = [64, 25, 12, 22, 11] print("Original array is : {}".format(arr)) selectionSort(arr) print("Sorted array is : {}".format(arr))
511a0d2736a2476a32d701974f8abc5977592a28
ilahoti/csci-101-102-labs
/102/Week4A-chess.py
558
3.796875
4
# Ishaan Lahoti # CSCI 102 – Section C # Week 4 - Lab A - Missing Chess Pieces # References: None # Time: 20 minutes print("Please enter the number of white chess pieces that you have of each type:") kings = int(input("KINGS> ")) queens = int(input("QUEENS> ")) rooks = int(input("ROOKS> ")) bishops = int(input("BISHOPS> ")) knights = int(input("KNIGHTS> ")) pawns = int(input("PAWNS> ")) print("The output below provides the number of each type you have (over or under):") print("OUTPUT", 1 - kings, 1 - queens, 2 - rooks, 2 - bishops, 2 - knights, 8 - pawns)
c9f1aa35355de516e9f0f377d10ae047eebbafde
yangbaoxi/dataProcessing
/python/字符串/创建字符串/create.py
400
4.59375
5
# 字符串简介 # 字符串是 python 数据类型之一 使用 "" / '' 创建: string = 'hello world' print(string) # hello world # Python 访问字符串中的值, 可以通过'索引'访问字符串的某一个值 print(string[0]) # h print(string[0:3]) # hel 可以传入 [索引:索引] 的方式获取某一起点到结束点的值 print(string[2: -1]) # llo worl
7fdd521f61749f07fc83803c4a6938b1474e3234
alagram/lpthw
/ex/ex15.py
412
3.921875
4
from sys import argv # run a script with arguments script, filename = argv # open a file txt = open(filename) print "Here's your file %r" % filename # read a file print txt.read() print "Type the filename again:" # get input from the user file_again = raw_input("> ") # open a file txt_again = open(file_again) # read a file print txt_again.read() print txt_again.readlines() txt.close() txt_again.close()
dd5df63efe5f90ca4523598e3771ebc22a80bb21
FarukA1/FirstProject
/Intro.py
1,634
3.796875
4
import sys phones = ('iPhone', 'Samsung', 'OnePlus', 'Pixel', 'blackberry') iphone = phones[0] samsung = phones[1] onePlus = phones[2] pixel = phones[3] blackberry = phones[4] print("Welcome to Phone Dealer") first_Name = raw_input("What is your first name?") second_Name = raw_input(first_Name + " , " + "what is your second name?") print("\n") print("Your full name is " + first_Name + " " + second_Name) person_Age = input("How old are you?") if person_Age <= 17: print("Unfortunately, you cannot purchase a phone by yourself") print("Do you want to quit?") under_Age = raw_input("yes or no") yes = "yes" or "Yes" no = "no" or "No" if under_Age == no: under_Age_Mother_Name = raw_input("What is your mother full name") under_Age_Mother_Age = input("How much is your mother?") under_Age_Father_Name = raw_input("What is your father full name") under_Age_Father_Age = input("How much is your father?") print("1. " + iphone) print("2. " + samsung) print("3. " + onePlus) print("4. " + pixel) print("5. " + blackberry) under_Age_Select_Phone = raw_input("This are the phones we have in stock, please one:") print("We are out of stock!") if under_Age == yes: print("Thanks for shopping at dealer phone!") sys.exit() if person_Age >= 18: print("1. " + iphone) print("2. " + samsung) print("3. " + onePlus) print("4. " + pixel) print("5. " + blackberry) under_Age_Select_Phone = raw_input("This are the phones we have in stock, please one:") print("We are out of stock")
cb83677e6fadf9afa03c145a2ca0ddad5db06f12
mhrao97/Data-Structures-And-Algorithms
/project_problems_vs_algorithms/Problem_2.py
4,221
4.28125
4
# Problem 2: Search in a Rotated Sorted Array """ Search in a Rotated Sorted Array You are given a sorted array which is rotated at some random pivot point. Example: [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2] You are given a target value to search. If found in the array return its index, otherwise return -1. You can assume there are no duplicates in the array and your algorithm's runtime complexity must be in the order of O(log n). """ def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ # check if array is rotated - if a pivot is found, then array is rotated # if a pivot is not found, then array is not rotated # on a rotated array, compare the number with the pivot, then search # the two sub-arrays around the pivot pivot = find_pivot(input_list, 0, len(input_list) - 1) if pivot == -1: return binary_search(input_list, 0, len(input_list) - 1, number) if input_list[pivot] == number: return pivot if input_list[0] <= number: return binary_search(input_list, 0, pivot - 1, number) return binary_search(input_list, pivot + 1, len(input_list) - 1, number) def find_pivot(arr, start_index, end_index): if start_index > end_index: return -1 if start_index == end_index: return start_index mid_index = (start_index + end_index) // 2 if mid_index < end_index and arr[mid_index] > arr[mid_index + 1]: return mid_index if mid_index > start_index and arr[mid_index] < arr[mid_index - 1]: return (mid_index - 1) if arr[start_index] >= arr[mid_index]: return find_pivot(arr, start_index, mid_index - 1) return find_pivot(arr, mid_index + 1, end_index) def binary_search(array, start_index, end_index, target): '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for start_index: initial position to start search end_index: last position to end search returns: int: the index of the target, if found, in the source -1: if the target is not found ''' while start_index <= end_index: mid_point = (start_index + end_index) // 2 mid_item = array[mid_point] if target == mid_item: return mid_point elif target < mid_item: end_index = mid_point - 1 else: start_index = mid_item + 1 return -1 def linear_search(input_list, number): for index, element in enumerate(input_list): if element == number: return index return -1 def test_function(test_case): if len(test_case) != 2: print("Please provide both - an array and a target") return input_list = test_case[0] number = test_case[1] if linear_search(input_list, number) == rotated_array_search(input_list, number): print("Pass") else: print("Fail") print("\n----------test cases given in the problem------------") test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6]) test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 8]) test_function([[6, 7, 8, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 10]) print("\n-------edge cases---------------------") print("\ncase where a target is searched in an empty array") test_function([[],0]) print("\ncase where target is not passed in an empty array") test_function([[],]) print("\ncase where an array is passed but target is missing") test_function([[6, 7, 8, 1, 2, 3, 4]]) # the above test cases should print the following results """ ----------test cases given in the problem------------ Pass Pass Pass Pass Pass -------edge cases--------------------- case where a target is searched in an empty array Pass case where target is not passed in an empty array Please provide both - an array and a target case where an array is passed but target is missing Please provide both - an array and a target """
873e1fb17cb78bd58e85fab30db9e19ae53fa9da
poojakancherla/Problem-Solving
/AlgoExpert/CompanyQuestions/Amazon/missing-item.py
229
3.90625
4
from collections import Counter def missing(arr1, arr2): counter = Counter(arr2) for num in arr1: if not counter[num]: return num arr1 = [4, 8, 12, 9, 3] arr2 = [4, 8, 9, 3] print(missing(arr1, arr2))
96945739c4cfca6b211c8a6ca8454a0ef68db848
ashishchandra1/project-euler
/assignment-1.py
470
4.40625
4
#!/usr/bin/env python """ Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def main(): sum = 0 for num in range(1,1000): if num % 3 == 0 or num % 5 == 0: sum += num print "The sum of all multiples of 3 and 5 below 1000 is: ",sum if __name__ == '__main__': main()
997844b03e9bc3e861f0c8b1832586029c1d2e86
HeDefine/LeetCodePractice
/Q496.下一个更大元素 I.py
1,741
3.90625
4
#!/usr/bin/env python3 # https://leetcode-cn.com/problems/next-greater-element-i # 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。 # nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。 # # 示例 1: # 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. # 输出: [-1,3,-1] # 解释: # 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 # 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 # 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。 # # 示例 2: # 输入: nums1 = [2,4], nums2 = [1,2,3,4]. # 输出: [3,-1] # 解释: #   对于num1中的数字2,第二个数组中的下一个较大数字是3。 # 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。 # # 注意: # nums1和nums2中所有元素是唯一的。 # nums1和nums2 的数组大小都不超过1000。 class Solution: def nextGreaterElement(self, nums1: [int], nums2: [int]) -> [int]: dic = dict() for idx, i in enumerate(nums2): for t in nums2[idx:]: if t > i: dic[i] = t break result = list() for num in nums1: result.append(dic.get(num, -1)) return result print(Solution().nextGreaterElement([4, 1, 2], [1, 3, 4, 2])) # [-1,3,-1] print(Solution().nextGreaterElement([2, 4], [1, 2, 3, 4])) # [3,-1]
1d670d2d71c069541b849ab766a8bd628c6b40a4
ravi4all/PythonAprilRegular_19
/LoopsIntro.py
373
4.21875
4
#Basic For Loop with a simple range ''' for count in range(1,11): print(count) print("Still inside loop") print("Loop Exit") ''' #Loop with step inside range function ''' for i in range(10,101,10): print(i) ''' # Reverse Loop for i in range(11,1,-1): print(i) print("----------------------") for i in reversed(range(1,11)): print(i)
1c7ee6a701b674c86a711e2f3687421ab2ece27e
ramkumar1308/python_basics_ram
/odd_even.py
221
3.9375
4
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for i in range(10): if i % 2 == 0: print "%d is even " % i else: print "%d is odd " % i for i in range(len(a)): print i print len(a)
67bef3a2e6a5e7acf5b26c88043d7ed0bbee2bcb
shammahm24/python2020-2
/leapYear.py
560
4.1875
4
#!/usr/bin/python ################################################## ## Program that checks if an entered year is a leap ## year ################################################## ## Author: Tanyaradzwa Matasva ## Course: CPSC-442-11 ## Instructor: Dr Abdelshakour Abuzneid ## School: University of Bridgeport ################################################## year = int(input("Enter year: ")) if year % 4 ==0 : if year % 100 ==0: if year % 400 ==0: print("True") else: print("False") else: print("True") else: print("False")
cf619951da48bd17a901365fa64c9a7fb5435734
ursu1964/Libro2-python
/Cap1/Ejemplo 1_3.py
3,431
4.125
4
# -*- coding: utf-8 -*- """ @author: guardati Ejemplo 1_3 Funciones predefinidas para trabajar con listas. Ejemplos de uso. """ dias_laborables = ["lunes", "martes", "miércoles", "jueves", "viernes"] colores_primarios = ['rojo', 'verde', 'azul'] precios = [205.30, 107.18, 25, 450, 310.89, 170.23, 340] pares = list(range(0, 30, 2)) impares = list(range(29, 0, -2)) colores_repetidos = colores_primarios * 2 # ============================================================================= # Algunas funciones para el manejo de listas. # ============================================================================= dias_laborables.append('sábado') # Agrega sábado al final de la lista. print('\nSemana laborable con un día extra =', dias_laborables) # Cuenta el número de veces que aparece lunes en la lista. print(f"\nEl lunes aparece = {dias_laborables.count('lunes')} vez (veces).") # Regresa el total de elementos que tiene la lista. print('Total de precios =', len(precios)) # Agrega en la primera posición el valor blanco. colores_primarios.insert(0, 'blanco') print('\nLista con un nuevo elemento:', colores_primarios) # No existe la posición 10. Lo inserta al final. colores_primarios.insert(10, 'amarillo') print('Lista con un nuevo elemento:', colores_primarios) # Agrega al final de la lista todos los elementos de la lista impares. pares.extend(impares) print('\nLista de pares extendida con la lista impares:', pares) # Quita el valor sábado de la lista. dias_laborables.remove('sábado') print('\nVolviendo a la normalidad =', dias_laborables) # Regresa la posición de rojo dentro de la lista. print('\nPosición del rojo:', colores_primarios.index('rojo')) print('Posición del segundo azul:', colores_repetidos.index('azul', 3)) # Da el error: ValueError: 'gris' is not in list # print('Posición del gris:', colores_repetidos.index('gris')) # Ordena los elementos de la lista de menor a mayor. precios.sort() print('\nPrecios ordenados de menor a mayor:', precios) # Ordena los elementos de la lista de mayor a menor. colores_repetidos.sort(reverse = True) print('Colores ordenados de mayor a menor:', colores_repetidos) # Genera una nueva lista ordenada, sin alterar la lista original. lista_ordenada = sorted(dias_laborables) lis_ord_long = sorted(dias_laborables, key = len) print('\nDías laborables sin alterar:', dias_laborables) print('Días laborables ordenados:', lista_ordenada) print('Días laborables ordenados por longitud:', lis_ord_long) # Invierte el orden de los elementos de la lista. impares.reverse() print('\nImpares en orden inverso:', impares) # Quita y regresa el elemento de la posición 0. quitado = colores_primarios.pop(0) print('\nEl elemento quitado es:', quitado) print('La lista quedó:', colores_primarios) rescatado = dias_laborables.pop() # Sin posición: quita el último. print('Se rescató para el fin de semana:', rescatado) print('Los días laborables quedaron:', dias_laborables) # print(precios.pop(10)) # IndexError: pop index out of range # Quita todos los elementos de la lista, dejándola vacía. precios.clear() print('\nLa lista de precios quedó vacía:', precios) # print(precios.pop()) IndexError: pop from empty list # Quita el segundo elemento de la lista. del colores_primarios[1] print('\nColores primarios luego de quitar el segundo elemento:', colores_primarios)
c14e340e885f4d96203197f99318819fbc8f76fd
MelCarl/PS239T-Final-Project
/Code/01_Webscraping_Python.py
1,513
3.71875
4
# coding: utf-8 # In[ ]: #In this document, I use Python to code a webscraper #that takes data from Wikipedia's List of Sieges and #produces a csv file that has the siege name, war #during which it occcured, the date of the seige, #and extra detail about who initiated the siege. # In[2]: #Import required modules import requests from bs4 import BeautifulSoup import os import re import csv from operator import itemgetter from itertools import groupby # In[3]: #Make a GET request req = requests.get('https://en.wikipedia.org/wiki/List_of_sieges') #Read the content of the server’s response src = req.text #Soup it soup = BeautifulSoup(src, "lxml") #print(soup.prettify()) # In[5]: #Get all ul elements rows = soup.find_all("ul") print(rows) # In[6]: #Subset the above rows to get only the modern sieges (from 1800s to the present) modernsieges = rows[26:28] #print(modernsieges) #type(modernsieges) # In[7]: #Keep only the text in each of those cells rowData = [cell.text for cell in modernsieges] #print(rowData) #type(rowData) #Split at each \n to return a list of lines for line in rowData: modSiege = line.split("\n") #print(Siege) #Get the number of elements in the list len(modSiege) #Get rid of first and last elements, which are blank FinalListofSieges = modSiege[1:77] #Print(FinalListofSieges) #Export as csv import pandas as pd my_df = pd.DataFrame(FinalListofSieges) my_df.to_csv('1-ListofSiegesScrapedfromWikipedia.csv', index=False, header=False)
158d6175ea9cef62b650521ef3578cd9ff2e7b00
GaoLF/LeetCode-PY
/Sum Root to Leaf Numbers.py
907
3.65625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @return {integer} def sumNumbers(self, root): return self.sumof_Tree(root,0) def sumof_Tree(self,root,up_v): if not root: return up_v sum = up_v*10 + root.val res = 0 if root.left: res += self.sumof_Tree(root.left,sum) if root.right: res += self.sumof_Tree(root.right,sum) if not root.left and not root.right: res += sum return res A = Solution() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) f = TreeNode(6) g = TreeNode(7) h = TreeNode(8) a.left = b a.right = c b.left = d c.right = e b.right = f f.left = g g.left = h print A.sumNumbers(a)
6da7456cc00fb7dad7799c9569b4d3fd4bb773af
Abhiaish/GUVI
/ZEN class/day 2/day 2/stack.py
142
3.8125
4
#stack implementation in python s=['x','y','z'] s.append('a') s.append('b') print(s) print(s.pop()) print(s) print(s.pop()) print(s)
6132ea1ccadfc61f818e77ce3ee289c0e17a7c09
ArdiSetiw/Login-Discount-Program
/Discount System.py
5,206
3.6875
4
# Program Diskon import secrets as gaca print("="*57) print("""\033[36m Menu Cafe PostTest 3 > Beverages Menu - Teh = Rp 5000 - Kopi = Rp 5000 - Air = Rp 2000 - JusBuah = Rp 10000 - EnergyDrink = Rp 10000 > Food Menu - FrenchFries = Rp 10000 - NasiAyam = Rp 15000 - Pizza = Rp 20000 - Borger = Rp 15000 - Pudding = Rp 5000\033[39m """) print("="*57) # Hari beli day = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] hari = gaca.choice(day) print("\033[32m Hey you order this on",hari,"\033[39m") print("="*57) # Proses Input Minuman x = 1 hargaMn = [] #List untuk harga minuman Minum = [] #List minuman print("-- Beverages --") print(" Type your order as in menu\n Type end if you finish ordering") while x > 0 : mn = str(input("> Beverages Order = ")) if mn == "Teh" or mn == "teh" : price_mn = 5000 hargaMn.append(price_mn) Minum.append(mn) elif mn == "Kopi" or mn == "kopi" : price_mn = 5000 hargaMn.append(price_mn) Minum.append(mn) elif mn == "Air" or mn == "air" : price_mn = 2000 hargaMn.append(price_mn) Minum.append(mn) elif mn == "JusBuah" or mn == "jusbuah" : price_mn = 10000 hargaMn.append(price_mn) Minum.append(mn) elif mn == "EnergyDrink" or mn == "energydrink" : price_mn = 10000 hargaMn.append(price_mn) Minum.append(mn) elif mn == "End" or mn == "end" : print("-"*57) break else : print(" Sorry We don't have that in the Menu") total_mn = sum(hargaMn) # Proses Input Makanan y = 1 hargaMk = [] # List Harga Makanan makan = [] # List Makanan print("-- Food --") print(" Type your order as in menu\n Type end if you finish ordering") while y > 0 : mk = str(input("> Food Order = ")) if mk == "FrenchFries" or mk == "frenchfries" : price_mk = 10000 hargaMk.append(price_mk) makan.append(mk) elif mk == "NasiAyam" or mk == "nasiayam" : price_mk = 5000 hargaMk.append(price_mk) makan.append(mk) elif mk == "Pizza" or mk == "pizza" : price_mk = 20000 hargaMk.append(price_mk) makan.append(mk) elif mk == "Burger" or mk == "burger" : price_mk = 15000 hargaMk.append(price_mk) makan.append(mk) elif mk == "Pudding" or mk == "pudding" : price_mk = 10000 hargaMk.append(price_mk) makan.append(mk) elif mk == "End" or mk == "end" : break else : print(" Sorry We don't have that in the Menu") total_mk = sum(hargaMk) # Diskon Minuman if len(Minum) >= 3 : print("="*57) print("\033[36mYour Beverages Order") for d in Minum : print("\033[36m-",d,"\033[39m") print("\033[32m| Beverages Prices = Rp",total_mn,"\033[39m") print("| You got 10% discount for ordering at least 3 beverages") total_mn = total_mn - (total_mn*10/100) print("\033[32m| Beverages Prices After Discount = ","Rp",total_mn,"\033[39m") else : print("\033[36mYour Beverages Order") for d in Minum : print("\033[36m-",d,"\033[39m") print("\033[32m| Beverages Prices = Rp",total_mn,"\033[39m") print("="*57) # Diskon Makanan if len(makan) >= 2 : print("\033[36mYour Food Order") for f in makan : print("\033[36m-",f,"\033[39m") print("\033[32m| Food's Prices = Rp ",total_mk,"\033[39m") print("| You got 5% discount for ordering at least 2 foods ") total_mk = total_mk - (total_mk*5/100) print("\033[32m| Food's Prices After Discount = ","Rp",total_mk,"\033[39m") else : print("\033[36mYour Food Order") for f in makan : print("\033[36m-",f,"\033[39m") print("\033[32m| Food's Prices = Rp",total_mk,"\033[39m") price = total_mn + total_mk print("="*57) print("\033[32mBeverages and Food's Prices = Rp",price,"\033[39m") print("="*57) # Diskon Hari if hari == "Saturday" or hari == "Sunday" : print("Since you order this on",hari,"you got 5% discount") price = price - (price * 5/100) print("\033[32mPrice After Weekend's Discount = Rp",price,"\033[39m") else : print("you came to our shop at",hari,"here 10% discount") price = price - (price * 10/100) print("\033[32mPrice After Weekday's Discount = Rp",price,"\033[39m") # Pembayaran and The End of the program print("="*57) print("""how would you like to pay > Cash > CC Card > eMoney""") print("="*57) bayar = str(input("Payment = ")) if bayar == "eMoney" or bayar == "emoney" : print("eMoney Payment, you got 5% discount") price = price - (price * 5/100) print("\033[32mFinal Price = Rp",price,"\033[39m") print("="*57) else : print("\033[32mFinal Price = Rp",price,"\033[39m") print("="*57)
478e577a2a20212e325b7803d0fb2304070c5504
thomashirtz/leetcode
/solutions/957-prison-cells-after-n-days.py
714
3.578125
4
from typing import List class Solution: def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]: memory = [] for i in range(N): cells = self.next_state(cells) if tuple(cells) in memory: return list(memory[N % len(memory) - 1]) memory.append(tuple(cells)) return cells def next_state(self, cells): cells_ = [0] * 8 for i in range(1, len(cells) - 1): cells_[i] = int(cells[i - 1] == cells[i + 1]) return cells_ examples = [[[0, 1, 0, 1, 1, 0, 0, 1], 21], [[1, 0, 0, 1, 0, 0, 1, 0], 1000000000]] for example in examples: print(Solution().prisonAfterNDays(*example))
cbc6170ba13b20001d7254807598f64fef1c2170
zmbush/binaries
/bf
1,936
3.65625
4
#!/usr/bin/env python import sys import string debug = False def main(): if len(sys.argv) < 2: print 'You must specify a file' return 1 else: try: program = list(open(sys.argv[1], 'r').read()) p = 0 pc = 0 memory = [ 0 ] backSearch = 0 forwardSearch = 0 while pc >= 0 and pc < len(program): c = program[pc] if backSearch == 0 and forwardSearch == 0: if c == '>': p += 1 if p == len(memory): memory.append(0) elif c == '<': p -= 1 if p < 0: print 'Error: You can\'t have a negative pointer' elif c == '+': memory[p] = memory[p] + 1 elif c == '-': memory[p] -= 1 elif c == '.': sys.stdout.write(chr(memory[p])) elif c == ',': memory[p] = ord(sys.stdin.read(1)) elif c == '[': if memory[p] == 0: forwardSearch = 1 elif c == ']': if memory[p] != 0: backSearch = 1 pc -= 2 pc += 1 elif backSearch: if c == '[': backSearch -= 1 elif c == ']': backSearch += 1 if backSearch > 0: pc -= 1 elif forwardSearch: if c == ']': forwardSearch -= 1 elif c == '[': forwardSearch += 1 if forwardSearch > 0: pc += 1 if debug: print memory continue memstr = '[' for m in memory: if chr(m) in string.printable: memstr += chr(m) + "," else: memstr += str(m) + ',' memstr = memstr[:-1] + ']' print memstr except IOError: print '%s: File not found' % sys.argv[1] return 2 if __name__ == "__main__": sys.exit(main())
79a4c0f49a3d34789dab8d3ce7aa290b326831b7
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4061/codes/1729_2525.py
268
4.1875
4
numero = int(input("digite numero: ")) divisores = 0 cont = numero while(cont > 0): if(numero % cont == 0): print(numero // cont) divisores = divisores + 1 cont = cont - 1 if(divisores < 2): print(divisores, " divisor") else: print(divisores, " divisores")
f704807e9cf2a4fc516f76b5e22f4a74a4eba401
NathanLHall/Project-Euler
/Problem 007.py
752
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 14 11:19:07 2018 @author: NathanLHall """ # Given an integer > 1, this will return the given integer if it is prime. # If it is not prime, it will return None. def checkDivisibility(number, primes): for p in primes: if number % p == 0: return None return number # Given a positive integer, the index = n, will find the nth prime number. def nth_prime(index): primes = [2,3] candidate = 5 while len(primes) < index: modCandidate = checkDivisibility(candidate, primes) if type(modCandidate) == int: primes.append(candidate) candidate += 2 return primes primes = nth_prime(10001) print(primes[-1])
cf854fa92573efba910835ee59707119fe95cb39
MaichelYB/TrainingCode
/training_9.py
1,642
4.25
4
''' ZigZag Conversion https://leetcode.com/problems/zigzag-conversion/ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I Example 3: Input: s = "A", numRows = 1 Output: "A" Constraints: 1 <= s.length <= 1000 s consists of English letters (lower-case and upper-case), ',' and '.'. 1 <= numRows <= 1000 ''' class Solution: def convert(self, s: str, numRows: int) -> str: results = ['']*numRows total_len_1_row = numRows + numRows - 2 max_num = total_len_1_row // 2 pos = 0 is_reverse = False results[0] = s[0] if numRows > len(s) - 1: return s if numRows < 2: return s for i in range(1, len(s)): if pos == 0 and is_reverse == True: is_reverse = False if pos == max_num: is_reverse = True if pos < max_num and is_reverse == False: results[pos + 1] += s[i] pos += 1 elif pos == max_num and is_reverse == True: results[pos - 1] += s[i] pos -= 1 elif pos < max_num and is_reverse == True: results[pos - 1] += s[i] pos -= 1 return ''.join(results)
08120d229964a1be9de58698363594e7203821e7
RDScambler/RS_biocode
/orthogroup_analysis/count_func_cats.py
1,587
3.828125
4
# This file contains the count_func_cats function, used to count all the functional categories present in an eggnog output file. import group import re import sys def count_func_cats(file): """ count_func_cats takes an eggnog output file as an argument, and counts different functional categories of each OG (note only one category is recorded per OG). These frequncies are stored in a functional category frequency dictionary. Note the function executes succesfully regardless of whether the eggnog output has been refined (i.e. parsed out) or is raw. """ og_list = group.count_ogs(file) overall_list = [] for og in og_list: with open(file) as f: # The cat_list must be appended for each OG in turn. cat_list = [] for line in f: if og in line: # Each seq is assigned up to 3 cats, so re must account for this. res = re.search(r"\s([A-Z]{1,3})\s", line.strip()) if res: func_cat = res.group(1) # Iterates over each letter (for cases where multiple cats are assigned). for cat in range(len(func_cat)): if func_cat[cat] not in cat_list: cat_list.append(func_cat[cat]) # Ignore eggnog nonhits. if len(cat_list) == 0: pass else: for cat in range(len(cat_list)): overall_list.append(cat_list[cat]) # List comprehension is used to generate a dict of counts for each cat in overall_list. func_cat_freq_dict = {i:overall_list.count(i) for i in overall_list} return func_cat_freq_dict # Configure file at command line. file = sys.argv[1] print(count_func_cats(file))
6e07830a26db7d51ab9998e6e2ab9a7f0712dbfc
fsouza/dojo-python-giran-2010-10-23
/palindromo/palindromo.py
323
3.765625
4
def is_palindromo(number): aux = str(number) reverse = aux[::-1] return aux == reverse def encontrar_palindromo(): maior = 999 lista_numeros = range(999) lista_numeros.reverse() lista_palindromos = [x * 999 for x in lista_numeros if is_palindromo(x * 999)] return lista_palindromos[0] print encontrar_palindromo()
aad4d14f18e39cb20a4c5c11be39f38beafc1773
paolo944/exo_python
/5/5.5.py
3,242
3.5625
4
#Exercice 5.5: def est_voyelle(c : str)-> bool: """Précondition : len(c) == 1Retourne True si et seulement si c est une voyelleminiscule ou majuscule.""" return(c == 'a') or (c == 'A') \ or(c == 'e') or (c == 'E') \ or(c == 'i') or (c == 'I') \ or(c == 'o') or (c == 'O') \ or(c == 'u') or (c == 'U') \ or(c == 'y') or (c == 'Y') # Jeu de tests assert est_voyelle('a') == True assert est_voyelle('E') == True assert est_voyelle('b') == False assert est_voyelle('y') == True assert est_voyelle('z') == False #Question 1: def nb_voyelles(c: str) -> int: """Précondition: c est de type str Renvoie le nombre de voyelles dans c.""" compte: int = 0 l: str for l in c: if est_voyelle(l): compte = compte + 1 return compte assert nb_voyelles('la maman du petit enfant le console') == 12 assert nb_voyelles('mr brrxcx') == 0 assert nb_voyelles('ai al o ents') == 5 #Question 2: def voyelles_accents(c: str) -> bool: """Précondition : len(c) == 1Retourne True si et seulement si c est une voyelleminiscule ou majuscule.""" return(c == 'a') or(c == 'A') \ or(c == 'e') or(c == 'E') \ or(c == 'i') or(c == 'I') \ or(c == 'o') or(c == 'O') \ or(c == 'u') or(c == 'U') \ or(c == 'y') or(c == 'Y') \ or(c == "À") or(c == "Â") \ or(c == "Ä") or(c == "Ê") \ or(c == "É") or(c == "È") \ or(c == "Ë") or(c == "Î") \ or(c == "Ï") or(c == "Ô") \ or(c == "Ö") or(c == "Ù") \ or(c == "Û") or(c == "Ü") \ or(c == "Ÿ") or(c == "à") \ or(c == "â") or(c == "ä") \ or(c == "é") or(c == "è") \ or(c == "ê") or(c == "ë") \ or(c == "î") or(c == "ï") \ or(c == "ô") or(c == "ö") \ or(c == "ù") or(c == "û") \ or(c == "ü") or(c == "ÿ") def nb_voyelles_accents(c: str) -> int: """Précondition: c est de type str Renvoie le nombre de voyelles dans c.""" compte: int = 0 l: str for l in c: if voyelles_accents(l): compte = compte + 1 return compte assert nb_voyelles_accents('la maman du bébé le réconforte') == 11 #Question 3: def sans_voyelle(c: str) -> str: """Précondition: c est de type str. Renvoie une chaine de caractere a partir de c mais sans les voyelles.""" l: str c_s: str = "" for l in c: if voyelles_accents(l): c_s = c_s + "" else: c_s = c_s + l return c_s #Jeu de test assert sans_voyelle('aeiouy') == "" assert sans_voyelle('la balle au bond rebondit') == 'l bll bnd rbndt' assert sans_voyelle('mr brrxcx') == 'mr brrxcx' #Question 4: def mot_mystere(c: str) -> str: """Précondition: c est de type str. Renvoie une chaine de caractere en remplacant les voyelles par des - """ l: str c_m: str = "" for l in c: if voyelles_accents(l): c_m = c_m + "_" else: c_m = c_m + l return c_m assert mot_mystere('aeiouy') == '______' assert mot_mystere('la balle au bond rebondit bien') == 'l_ b_ll_ __ b_nd r_b_nd_t b__n' assert mot_mystere('mr brrxcx') == 'mr brrxcx'
ad0d07772323ae729b33f280a092764aadc5eec2
guptaShantanu/Python-Programs
/cuckoo.py
137
3.6875
4
def cuckoo(n): if n==1: return 0 if n==2: return 1 return 1*cuckoo(n-1)+2*cuckoo(n-2)+3*1 print(cuckoo(3))
95f944befb90753828b16b6149df86f90cd58fad
AnnLas/InternTask
/test_calculator.py
1,572
3.5625
4
import unittest from unittest import TestCase from main import calculate class TestCalculator(TestCase): def test_calculate1(self): usb_size = 1 memes = [ ('rollsafe.jpg', 205, 6), ('sad_pepe_compilation.gif', 410, 10), ('yodeling_kid.avi', 605, 12) ] self.assertEqual((22, {'sad_pepe_compilation.gif', 'yodeling_kid.avi'}), calculate(usb_size, memes)) def test_calculate2(self): usb_size = 165 / 1024. memes = [ ('a', 23, 92), ('b', 31, 57), ('c', 29, 49), ('d', 44, 68), ('e', 53, 60), ('f', 38, 43), ('g', 63, 67), ('h', 85, 84), ('i', 89, 87), ('j', 82, 72) ] self.assertEqual((309, {'a', 'b', 'c', 'd', 'f'}), calculate(usb_size, memes)) def test_calculate_one_meme(self): usb_size = 165 / 1024. memes = [ ('a', 23, 92) ] self.assertEqual((92, {'a'}), calculate(usb_size, memes)) def test_calculate_two_meme(self): usb_size = 165 / 1024. memes = [ ('a', 33, 92), ('b', 33, 92) ] self.assertEqual((184, {'a', 'b'}), calculate(usb_size, memes)) def test_calculate_two_same_meme(self): usb_size = 165 / 1024. memes = [ ('a', 23, 92), ('a', 23, 92) ] self.assertEqual((92, {'a'}), calculate(usb_size, memes)) if __name__ == '__main__': unittest.main()
dd47a4a67412a12155a59fbe54e21d96ff7db1f8
btn6364/DataStructure-Algorithms
/Array/sliding_window.py
1,014
4.1875
4
""" Given n non-negative integers a_1, a_2, ..., a_n and a target k, count the number of contiguous subarrays that are less than k. Example: Input: nums = [1,2,3,2,1], k = 3 Output: 7 Explanation: The 8 subarrays that have sum less than 3 are: [1], [2], [3], [2], [1], [1,2], [2,1] """ def numSubArr(nums, k): start = 0 curSum = 0 count = 0 for end in range(len(nums)): curSum += nums[end] while curSum > k: curSum -= nums[start] start += 1 count += end - start + 1 return count def numSubArr_while(nums, k): start, end = 0, 0 curSum, count = 0, 0 while end < len(nums): curSum += nums[end] while curSum > k: curSum -= nums[start] start += 1 count += end - start + 1 end += 1 return count if __name__ == '__main__': nums = [1, 2, 3, 2, 1] k = 3 print(f"Number of arrays: {numSubArr(nums, k)}") print(f"Number of arrays: {numSubArr_while(nums, k)}")
e46756a45d30cedb825aafdaef14e51c0450e580
Lut99/CookieFactory
/APIs/calculator.py
4,322
3.796875
4
# CALCULATOR.py # # A handy library to parse and then executed formulas. # The library supports: # - plus and min # - times and divide # - brackets # - declaration of variables as numbers using mapping at calculation time # - declaration of variables as other variables (at calculation time) # - operator-less formulas (e.g. '[x]' or '5') # - Formulas with sign operators ('+1', '-1') class Formula (): def __init__(self, val1=0, op="+", val2=0, verbose=True): self.val1 = val1 self.val2 = val2 self.op = op self.verbose = verbose def __str__ (self): return("(" + str(self.val1) + self.op + str(self.val2) + ")") # Calculate the formula def calc (self, map = {}): while type(self.val1) == str: if self.val1 not in map: if self.verbose: print("ERR: " + self.val1 + " not declared (interpreting as 0)") return 0 self.val1 = map[self.val1] while type(self.val2) == str: if self.val2 not in map: if self.verbose: print("ERR: " + self.val2 + " not declared (interpreting as 0)") return 0 self.val2 = map[self.val2] if type(self.val1) != int: self.val1 = self.val1.calc(map) if type(self.val2) != int: self.val2 = self.val2.calc(map) if self.op == "+": return self.val1 + self.val2 elif self.op == "-": return self.val1 - self.val2 elif self.op == "*": return self.val1 * self.val2 elif self.op == "/": return self.val1 / self.val2 class Value (Formula): def __init__(self, val, verbose = True): super().__init__(val, "+", 0, verbose) def __str__(self): return str(self.val1) def calc (self, map = {}): while type(self.val1) == str: if self.val1 not in map: if self.verbose: print("ERR: " + self.val1 + " not declared (interpreting as 0)") return 0 self.val1 = map[self.val1] return self.val1 # Tools def is_int (s): try: int(s) return True except ValueError: return False def has_operator (s, operators): for ops in operators: for op in ops: if op in s: return True return False def parse (s, verbose=True): if len(s) == 0: if verbose: print("Empty value found: interpreting as '0'") s = "0" value = "" disabled = 0 operators = [[ '+', '-' ], [ '*', '/' ]] s = s.replace(' ', '') if not has_operator(s, operators) and s[0] == "[" and s[-1] == "]": return Value(s[1:-1], verbose=verbose) if s[0] == "(" and s[-1] == ")": s = s[1:-1] if is_int(s): return Value(int(s), verbose=verbose) # Pass in steps, making the less important operators go first for ops in operators: for i in range(len(s) - 1, -1, -1): c = s[i] if c == "(": disabled += 1 elif c == ")": disabled -= 1 if disabled == 0: if c in ops: # Done, formulize return Formula(parse(s[:i]), c, parse(s[i + 1:]), verbose=verbose) else: value += c if __name__ == "__main__": definitions = {} while True: print("Definitions:") for var in definitions: print(" " + var + " = " + str(definitions[var])) print("Use '[x]' to use x") print("------------------") print("To declare a variable, type (e.g.): '\\def: x = 5'") print("To exit, type '\\exit'") print("Otherwise, enter the string that is to be calculated:") s = input() if s[:5] == "\\def:": s.replace(' ', '') s = s[5:] # split on the = splitted = s.split("=") if is_int(splitted[1]): splitted[1] = int(splitted[1]) definitions[splitted[0]] = splitted[1] elif s[:5] == "\\exit": break else: form = parse(s) print("Formula interpreted as: " + str(form)) # Calculate print("Result: " + str(form.calc(definitions))) print('\n')
a1d66280290fbee989fe96c074fb48e2d5cd2a8c
addie293/Conveyor-Belt-and-Waste-Management-System
/conveying_workshop/internal_process/FinalVersion_InternalProcess_conveyingWrkshp.py
5,281
4.03125
4
import random num=random.randint(0,1) initiate_the_process=input("please type in START to initialise:") case_sensitive_input=initiate_the_process.lower() while case_sensitive_input!='start': try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: initiate_the_process=input("please type in START to initialise:") case_sensitive_input=initiate_the_process.lower() else: print("goodbye") break if case_sensitive_input=='start': print("checking the availability of green jack") while num==0: print("no jack available") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("checking the availability of green jack") num=1 else: print("goodbye") if num==1: print("jack status is okay") print("now checking power button status") while num==0: print("power button is off, right now") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("now checking power button status") else: print("goodbye") break if num==1: print("the power button is ON") print("checking the tray status now") while num==0: print("no pot stock available right now") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("checking the tray status now") else: print("goodbye") break if num==1: print("pots are available, please choose the pot type") pot_size=int(input("please choose 0 for small pots and 1 for large pots:")) if pot_size==0: pot_number=int(input("enter the number of small pots required:")) else: pot_number=int(input("enter the number of large pots required:")) speed=int(input("please set the speed of the conveyer between 1 and 10:")) if speed in range(1,11): print("starting belt") print("starting arm") print("checking error") print("checking air fault status") print("air fault doesn't exist, all well") print("checking axis controller fault") while num==0: print("fault exists in axis controller, stopping now, cannot proceed forward") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("checking axis controller fault") else: print("goodbye") break if num==1: print("no fault found in axis controller") print("checking critical conveyer motor fault") while num==0: print("fault exists in critical conveyer motor fault,stopping now") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("checking critical conveyer motor fault") else: print("goodbye") break if num==1: print("no fault found in critical conveyer motor") print("checking critical fault emergency stop") while num==0: print("fault exists in critical fault emergency stop, stopping now, cannot proceed forward") try_again=int(input("enter 0 to skip and 1 to try again:")) if try_again==1: print("checking critical conveyer motor fault") else: print("goodbye") break if num==1: print("no fault found in critical fault emergency") print("everything is fine, no errors found") print("initiating grab arm and sending") print(pot_number,"is required") pot_number=pot_number+1 for i in range(1,pot_number): print(i,"has arrived at the end of conveyer belt") print("end of arm and belt") print("checking information from filling, if it's finished or not") print("status:filling is completed") else: print("invalid speed range has been selected")
54e43c2a7f344fa41abca56c2945ff2a6d665f49
YarikHumanities/Studies-Python
/Лабораторная работа 1 Py/Лабораторна_робота_1_Py.py
700
4.3125
4
from math import sqrt a=float(input("Значення першого катета: ")) #Ввод значение первого катета c=float(input("Значення гіпотенузи: ")) #Ввод значения гипотенузы b=(c**2-a**2)**0.5 #Формула второго катета if a>0 and c>0: print("Значення другого катета:", b) elif a<=0: print("Значення першого катета недопустиме ") elif c<=0: print("Значення гіпотенузи недопустиме") input() #Комадна для того что бы консоль не закрывалась после обработки
783cee3437b840ea1b4bd4450ed0562b756c1309
RohunNanda/DPCSYear11-PythonRN
/FindGCF.py
244
3.5
4
def findGCF (num, den): if num > den: low = den else: low = num for i in range(1, low+1): if((num%i == 0) and (den%i==0)): gcf = i return gcf num1 = 6 den1 = 18 print("The GCF of", num1, "and", den1, "is", findGCF(num1, den1))
d6297b2f8b2cca972d794551f3135eceaee9bdee
seattlechem/codewars
/7kyu/python/simple-rotated-palindromes/simple_rotated_palindrome.py
636
3.828125
4
"""Simple rotated palindrome solution.""" def solve(st): """Return True if a string is palindrome after rotating to left.""" def is_palindrome(st): return str(st) == str(st)[::-1] if is_palindrome(st) is True: return True st_list = list(str(st)) for i in range(0, len(st_list)): last = st_list.pop() st_list.insert(0, last) st = ''.join(st_list) if is_palindrome(st) is True: return True return False def best_solve(s): """Best practice solution from codewars.""" return any(s[i+1:] + s[:i+1] == s[i::-1] + s[:i:-1] for i in range(len(s)))
76037de4b418647483a4084a332441056ce2497d
IngridDilaise/programacao-orientada-a-objetos
/listas/lista-de-exercicio-03/questao15.py
436
4.09375
4
lado1 = float(input("Lado 1: ")) lado2 = float(input("Lado 2: ")) lado3 = float(input("Lado 3: ")) if lado1 + lado2 > lado3 or lado1 + lado3 > lado2 or lado2 + lado3 > lado1: print("É UM TRINGULO") if lado1 == lado2 and lado1 == lado3: print("Equilatero") elif lado1 == lado2 or lado2 == lado3 or lado3 == lado1: print("Isóceles") else: print("Escaleno") else: print("Não é um TRINGULO")
677400ae62113c2b8a00a497f6719c869544aa0d
mrwm/python-graphy
/graphs.py
13,054
3.84375
4
#!/usr/bin/env python3 #coding:utf-8 # graphs.py # Author: William Chung # Last Updated: # Purpose: Creates line or bar graph(s) or donut graphs with the given data # points given within a CSV file. # Program Uses: ./graphs.py # Notes: # - Requires svgwrite python module # - Requires a scecifically formatted csv file. # import svgwrite import math # for the trig functions import os # for file checking # breaking `with` using `with` # https://stackoverflow.com/a/23665658 class fragile(object): class Break(Exception): """Break out of the with statement""" def __init__(self, value): self.value = value def __enter__(self): return self.value.__enter__() def __exit__(self, etype, value, traceback): error = self.value.__exit__(etype, value, traceback) if etype == self.Break: return True return error def header_count(file_name): """ returns the number of headers in a file """ count = 0 with fragile(open(file_name, "r")) as file_input: for line in file_input: c_line_content = line.rstrip("\n").split(",") # Check if this is the start of a set of data using config information if (c_line_content[1] == "r") or (c_line_content[1] == "c"): count += 1 # subtract from one because we don't want to go past the last header count -= 1 return count def dict_to_list(dictionary_in): """ Converts the given dictionary to two separate lists """ item_list = [] for key, value in dictionary_in.items(): if type(value) is not list: item_list.append(value) else: item_list.append(value[0]) return item_list def conf_graph(line_buffer): """ Parses the given csv file and returns the configuration and colors. Will skip to whatever line number given, excluding the initial line. """ config = {} height_dictionary = {} color_dictionary = {} # Open the csv file with fragile(open(csv_file, "r")) as csv_input: csv_input.readline() # skip the first line # skip through the lines that have already been read. if line_buffer != 0: for num in range(0, line_buffer): csv_input.readline() # read through the line contents c_line_content = "" line_count = 0 # keep track of the number of lines read for csv_line in csv_input: c_line_content = csv_line.rstrip("\n").split(",") # Check if this is the start of a set of data using config information if c_line_content[1] == "r" and line_count == 0: config = { "filename" : c_line_content[0], "draw_mode" : c_line_content[1].lower(), "rect_width" : float(c_line_content[2]), "v_offset" : float(c_line_content[3]), "st_width" : float(c_line_content[4]), "dot_radius" : float(c_line_content[5]), "show_rect" : c_line_content[6].lower(), "show_line" : c_line_content[7].lower(), } # Check if the config is for circles elif c_line_content[1] == "c" and line_count == 0: config = { "filename" : c_line_content[0], "draw_mode" : c_line_content[1].lower(), "line_stroke_width" : c_line_content[2], "make_donut" : c_line_content[6].lower(), } # Add the rest of the data below the config line (r) elif (c_line_content[1] != "r" and c_line_content[1] != "c") and \ line_count != 0: # Set the color of the bars c_name = "color_" + str(line_count - 1) color_dictionary[c_name] = c_line_content[0] # Then set the bar heights h_name = "height_list_" + str(line_count - 1) h_list = c_line_content[1:] # Remove blanks while("" in h_list): h_list.remove("") # Convert the strings to numbers for h_index in range(0, len(h_list)): h_list[h_index] = float(h_list[h_index]) height_dictionary[h_name] = h_list # Exit the loop if we see another data configuration if (c_line_content[1] == "r" and line_count != 0) or \ (c_line_content[1] == "c" and line_count != 0): # Break out of the with loop once a dataset is collected raise fragile.Break line_count += 1 line_buffer = line_count return [line_buffer, config, height_dictionary, color_dictionary] ####################################### ####################################### ### ### RECTANGLE ### ####################################### ####################################### def draw_rect_graph(config, height_dictionary, color_dictionary): """ Draws the rectangle graph with the given hight and color values """ if config["draw_mode"] != "r": # toss the data to make a round graph draw_round_graph(config, height_dictionary, color_dictionary) return dwg = svgwrite.Drawing(config["filename"] + ".svg", profile="full") v_offset_origin = config["v_offset"] if config["show_rect"] == "true": # For making the bar graphs for group_index in range(1, len(height_dictionary)): x_index = 0 for list_index in range(1, len(height_dictionary["height_list_"+str(group_index)])): # draw the boxes r_size = height_dictionary["height_list_"+str(group_index)][list_index] dwg.add(dwg.rect((x_index, -r_size + v_offset_origin), (config["rect_width"], r_size), fill=color_dictionary["color_"+str(group_index)]) ) x_index += config["rect_width"] v_offset_origin += config["v_offset"] if config["show_line"] == "true": # For connecting the dots together config["v_offset"] = v_offset_origin for group_index in range(0, len(height_dictionary)): line_points = "M" x_index = 0 l_max = len(height_dictionary["height_list_"+str(group_index)]) for list_index in range(0, l_max): # draw the boxes r_size = height_dictionary["height_list_"+str(group_index)][list_index] if list_index < l_max-1: line_points = line_points + str(x_index) + "," + str(-r_size + v_offset_origin) + ", " else: line_points = line_points + str(x_index) + "," + str(-r_size + v_offset_origin) x_index += config["rect_width"] # draw a cubic-bezier-curve path dwg.add(dwg.path( d=line_points, stroke=color_dictionary["color_"+str(group_index)], fill="none", stroke_width=config["st_width"]) ) v_offset_origin += config["v_offset"] # For making the dots at the corner of each rectangle v_offset_origin = config["v_offset"] for group_index in range(0, len(height_dictionary)): x_index = 0 for list_index in range(0, len(height_dictionary["height_list_"+str(group_index)])): # draw the boxes r_size = height_dictionary["height_list_"+str(group_index)][list_index] dwg.add(dwg.circle(center=(x_index, -r_size + v_offset_origin), r=config["dot_radius"], fill=color_dictionary["color_"+str(group_index)]) ) x_index += config["rect_width"] v_offset_origin += config["v_offset"] # output our svg image as raw xml #print(dwg.tostring()) # write svg file to disk dwg.save() print("Exported file:", config["filename"] + ".svg") ####################################### ####################################### ### ### CIRCLE ### ####################################### ####################################### def addArc(dwg, current_group, p0, p1, radius, f_color, line_stroke_width): """ Adds an arc that bulges to the right as it moves from p0 to p1 """ args = {'x0':p0[0], 'y0':p0[1], 'xradius':radius, 'yradius':radius, 'ellipseRotation':0, #has no effect for circles 'x1':(p1[0]-p0[0]), 'y1':(p1[1]-p0[1])} current_group.add(dwg.path(d="M %(x0)f,%(y0)f a %(xradius)f,%(yradius)f %(ellipseRotation)f 0,0 %(x1)f,%(y1)f M0,0"%args, fill='none', stroke=f_color, stroke_width=line_stroke_width )) def anglept(angle=0): """Finds the location of a point on the circle. This assumes the center is at 0,0""" # convert degree to radian, then back to degree # reason: python trig functions use radians, but we want degrees x_point = math.degrees(math.cos(math.radians(angle))) y_point = math.degrees(math.sin(math.radians(angle))) # Offset number taken from the calculation for circle_size center_offset = 57.29577951308232 * 1.5 point=[x_point + center_offset, y_point + center_offset] return point def num_to_degree(index=0, list_given=None): """ Calculates the degrees of 360° from the total of the given list Note: Degree is cumulative, and if the degree is over 180°, the function will split the degree into two parts (180° + the remainder) Eg: index=1 will have the degree of 360° of index=0 + index=1 """ if list_given == None: print("num_to_percent wasn't given a list") exit(1) total = 0 divisor = 0 for num in range(0,len(list_given)): total += list_given[num] # add all the list numbers if num <= index: divisor += list_given[num] # get the sum up to the index given # Check if the current number is over 50% isOverHalf = False numerator = list_given[index] if round((numerator / total)*100) > 50: isOverHalf = True return [isOverHalf, round((divisor / total)*360)] def draw_round_graph(config, height_dictionary, color_dictionary): """ Draws the donut or pie graph with the given hight and color values """ if config["draw_mode"] != "c": # toss the data to make a round graph draw_round_graph(config, height_dictionary, color_dictionary) return line_stroke_w = config["line_stroke_width"] name="circle" # we need a name for the graph, tho it doesn't matter what it is dwg = svgwrite.Drawing(filename=config["filename"] + ".svg", size=(175,175)) current_group = dwg.add(dwg.g(id=name, stroke='red', stroke_width=3, fill='red', fill_opacity=1 )) # This is kinda arbitrary, but we want a constant radius, so here it is. circle_size = math.degrees(math.sin(math.radians(90))) #print(circle_size) # Make a solid circle if we don't want a donut if config["make_donut"] != "true": line_stroke_w = circle_size*2 graph_numbers = dict_to_list(height_dictionary) graph_colors = dict_to_list(color_dictionary) last_angle_used = 0 # Look thru all the numbers in the list and graph them out! for index in range(0, len(graph_numbers)): split = 1 # Set the slice color fill_color = graph_colors[index] # Check if we need to split the slice to 2 pieces (if slice is over 180°) if num_to_degree(index, graph_numbers)[0]: split = 2 # Create the slice points if index == 0 and index != len(graph_numbers): # start the first slice at 0 start_angle = last_angle_used end_angle = num_to_degree(index, graph_numbers)[1] / split #print("a first slice", start_angle, end_angle) elif index != len(graph_numbers): # Start at the last slice calculated start_angle = last_angle_used end_angle = num_to_degree(index, graph_numbers)[1] / split #print("a followed slice", start_angle, end_angle) else: start_angle = 0 end_angle = 0 print("a Something went wrong. Was there a bad number?") # if we need to split the slice, then draw the first half, # then recalculate the points for the second half slice. if split == 2: # Draw the split slice addArc(dwg, current_group, p0=anglept(end_angle), p1=anglept(start_angle), radius=circle_size, f_color=fill_color, line_stroke_width=line_stroke_w) # Then update to the second half of the slice start_angle = end_angle end_angle = num_to_degree(index, graph_numbers)[1] # Print the % of what the slice takes up. percentage = round(num_to_degree(index, graph_numbers)[1]/3.6) if index != 0: percentage = percentage - round(num_to_degree(index-1, graph_numbers)[1]/3.6) print(index+1, ':', percentage, '%') # Draw the slice addArc(dwg, current_group, p0=anglept(end_angle), p1=anglept(start_angle), radius=circle_size, f_color=fill_color, line_stroke_width=line_stroke_w) last_angle_used = end_angle dwg.save() print("Exported file:", config["filename"] + ".svg") ################################################################################ ################################################################################ print("Please input CSV file name (including the .cvs extention)") print("Default: sample_data.csv") csv_file = input("File name: ") if not os.path.isfile(csv_file): csv_file = "sample_data.csv" print("===") line_buffer = 0 capture = conf_graph(line_buffer) line_buffer += capture[0] draw_rect_graph(capture[1], capture[2], capture[3]) for i in range(0, header_count(csv_file)): capture = conf_graph(line_buffer) line_buffer += capture[0] draw_rect_graph(capture[1], capture[2], capture[3])
583adc2f9279e07cb5f32a57e99465901255c8a4
ShreyashSalian/Python-Multiple-Inheritance
/Inheritance.py
2,033
3.84375
4
class Student: StudentCount = 0 def __init__(self,StudentId = 0,StudentName = "",StudentPhone =""): self.StudentId = StudentId self.StudentName = StudentName self.StudentPhone = StudentPhone Student.StudentCount += 1 def showCount(self): print("Total instances of Student is:",Student.StudentCount) def showData(self): print("Student Id is",self.StudentId) print("Student Name is", self.StudentName) print("Student Phone is", self.StudentPhone) def setData(self,StudentId = 0,StudentName = "",StudentPhone =""): self.StudentId = StudentId self.StudentName = StudentName self.StudentPhone = StudentPhone #Student.StudentCount += 1 class Science: def __init__(self,Physics = 0.0,Chemistry=0.0): self.Physics = Physics self.Chemistry = Chemistry def showData(self): print("Physics Marks is : ",self.Physics) print("Chemistry Marks is :",self.Chemistry) def setData(self,Physics = 0.0,Chemistry=0.0): self.Physics = Physics self.Chemistry = Chemistry class Results(Student,Science): def __init__(self,StudentId = 0,StudentName = "",StudentPhone = "",Physcis = 0.0,Chemistry = 0.0): Student.__init__(self,StudentId,StudentName,StudentPhone) Science.__init__(self,Physcis,Chemistry) self.total = Physcis + Chemistry self.percentage = self.total/200 * 100 def setData(self,StudentId = 0,StudentName = "",StudentPhone ="",Physics = 0.0,Chemistry = 0.0): Student.__init__(self, StudentId, StudentName, StudentPhone) Science.__init__(self, Physics, Chemistry) self.total = Physics + Chemistry self.percentage = self.total / 200 * 100 def showData(self): Student.showData(self) Science.showData(self) print("Total Marks :",self.total) print("Percentage :",self.percentage) a = Results(1,"Shreyash","344534334",89.9,90.6) a.showData() a.showCount()
ed25afb2dfc205aae59607c3fb66fc865d452bfa
chuzcjoe/Leetcode
/404. Sum of Left Leaves.py
1,193
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: """ 1.BFS if not root: return 0 leaves = [] level = [root] while level: for node in level: if node.left and not node.left.left and not node.left.right: leaves.append(node.left.val) level = [child for node in level for child in [node.left, node.right] if child] return sum(leaves) """ """ 2.DFS """ def dfs(node): if not node: return 0 if node.left and not node.left.left and not node.left.right: return node.left.val + dfs(node.right) return dfs(node.left) + dfs(node.right) return dfs(root)
e42f8619dd99e67ab76c28c088e5efb31d9584cc
liuw/project-euler
/p41.py
1,318
3.78125
4
#!/usr/bin/python # encoding: utf-8 import time import itertools # Fast prime generator from python cookbook def erat2(): D = {} yield 2 for q in itertools.islice(itertools.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = p + q while x in D or not (x&1): x += p D[x] = p def get_primes_erat(n): return list(itertools.takewhile(lambda p: p < n, erat2())) st1 = time.time() print "Generating primes" primes = get_primes_erat(10000000) st2 = time.time() print "done", st2-st1 arr = [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 ] # judging from the array above, the target number cannot be consisted # of 8 and 9 digits, as they are always divisible by 3 def is_pandigital(n): s = str(n) s1 = set(s) s2 = set(map(int, s1)) if '0' in s1: return False if len(s) != len(s1): return False if sum(s2) != arr[len(s1)]: return False return True def solve(): global primes for i in xrange(len(primes)-1, -1, -1): if is_pandigital(primes[i]): print primes[i] break def main(): solve() start_time = time.time() main() end_time = time.time() print "Program finished in", end_time - start_time, "second(s)"
a5933071606837f7875e7f428c83f761f4887c44
george-zip/ap_exam_to_corpus
/text_handling.py
3,375
3.8125
4
""" Library for tokenizing and parsing exam text Available functions: - extract_all_sections: divide text into consecutive sections - tokenize_text: tokenize text into sentences, words and parts-of-speech tags - extract_section_reg_exp: extract sections identified by a regular expression - extract_named_sections: extract all named or identified sections - fill_in_all_sections: fill in sections not identified by regular expression """ import re from collections import namedtuple CorpusSection = namedtuple('CorpusSection', ('type', 'start_position', 'end_position', 'contents')) def tokenize_text(text, tokenizer): """Tokenize text into sentences, words and parts-of-speech tags Args: text: text to be tokenized tokenizer: tokenizer that implements sent_tokenize, word_tokenize and pos_tag Returns: (sentences, words, pos_tags) pos_tags are in format [[(word1, tag1),(word2, tag2), ...]] """ sentences = tokenizer.sent_tokenize(text) words = [tokenizer.word_tokenize(s) for s in sentences] pos_tags = [tokenizer.pos_tag(w) for w in words] return sentences, words, pos_tags def extract_section_reg_exp(text, reg_exp, section_name, tokenizer): """Extract sections of text found by regular expression and identified by section name""" matches = re.finditer(reg_exp, text, flags=re.MULTILINE) for match in matches: (start, end) = match.span() _, _, words_with_pos_tags = tokenize_text(text[start:end], tokenizer) yield CorpusSection(section_name, start, end, words_with_pos_tags) def extract_named_sections(text, tokenizer): """Extract all named sections of text""" section_regular_expressions = { "directions": "^Directions: [\w\d\s;.,:-]+\n", "question_top_level": "^\d+\..*\n", "question_sub_level": "^[abc]\).+[\s\n\r]*?.*\.", "quotation": '^“[\w\d\s’.,-]*”' } for name in section_regular_expressions: for section in extract_section_reg_exp(text, section_regular_expressions[name], name, tokenizer): yield section def fill_in_all_sections(named_sections, text, tokenizer): """Fill in gaps in sections that are not named""" current_position = 0 for section in named_sections: if section.start_position > current_position: _, words, words_with_pos_tags = tokenize_text(text[current_position:section.start_position - 1], tokenizer) if len(words): yield CorpusSection("non_pedagogical", current_position, section.start_position - 1, words_with_pos_tags) yield section current_position = section.end_position + 1 if current_position < len(text): _, words, words_with_pos_tags = tokenize_text \ (text[current_position:len(text) - 1], tokenizer) if len(words): yield CorpusSection("non_pedagogical", current_position, len(text) - 1, words_with_pos_tags) def extract_all_sections(text, tokenizer): """Extract all sections of text Args: text: text to be tokenized tokenizer: tokenizer that implements sent_tokenize, word_tokenize and pos_tag Returns: list(CorpusSection) """ named_sections = extract_named_sections(text, tokenizer) return fill_in_all_sections(sorted(named_sections, key=lambda t: t[1]), text, tokenizer)
8c787b221b005f2f997f7d927a008d3ff9fa1514
ayeshaghoshal/learn-python-the-hard-way
/ex19.py
2,520
4.40625
4
# -*- coding: utf-8 -*- print "EXERCISE 19 - Functions and Variables" # defining the function that commands the following strings to be printed out # there are 2 parameters that have to be defined in brackets def cheese_and_crackers(cheese_count, boxes_of_crackers): # use of the parameters is the same method as writing string and designating values to it print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man, that's enough for a party!" print "Get a blanket.\n" # a new method of displaying the function directly by designating it values print "We can just give the function numbers directly:" # the following function will promth the command to print the stated 4 sentences above cheese_and_crackers(20,30) # another method of printing the same function print "OR, we can use variables from our script:" # designate a value to new variables amt_of_cheese = 10 amt_of_crackers = 30 # the new variables will replace the old parameters to state the defined values right above cheese_and_crackers(amt_of_cheese,amt_of_crackers) # use just numbers to define the two parameters inside the defined function print "We can even do math inside too:" cheese_and_crackers(20 + 25, 48 + 50) # Showcases the use of both variables and math to display the defined function # as long as there are only 2 paramenters defined within the brackets!!! print "And we can combine the two, variables and math:" cheese_and_crackers(amt_of_cheese + 20, amt_of_crackers + 450) #STUDY DRILLS - NEW FUNCTION! def animals_on_farm(cows, chickens, sheep): print "Can you spot %d cows?" % cows print "I bet you won't be able to identify %d red chickens!" % chickens print "Did you sheer all %d sheep this season?" % sheep print "I hope so! otherwise they will all look like cotton balls! HAHAHA\n" animals_on_farm(10, 4, 23) animals_on_farm(3 + 4, 51 + 1, 2 + 7) a = 20 b = 14 c = 24 # can replace the name of parameters inside the function () animals_on_farm(a, b, c) animals_on_farm(a + 2, b*2, c - 10) print "We can assign the function to a variable and simply call it by its new variable name" poo = animals_on_farm poo(2, 4, 8) print "We can pass a function as arguments" print "Now ask the user for the number of cows, chickens and sheep! - brackets within brackets" animals_on_farm(int(raw_input("How many cows?")), int(raw_input("How many chickens?")), int(raw_input("How many sheep?)")))
25539de8a8453728081d55fd44d77232528652b0
zeroam/TIL
/codeit/oop/open_closed_principle/keyboard_manager.py
1,398
3.90625
4
from abc import ABC, abstractmethod class Keyboard(ABC): @abstractmethod def save_input(self, input): pass @abstractmethod def send_input(self): pass class SamsungKeyboard(Keyboard): def __init__(self): self.user_input = "" def save_input(self, input): self.user_input = input def send_input(self): return self.user_input class AppleKeyboard(Keyboard): def __init__(self): self.keyboard_input = "" def save_input(self, input): self.keyboard_input = input def send_input(self): return self.keyboard_input class KeyboardManager: def __init__(self): self.keyboard = None def connect_to_keyboard(self, keyboard): self.keyboard = keyboard def get_keyboard_input(self): if isinstance(self.keyboard, Keyboard): return self.keyboard.send_input() return None if __name__ == '__main__': keyboard_manager = KeyboardManager() apple_keyboard = AppleKeyboard() samsung_keyboard = SamsungKeyboard() keyboard_manager.connect_to_keyboard(apple_keyboard) apple_keyboard.save_input("안녕하세요") print(keyboard_manager.get_keyboard_input()) keyboard_manager.connect_to_keyboard(samsung_keyboard) samsung_keyboard.save_input("안녕하세요") print(keyboard_manager.get_keyboard_input())
d80412a21784432dd13869d42cc4e0f39341878c
AmigaTi/Python3Learning
/builtins/bins-modules/bins-collections.py
4,491
3.953125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import namedtuple, deque, defaultdict from collections import OrderedDict, Counter # namedtuple # namedtuple是一个函数,用来创建一个自定义的tuple对象, # 规定了tuple元素的个数,并可用属性而不是索引来引用tuple的某个元素 # 用namedtuple可以很方便地定义一种数据类型, # 它具备tuple的不变性,又可以根据属性来引用 Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p) # Point(x=1, y=2) print(p.x) # 1 print(p.y) # 2 print(isinstance(p, Point)) # True print(isinstance(p, tuple)) # True print('-----------------------------') # 用坐标和半径表示一个圆,也可以用namedtuple定义 # namedtuple('名称', [属性list]) # AttributeError: can't set attribute Circle = namedtuple('Circle', ['x', 'y', 'r']) c = Circle(3, 4, 5) print(c) # Circle(x=3, y=4, r=5) print('-----------------------------') # deque # 使用list存储数据时,按索引访问元素很快,但插入和删除元素就很慢, # 因为list是线性存储,数据量大的时候,插入和删除效率很低。 # deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈。 # deque除了实现list的append()和pop()外,还支持appendleft() # 和popleft(),这样就可以非常高效地往头部添加或删除元素。 q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') print(q) # deque(['y', 'a', 'b', 'c', 'x']) print(q[1]) # a print('-----------------------------') # defaultdict # 使用dict时,如果引用的Key不存在,就会抛出KeyError。 # 如果希望key不存在时,返回一个默认值,就可以用defaultdict # 注意默认值是调用函数返回的,而函数在创建defaultdict对象时传入 # 除了在Key不存在时返回默认值,defaultdict的其他行为 # 跟dict是完全一样的 dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' print(dd['key1']) # abc print(dd['key2']) # N/A print('-----------------------------') # OrderedDict # 使用dict时,Key是无序的。在对dict做迭代时,无法确定Key的顺序 # 如果要保持Key的顺序,可以用OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) print(d) # {'a': 1, 'c': 3, 'b': 2} od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)]) # OrderedDict的Key会按照插入的顺序排列,不是Key本身排序 od = OrderedDict() od['z'] = 1 od['y'] = 2 od['x'] = 3 print(list(od.keys())) # ['z', 'y', 'x'] print('-----------------------------') # OrderedDict可以实现一个FIFO(先进先出)的dict, # 当容量超出限制时,先删除最早添加的Key class LastUpdateOrderedDict(OrderedDict): def __init__(self, capacity): super(LastUpdateOrderedDict, self).__init__() self.capacity = capacity def __setitem__(self, key, value): # containsKey=1时表示key已存在,则执行修改操作 # containsKey=0时表示key不存在,则执行添加操作 containskey = 1 if key in self else 0 # ?? # 当已达最大容量,当新加key不存在时,会运行这段,先删除最先添加的 # 当key存在时,不会运行这段,会运行第2个if进行修改 if len(self) - containskey >= self.capacity: # popitem移除键值对并返回,last=true时按LIFO顺序返回 # last=false时按FIFO顺序返回 last = self.popitem(last=False) print('remove: ', last) if containskey: del self[key] print('set: ', (key, value)) else: print('add: ', (key, value)) OrderedDict.__setitem__(self, key, value) luod = LastUpdateOrderedDict(2) luod['first'] = 'Hello' luod['second'] = 'World' luod['third'] = 'Me' print(luod) print('-----------------------------') ''' add: ('first', 'Hello') add: ('second', 'World') remove: ('first', 'Hello') add: ('third', 'Me') LastUpdateOrderedDict([('second', 'World'), ('third', 'Me')]) ''' # Counter # Counter是一个简单的计数器 # Counter实际上也是dict的一个子类 c = Counter() for ch in 'programming': c[ch] += 1 # Counter({'g': 2, 'm': 2, 'r': 2, 'a': 1, 'i': 1, 'n': 1, 'p': 1, 'o': 1}) print(c) print('-----------------------------')
9e8622b11e3d4d40c1681d131bede9fb9c8faeb4
danhill600/mymatthespython
/ch7while_input/7_1rental_car.py
116
3.640625
4
car = input("What kind of car do you want, Man?") print("okay let me see if I can find you a " + car.title() +".")
f3712af51a8873b98f70ab612246d649228a001c
Shikhar21121999/ptython_files
/nth_last_node_of_ll.py
1,060
3.953125
4
class Node: def __init__(self, val): self.data = val self.next = None def print_linked_list(head): # a while loop to print the linked list curr = head while(curr): print(curr.data, end=" ") curr = curr.next print() def give_length(head): # utility function to calculate length or number of nodes in the linked list if head is None: return 0 curr = head length = 0 while(curr is not None): length += 1 curr = curr.next return length def create_ll(head, arr): curr = head for i in range(1, len(arr)): new_node = Node(arr[i]) curr.next = new_node curr = new_node return head # main function if __name__ == '__main__': test = int(input()) while test > 0: arr = list(map(int, input().split(' '))) n = int(input()) head = Node(arr[0]) fir_head = create_ll(head, arr) # print_linked_list(fir_head) p = nth_last_node(fir_head, n) print(p) test -= 1
ebd20ceb57ff713a5578690fa870cf802075ceb4
johnny980627/python200818
/0818/turtle04.py
164
3.6875
4
import turtle t = turtle.Turtle() t.shape("turtle") t.pu() s=20 for i in range(30): t.stamp() s=s+3 t.forward(s) t.right(24) turtle.done()
10cb871ce76f11bb9c01998affa4ddff0972f51a
umadevic/07.py
/07.py
83
3.6875
4
d=int(input()) def hello(a,d): for i in range(0,d): print(a) hello("Hello",d)
471f321340554835aa58025b3654d95ceb36df51
ROHROCK/practice
/cracking_the_coding_interview/trees_graphs/firstCommonAncestor.py
2,422
3.734375
4
from tree import BST from collections import deque class customNode: parentNode = None data = None left = None right = None def __init__(self,d,parent): self.parentNode = parent self.data = d def copyTree(root,customRoot): if(root == None): return None if(root.left != None): customRoot.left = customNode(root.left.data,customRoot) if(root.right != None): customRoot.right = customNode(root.right.data,customRoot) copyTree(root.left,customRoot.left) copyTree(root.right,customRoot.right) return customRoot # my approach to create a new tree with parent data def solution(root): newRoot = customNode(root.data,None) newTreeRoot = copyTree(root,newRoot) return newRoot def findNode(root,key): if(root == None): print('Tree is empty') return queue = deque([]) queue.append(root) while(len(queue) != 0): currentNode = queue.popleft() if(currentNode.data == key): return currentNode if(currentNode.left != None): queue.append(currentNode.left) if(currentNode.right != None): queue.append(currentNode.right) print("Key node not found !") # exit() return None def firstAncestor(target1 , target2): routeTarget1 = [] target1 = target1.parentNode while(target1 != None): routeTarget1.append(target1) target1 = target1.parentNode while(target2 != None): if(target2 in routeTarget1): return target2 target2 = target2.parentNode return None # considering both nodes contain in the tree def recursiveOptimalSolution(root,target1,target2): if(root == None): return root if(root.data == target1 or root.data == target2): return root leftPath = recursiveOptimalSolution(root.left,target1,target2) rightPath = recursiveOptimalSolution(root.right,target1,target2) if(leftPath == None): return rightPath if(rightPath == None): return leftPath return root if __name__ == '__main__': treeObj = BST() numberList = [10,5,20,19,25] for number in numberList: treeObj.addNode(treeObj.root,number) newTreeRoot = solution(treeObj.root) print('Special Tree') treeObj.inOrder(newTreeRoot) target1 = findNode(newTreeRoot,19) target2 = findNode(newTreeRoot,25) if(target1 == None): print("key 1 is not found") exit() if(target2 == None): print("Key 2 is not found") exit() ancestor = firstAncestor(target1,target2) # print("Ancestor: ",ancestor.data) answer = recursiveOptimalSolution(treeObj.root,1,25) print("Ancestor: ",answer.data)
ee21ee5d04cd8fe66e49547f2f1790dfbda0c188
Piper-A/CSCI-102-Week12
/Week12-utility.py
1,692
3.59375
4
# #Piper Arnold #CSCI 102- A #Week 12 def PrintOutput(text): print("OUTPUT", text) return def LoadFile(file_name): file = open(file_name, 'r') lines = file.readlines() contents = [] for line in lines: contents.append(line.strip()) return PrintOutput(contents) def UpdateString(str_one, str_two, index): list_one = [] for i in str_one: list_one.append(i) list_one[index] = str_two output = '' for j in list_one: output += j return PrintOutput(output) def FinalWordCount(list_thing, string): occur = 0 for i in list_thing: if i.find(string) > -1: occur += 1 return PrintOutput(occur) def ScoreFinder(list_names, list_scores, player): low_names = [] for i in list_names: low_names.append(i.lower()) player = player.lower() index = -1 for j in range(len(low_names)): if low_names[j] == player: index = j if index > -1: outputname = list_names[index] outputscore = list_scores[index] out = outputname + ' ' + "got a score of" + ' ' + str(outputscore) else: out = "player not found" return PrintOutput(out) def Union(list_one, list_two): union = list_one for i in list_two: if i not in union: union.append(i) return PrintOutput(union) def Intersection(list_one, list_two): inter = [] for i in list_one: if i in list_two: union.append(i) return PrintOutput(inter) def NotIn(list_one, list_two): not_list = [] for i in list_one: if i not in list_two: not_list.append(i) return PrintOutput(not_list)
cbb8315c197b893fca57b28424aa8d51123f7e17
iamkissg/leetcode
/leetcode/145.binary-tree-postorder-traversal.py
2,969
4.03125
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # def postorderTraversal(self, root: TreeNode) -> List[int]: # if not root: # return [] # return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] def postorderTraversal(self, root: TreeNode) -> List[int]: ''' 20191009 使用 stack 来进行树的 DFS ''' if not root: return [] result = [] visited = set() myque = [root] while myque: node = myque.pop() if not node.left and not node.right: result.append(node.val) visited.add(node) continue else: if node not in visited: visited.add(node) myque.append(node) if node.right: myque.append(node.right) if node.left: myque.append(node.left) else: result.append(node.val) return result # def postorderTraversal(self, root: TreeNode) -> List[int]: # if not root: # return [] # return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] # def postorderTraversal_iteratively(self, root: TreeNode) -> List[int]: # ''' # 20191009 # 48 ms 13.9 MB Python3 # 使用 stack 来进行树的 DFS # ''' # if not root: # return [] # res = [] # stack = [root] # visited = set() # while stack: # node = stack.pop() # right = node.right # left = node.left # # 叶节点 # if not (left or right): # res.append(node.val) # continue # # 中间节点, 第二次访问 # if node in visited: # res.append(node.val) # continue # # 非叶节点第一次被遍历到, 用于取出左右节点, 同时自己再次入栈 # if node not in visited: # visited.add(node) # stack.append(node) # if right: # stack.append(right) # if left: # stack.append(left) # return res if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) sol = Solution() print(sol.postorderTraversal(root)) print(sol.postorderTraversal(root))
e264d778eaf7df150048c7655789754c852febd9
rahulptel/os-lab
/os_lab_6_121040.py
2,343
3.859375
4
#import necessary libraray files import time from threading import * import threading from random import * ## To implement monitor locks are used to achieve synchronization. ## Reference: http://stackoverflow.com/questions/8127648/how-to-synchronize-threads-in-python ## http://effbot.org/zone/thread-synchronization.htm ## Initialize the necessary locks for synchronization ## Check if buffer full or not fullL = threading.Lock() ## Check if buffer empty or not emptyL = threading.Lock() ## Constrain producer to producer producerL = threading.Lock() ## Constarin consumer to consume consumerL = threading.Lock() ## Buffer initialization buf=[] def producer(): global buf time.sleep(randint(0,50)) ## if queue is full it acquires a lock over thread which prevents producer to produce more items until customer bus something if len(buf) == 10: print "\n Buffer (size 10) is full. Producer gets blocked" fullL.acquire() producerL.acquire() fullL.acquire() buf.append(randint(0,100)) fullL.release() print "\n Producer produced "+str(buf[-1]) ## Check everytime that if the empty was acquired due to no items in the buffer, then it must be released as the producer has appended an item. if emptyL.locked(): emptyL.release() producerL.release() def consumer(): global buf time.sleep(randint(0,50)) consumerL.acquire() ## If queue is empty it acquires a lock over thread which prevents customer to buy more items until the producer produces more if len(buf) < 1: print "\n Buffer (size 10) is empty. Consumer gets blocked" emptyL.acquire() emptyL.acquire() print "\n Consumer consumed "+str(buf[-1]) del buf[-1] if emptyL.locked(): emptyL.release() ## Check everytime that if the full lock was acquired as due to buffer full,then it must be released as the consumer has consumed an item. if fullL.locked(): fullL.release() consumerL.release() print "Threads are getting created" # Create 20 producer threads for i in xrange(20): Thread(target=producer).start(); # Create 5 consumer threads for j in xrange(5): Thread(target=consumer).start(); print "Threads are running"
12323eee5c3ece368cf8ef568241ca8d633c4de6
AdamAtkins-Public/current
/Project_Euler/python/p014.py
1,156
4.28125
4
 import os ''' The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. ''' #return count of terms for starting number n def collatz_chain_length(n): term_count = int(1) while n != 1: if n & 1 == 0: n = int(n/2) else: n = int(3*n + 1) term_count = term_count + 1 return term_count if __name__ == '__main__': max = int(0) count = int(0) max_start = int(1) for n in range(1,1000000): count = collatz_chain_length(n) if count > max: max = count max_start = n print(max_start)
0a227b1ddde129e2d423683d33093c482bbd41ce
garrodbr/NOTsportsBetting
/SkeletonExcel_01.py
4,507
3.53125
4
# ------ # Goals # - Scrape website to find games # - Populate excel sheet with games # - Populate excel sheet with formulas # - This is purely to develop the skeleton document, not to update the scores # ------- # Get all bowl games # Scrape URL for bowl games # Get bowl game name, team, and date # INPUT: URL # OUTPUT: Bowl Name, Date, Home Team, Away Team # output could be a class, list of lists, dict, etc. # should sort by date # List of lists would be very simple, class would be inclusive import requests from bs4 import BeautifulSoup # ------------------------------------------------------------------------------------------------------------------- # Basic download of page # ------------------------------------------------------------------------------------------------------------------- url = "https://www.ncaa.com/scoreboard/football/fbs/2019/14" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # ------------------------------------------------------------------------------------------------------------------- # Get all containers, they contain the date # ------------------------------------------------------------------------------------------------------------------- container = soup.find_all(class_="gamePod_content-division") # date = container[0].find('h6') # ------------------------------------------------------------------------------------------------------------------- # Get all the games # ------------------------------------------------------------------------------------------------------------------- gamesList = [] for pod in container: date = pod.find('h6').get_text() teamNames = [team.get_text() for team in pod.find_all(class_="gamePod-game-team-name")] # teamScores = [score.get_text() for score in pod.find_all(class_="gamePod-game-team-score")] for index in range(0,len(teamNames), 2): homeTeam = teamNames[index] awayTeam = teamNames[index + 1] gameIndex = [date, 'BOWL NAME' + str(index), homeTeam, awayTeam] gamesList.append(gameIndex) # ------------------------------------------------------------------------------------------------------------------- # Create the worksheet # ------------------------------------------------------------------------------------------------------------------- from openpyxl import Workbook from openpyxl.styles import PatternFill players = ["Brad", "Burton", "Chris", "Martin"] playerEntry = [] for user in players: playerEntry += [user + 'Home', user + 'Away', user + 'Score'] wb = Workbook() destFile = "sampleSkeleton.xlsx" # Change the Cover sheet name ws1 = wb.active ws1.title = "CoverPage" # Create a new sheet for the bowl games wb.create_sheet("BowlGames") wb.active = wb["BowlGames"] # Create the Header ws = wb.active appendHeader = ['DATE', 'BOWL NAME', 'HOME TEAM', 'AWAY TEAM'] + playerEntry + ['ACTUAL HOME', 'ACTUAL AWAY'] ws.append(appendHeader) # Fill in the games for game in gamesList: ws.append(game) # Fill in the formula # =IF(ISBLANK($Q2), , SUM(IF(OR(AND($Q2>$R2, E2>F2), AND($R2>$Q2, F2>E2)), 50, 0), E2-$Q2, F2-$R2)) sample for 4 users # Q = Home Team Actual # R = Away Team Actual # E = Home Team User # F = Away Team User # 2 = Row Number scoreFormula = "=IF(ISBLANK(${}{}), , SUM(IF(OR(AND(${}{}>${}{}, {}{}>{}{}), AND(${}{}>${}{}, {}{}>{}{})), 50, 0), " \ "50-ABS({}{}-${}{})-ABS({}{}-${}{})))" # order is Q, Q, R, E, F, R, Q, F, E, E, Q, F, R headerLength = 0 # This should get overwritten for rowi, rows in enumerate(ws.iter_rows()): if rowi == 0: headerLength = len(rows) continue # Skip the header rowi += 1 for celli, cell in enumerate(rows): if celli in [6, 9, 12, 15]: # still could update to be auto based on number of entries cell.fill = PatternFill(fgColor="deb137", fill_type = "solid") # Format color changeCell = cell cellQ = chr(64+headerLength-1) cellR = chr(64+headerLength) cellE = chr(64 + celli-1) cellF = chr(64 + celli) cellFormula = scoreFormula.format( cellQ, rowi, cellQ, rowi, cellR, rowi, cellE, rowi, cellF, rowi, cellR, rowi, cellQ, rowi, cellF, rowi, cellE, rowi, cellE, rowi, cellQ, rowi, cellF, rowi, cellR, rowi) # order is Q, Q, R, E, F, R, Q, F, E, E, Q, F, R changeCell.value = cellFormula wb.save(filename=destFile)
a715461368b30c5a40c61a2a26a83b91c9a82fe7
suneelyadava/Python_Practice
/Python_Basics/StringOpretion.py
192
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 2 12:50:31 2018 @author: syadava """ aString = "test Me" print(len(aString)) print(aString.index("M")) print((aString.count("e")))
1eafd60aae155fff855da9b700064b5e5f2ecbde
drfoland/cs1113
/npcs.py
3,016
3.75
4
import items class NPC: name = "Do not create raw NPCs!" description = "There is no description here because you should not create raw NPC objects!" goods = [] # Stuff an NPC is carrying. quantities = [] # Quantities of that stuff. first_encounter = True # Used to do something different on first encounter. def __str__(self): return self.name def check_text(self): if(self.first_encounter): text = self.first_time() return text else: return self.description def talk(self): # Add to this method if you want to be able to talk to your NPC. return "The %s doesn't seem to have anything to say." % self.name def first_time(self): # Used to have your NPC do something different the first time you see them. self.first_encounter = False return self.description def handle_input(self, verb, noun1, noun2, inventory): return [False, None, inventory] class OldMan(NPC): name = "Old Man" goods = [items.Dagger(), items.Red_Potion(value = 50), items.Crusty_Bread(value = 5)] quantities = [1, -1, 2] # Set quantity to -1 if you want it to be infinite. description = "An old man in a red robe is standing in the middle of the room." def talk(self): # Add to this method if you want to be able to talk to your NPC. print("The old man says: I can sell you an item or two, if you are interested:") for item in self.goods: if item.value > 0: if(self.quantities[self.goods.index(item)] > 0): quantity = "quantity = %d" % self.quantities[self.goods.index(item)] else: quantity = "quantity = unlimited" print("* " + item.name.title() + " (" + str(item.value) + " gold, " + quantity + ")") return "" def give(self, item, inventory): for good in self.goods: if(good == item): inventory.append(good) if(self.quantities[self.goods.index(good)] > 0): self.quantities[self.goods.index(good)] -= 1 for index in reversed(range(len(self.quantities))): # Get rid of items with zero quantity. if(self.quantities[index] == 0): self.quantities.pop(index) self.goods.pop(index) return inventory def first_time(self): # Used to have your NPC do something different the first time you see them. self.first_encounter = False text = self.description text += " As he holds out a dagger, he says: 'It is dangerous to go alone... take this.'" return text def handle_input(self, verb, noun1, noun2, inventory): if(noun1 == 'old man' or noun1 == 'man'): if(verb == 'check'): return [True, self.check_text(), inventory] elif(verb == 'talk'): text = self.talk() return [True, text, inventory] elif(verb == 'take'): for good in self.goods: if(good.name.lower() == noun1): if(good.value == 0): inventory = self.give(good, inventory) return [True, "The old man gave you the %s." % good.name, inventory] else: return [True, "'Hey, what are you trying to pull? If you want that, the cost is %d gold.'" % good.value, inventory] return [False, "", inventory]
1390a8debf61250cf52ede189d6bf71b19e2fc57
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/fllkea001/question1.py
1,488
4.125
4
#PRogram for a simple BBS #Keanon Fell #15 April 2014 #Creating empty strings outside the loop so it can be ovewritten each time the user inputs something different answer = "" message ="" while answer != 'X':#Once the user enters X then the program will execute #whatever code is in the body of the else and then break out of the program #Printing out the menu print("Welcome to UCT BBS") print("MENU") print("(E)nter a message\n(V)iew message\n(L)ist files\n(D)isplay file\ne(X)it") answer = input("Enter your selection:\n") answer = answer.upper()#Form of data validation #Checking for all instances of the users inputs if answer == 'E': message = input("Enter the message:\n") elif answer == 'V': print('The message is:',message) elif answer == 'L': if answer != "": print('The message is: No message yet') else: print('List of files: 42.txt, 1015.txt') elif answer == 'D': file = input("Enter the filename:\n") if file == '42.txt': print('The meaning of life is blah blah blah ...') elif file == '1015.txt': print('Computer Science class notes ... simplified') print('Do all work') print('Pass course') print('Be happy') else: print("File not found") elif answer == 'X': print('Goodbye!')
d4bae481c3c6561588ce4ccf97b69fe2665df0a7
kumar-prakash/workspace
/python/bootcamp/operators.py
149
3.875
4
def is_even_or_odd(arg) : if arg % 2 == 0: print(" is even") else: print( " is odd") is_even_or_odd(10) is_even_or_odd(11)
061c44835fdf78b35fa3c9394f71e2d963de46be
ethan8621/Training-Python-Public
/src/training_src/demo3.py
585
3.8125
4
# class Name(object): # def __init__(self, name): # self.name = name # def __len__(self): # return len(self.name) # def split(self): # return self.name.split() # def lower(self): # return self.name.lower() # def lastname(self): # return self.name.split()[-1] class Name(str): def lastname(self): return self.split()[-1] zhangsan = Name('Zhang San') print(len(zhangsan)) # 9 print(zhangsan.split()) # ['Zhang', 'San'] print(zhangsan.lower()) # 'zhang san' print(zhangsan.lastname()) # 'San' print(zhangsan)
09554045c3b9b86422bfb0d6f015565c62714ca3
Aasthaengg/IBMdataset
/Python_codes/p04019/s213376041.py
126
3.609375
4
S=input() sn = "N" in S se = "E" in S ss = "S" in S sw = "W" in S if (sn==ss) and (se==sw): print("Yes") else: print("No")
10081e3610e060edcedb6a85df8aef416aea9b2b
felipe-gdr/linear-algebra
/word_counter.py
831
4.1875
4
"""Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s words = s.split(' ') d = {} for w in words: if w in d: d[w] = d[w] + 1 else: d[w] = 1 # TODO: Sort the occurences in descending order (alphabetically in case of ties) result = [] [result.append(v) for v in sorted(d.items(), key=lambda kv: (-kv[1], kv[0]))] # TODO: Return the top n words as a list of tuples (<word>, <count>) return result[:n] def test_run(): """Test count_words() with some inputs.""" print (count_words("cat bat mat cat bat cat", 3)) print (count_words("betty bought a bit of butter but the butter was bitter", 3)) if __name__ == '__main__': test_run()
b8250982419c17e1e29c4fb0bfa6f03c69fbc990
jkapila/MVP_AI
/OutputAdaptor.py
753
3.5
4
""" Output Apadtor: This adaptor act as the interface between the prediction process's output and the activity you want to perform on that. As this is an independent adaptor, we can replicate the same for many multiple output methods. """ from __future__ import print_function, division, with_statement class OutputAdaptor(object): def __init__(self, output_method): print('Output Adaptor Invoked!') self.output_method = output_method self.prediction = None self.output = None def outputs(self): print('The Output is:', self.output) return self.output def adapat_y(self, predictions): self.prediction = predictions self.output = self.prediction
670d094b5262c9fe36a499d62e496225b5543f5e
marufmorshed1/Codeforces
/lab06 Q5.py
529
3.75
4
class Vehicle: def __init__(self): self.x = 0 self.y = 0 def print_position(self): print("(", self.x, ",", self.y, ")", sep="") def moveUp(self): self.y += 1 def moveDown(self): self.y -= 1 def moveRight(self): self.x += 1 def moveLeft(self): self.x -= 1 car = Vehicle() car.print_position() car.moveUp() car.print_position() car.moveLeft() car.print_position() car.moveDown() car.print_position() car.moveRight()
a87a876c78432bbb9fc611bb17113dbc9013381a
Cunarefa/AVADA
/Patterns/behaveral/Iterator/Iterator_list_dict.py
1,602
3.953125
4
from abc import ABC, abstractmethod class Collection(ABC): @abstractmethod def iterator(self): pass class ListCollection(Collection): def __init__(self, collection): self._collection = collection def iterator(self): return ListIterator(self._collection) class Iterator(ABC): def __init__(self, collection, position): self._collection = collection self._position = position @abstractmethod def current(self): pass @abstractmethod def next(self): pass @abstractmethod def has_next(self): pass def _raise_key_exception(self): raise self._error(f'Collection of class {self.__class__.__name__}' f' does not have key "{self._position}"') class ListIterator(Iterator): _error = IndexError def __init__(self, collection): super(ListIterator, self).__init__(collection, 0) def current(self): if self._position < len(self._collection): return self._collection[self._position] self._raise_key_exception() def next(self): if len(self._collection) >= self._position + 1: self._position += 1 return self._collection[self._position] self._raise_key_exception() def has_next(self): return len(self._collection) >= self._position + 1 if __name__ == '__main__': lis = ListCollection([1, 2, 3, 4, 5]) print('OUTPUT:') j = lis.iterator() print(j.current()) j.next() print(j.next()) print(j.current()) print(j.has_next())
95699e9032d558781d272d56f0304cab881e97f2
Adil-Anzarul/Pycharm-codes
/OOPS 2 Creating our first class in python T53.py
478
3.734375
4
class Employee: no_of_leaves=8 pass harry=Employee() rohan=Employee() harry.name="Harry" harry.salary=4587 harry.role="Instructor" rohan.name="Rohan" rohan.salary=2854 rohan.role="Student" print("1-> ",Employee.no_of_leaves) print("2-> ",rohan.__dict__) rohan.no_of_leaves=154 print("3-> ",rohan.__dict__) print("4-> ",Employee.no_of_leaves) print("5-> ",rohan.no_of_leaves) Employee.no_of_leaves=41 print(Employee.no_of_leaves) print("5'-> ",rohan.no_of_leaves)
c46b3caf23c847e1cc08d0f4d7e62e4d6a4c1905
almqv/cipher
/caesar.py
1,159
3.96875
4
#!/usr/bin/env python from lib.input import * from lib.vars import alphabet from lib.vars import listToString if( inputHasKeys(["-k", "-i", "-a"]) ): in_key = int(getValueOfKey("-k")) in_txt = getValueOfKey("-i") in_alphabet = getValueOfKey("-a") else: print("file.py -k {int KEY} -i {string TXT} -a {string ALPHABET_TYPE}") print("-k: The encryption/decryption key") print("-i: The text to be encrypted/decrypted") print("-a: The alphabet (SWE or ENG)") exit() alen = len(alphabet[in_alphabet]) txt_list = list(in_txt) decryp_list = [""] * len(in_txt) charindex = -1 for char in txt_list: # loop through all of the chars charindex = charindex + 1 index = alphabet[in_alphabet].index(char) print("Decrypting char-index: " + str(charindex) + " (" + char + ":" + str(index) + ")") index = index + in_key # shift the alphabet while( index > alen - 1 ): #cycle through the alphabet index = index - alen print(" Alphabet cycle, index: " + str(index)) charDe = alphabet[in_alphabet][index] decryp_list[charindex] = charDe print( "Output: " + listToString(decryp_list) )
f1ddd784618e1599f177d868672a59ae16e01d37
kurniacf/Basic_Python_ai
/Final-Project/final_project.py
2,670
3.578125
4
# Final Project # Send Email with Python ''' Source = Youtube = https://youtu.be/bXRYJEKjqIM , Web = https://www.freecodecamp.org/news/send-emails-using-code-4fcea9df63f/, https://community.esri.com/t5/python-questions/how-to-display-python-results-into-email-body/td-p/641235 ''' import getpass # Library input password *hidden string) import smtplib # library kirim email # Library kirim text dan subject from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # Library kirim attach file (document, image, pdf, dll) from email.mime.base import MIMEBase from email import encoders email_mailer = 'darkpotato171717@gmail.com' # Email pengirim print("Email Pengirim = " + email_mailer) # membuka file txt email yg dituju (sesuai lokasi folder) with open('E:\Programming\Python\AIBasicPython\Basic_Python_ai\Final-Project\Receiver_list.txt') as file_listEmail: # mengurutkan agar sejajar dan memasukkan ke variable tmp tmp = list(file_listEmail) print("Email Penerima: " + str(tmp)) ''' with open('E:\Programming\Python\AIBasicPython\Basic_Python_ai\Final-Project\Subject_email.txt') as file_subjectEmail: sub = list(file_subjectEmail) ''' subject = 'Subject Python Email' # Isi subject sesuai selera email_addressee = tmp # memindahkan nilai tmp #email_subject = sub # menginisiasi nilai From, To, dan Subject dalam email msg = MIMEMultipart() msg['From'] = email_mailer msg['To'] = ', '.join(tmp) msg['Subject'] = subject # Isi email body = 'Email ini dikirim dari python -_- :)' msg.attach(MIMEText(body, 'plain')) # attach text # Kirim attach file (example : Doraemon.jpg [image file]) namafile = 'Doraemon.jpg' # membuka file yg dikirim sesuai lokasi a = open('E:\Programming\Python\AIBasicPython\Basic_Python_ai\Final-Project\sem\Doraemon.jpg', 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((a).read()) # menampung data sementara ke base64 (penyimpanan sementara) encoders.encode_base64(part) # agar file bertuliskan namafile part.add_header('Content-Disposition', "attachment; filename= " + namafile) msg.attach(part) # attchfile ke base64 text = msg.as_string() # menginisiasi text sebagai string server = smtplib.SMTP('smtp.gmail.com', 587) # mengoneksi server gmail server.starttls() # memulai server gmail # input dgn getpass agar tidak diketahui password = getpass.getpass('Masukkan password email: ') # Server penjalanan email server.login(email_mailer, password) # login email server.sendmail(email_mailer, email_addressee, text) # kirim email server.quit() # tutup email print("Pengiriman Email Berhasil!!")
ef46d1180857971eca5d92f7dd70d57055ef241e
UrenaAlex/Urena_Story
/Basic Functions/second.py
188
4.375
4
x = input("Hello, enter a number, I will tell you if it is even or odd. ") if ( x % 2 == 1): print("You have an odd number!") elif ( x % 2 == 0): print("You have an even number!")
7c61e2a6c8bcc2ae01a4cf3223d28da298cf948e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2312/60829/292332.py
109
3.59375
4
n=int(input()) a=[3,5] b=[5,42] for i in range(len(a)): if n==a[i]: n=b[i] break print(n)