blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
f72a2973777f6e07a472d8d945c6181db55f0149
hsuanwen0114/sharon8811437
/HW3/binary_search_tree_06170226.py
2,729
3.6875
4
# coding: utf-8 # In[33]: class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None class Solution(object): def insert(self, root, val): if root == None: root = TreeNode(val) return root else: if val > root.val: if root.right == None: newnode = TreeNode(val) root.right = newnode else: self.insert(root.right, val) if val <= root.val: if root.left == None: newnode = TreeNode(val) root.left = newnode else: self.insert(root.left, val) return root def search(self, root, target): if target< root.val: if root.left!=None: return self.search(root.left, target) else: return None elif target> root.val: if root.right!=None: return self.search(root.right, target) else: return None elif target==root.val: return root#當節點等於目標時,回傳正確 def children_count(self, node): a = 0 if node.left: a += 1 if node.right: a += 1 return a def delete(self, root, target):#delete有三種可能 x = self.children_count(root) if root==None: return root else: if target<root.val: root.left=self.delete(root.left,target) elif target>root.val: root.right=self.delete(root.right,target) else: if x == 0: root = None elif x == 1: if root.left != None: root = root.left root.left = None if root.right != None: root = root.right root.right = None else: root = root.left root.left = None return root def modify(self, root, target, new_val): if target is not new_val: Solution().insert(root,new_val) return Solution().delete(root,target) else: return root
1d3fff09c010a933a0ca8e449d26a400c8f82018
GhadeerHS/FullStack-DojoBootcamp
/Python_Stack/_python/OOP/User-ChainingMethods.py
937
3.78125
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_deposit(self, amount): self.account_balance += amount return self def make_withdrawal(self, amount): self.account_balance -= amount return self def display_user_balance(self): # print("User:"+ self.name + "Balance:" + self.account_balance) print "User: {}, Balance: {}".format(self.name,self.account_balance) return self user1=User("Ghado","gh@gmail.com") user2=User("Jan","jan@gmail.com") user3=User("hui","hui@gmail.com") user1.make_deposit(100).make_deposit(200).make_deposit(50).make_withdrawal(150).display_user_balance() user2.make_deposit(200).make_deposit(200).make_withdrawal(150).make_withdrawal(10).display_user_balance() user3.make_deposit(500).make_withdrawal(150).make_withdrawal(10).make_withdrawal(10).display_user_balance()
2545737696b06791648668be7b1ff00f4560fda0
cheungYX/nlp100
/python/temp.py
195
3.640625
4
# encoding: UTF-8 x = 12 y = "気温" z = 22.4 def temp(x, y, z): # return str(x) + "時の" + y + "は" + str(z) return '{x}時の{y}は{z}'.format(x=x, y=y, z=z) print(temp(x, y, z))
e50125140d9bea77ba542aa0744c3f8a37559b1e
cheungYX/nlp100
/python/patoka_taxi.py
179
3.5625
4
# encoding: UTF-8 word1 = "パトカー" word2 = "タクシー" res = "" for i,j in zip(range(0, len(word1)), range(0,len(word2))): res += word1[i] res += word2[j] print(res)
fbf53fa4ce50fd7df01df3f67659824eeb031b07
c-a-r-d-g-a-m-e/tacobellgenerator
/taco bell generator.py
710
3.796875
4
import random word1 = ["crunchy", "soft", "supreme", "beefy", "nacho", "beefy 5-layer", "cheesy", "nacho cheese", "spicy", "mild"] word2 = [" chicken", " bean", " black bean", " nacho", " doritos locos", " gordita"] word3 = [ " taco", " burrito"," chalupa", " quesadilla", " bellgrande", " supreme", " crunchwrap", " quesalupa", " nachos", " fries", " quesarito"] def generate(): for i in range(30): print(word1[random.randint(0,9)] + word2[random.randint(0,5)] + word3[random.randint(0,10)]) restart() def restart(): restart = input("r to run ") if restart == "r": generate() print("TACO BELL GENERATOR") print("=-=-=-=-=-=-=-=-=-=") restart()
8bf2921b08e068aa754f0924f164605dd672049a
nauman-sakharkar/Python-2.x
/Skip Repeated Char.py
164
3.953125
4
list=input("Please Enter Your List = ") output=[] output = [n for n in list if n not in output] print("Your Requested List : ", ''.join(output)) print("Thank You")
0a3b73ddacb55539c7fbf2cd7c97fe40aed5a0ce
nauman-sakharkar/Python-2.x
/Area of the Triangle.py
169
3.921875
4
b=float(input("Enter the Base of the Triangle = ")) h=float(input("Enter the Height of the Triangle = ")) a=.5*h*b print("Area of the Triangle is",a) print("Thank You")
88b0275b14cfe4ab86b469926df08dfbe37229cc
nauman-sakharkar/Python-2.x
/Sum of Factorials.py
285
4.03125
4
a=int(input("Please Enter Your Number = ")) b=int(input("Please Enter Your Number = ")) sum=0 for i in range(a,b+1): fact=1 for j in range(1,i+1): fact=fact*j print("Factorial of ",j," = ",fact) sum=sum+fact print("Sum of Factorials = ",sum) print("Thank You")
944c8136f1e444ccb9fb15eaacb731df40c67184
nauman-sakharkar/Python-2.x
/Check Leap Year.py
128
4.03125
4
a=int(input("Please Enter The Year = ")) if a%4==0: print(a," Is A Leap Year") else: print(a,"Is Not A Leap Year")
82578460b2e44863b1ec837df47585d1da63f41c
nauman-sakharkar/Python-2.x
/Binary to Decimal.py
203
3.8125
4
a=int(input("Please Enter Your Binary Number = ")) j=1 o=0 while True: if a<1: break else: s=a%10 o=o+s*j a=a//10 j=j*2 print("Your Decimal Number : ",o)
dbb7679261275df18328c3309f0a675e22714740
adoskk/PyTorch-Learning-101-Fizz-Buzz-Net
/utils/data_preprocessing.py
590
3.609375
4
import numpy as np # Represent each input by an array of its binary digits. def binary_encode(i, num_digits): return np.array([i >> d & 1 for d in range(num_digits)]) # One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz"] def fizz_buzz_encode(i): if i % 15 == 0: return np.array([0, 0, 0, 1]) elif i % 5 == 0: return np.array([0, 0, 1, 0]) elif i % 3 == 0: return np.array([0, 1, 0, 0]) else: return np.array([1, 0, 0, 0]) def fizz_buzz(i, prediction): return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]
ac4dd126f23e04a3033d8d3c1525f8019b8ce885
pillared/PLC-Exam-2
/Q1/driver.py
1,708
3.546875
4
##################################### ##################################### ############# PLC EXAM 2 ############ ###### Created by Anthony Asilo ##### ########### November 2020 ########### #### https://github.com/pillared #### ##################################### ##################################### """ DRIVER.PY TAKES A TEXT FILE AS INPUT, AND FOR EACH STRING WILL CHECK ALL FUNCTIONS TO FIND A VALID TOKEN """ from perl import validateToken_Perl from javastring import validateToken_JavaString from cint import validateToken_cInt from cchar import validateToken_cChar from cfloat import validateToken_cFloat from ops import validateToken_Ops import sys def main(): # a giant list of test words for function matching token={ 'token_A' : 'Perl', 'token_B' : 'JavaString', 'token_C' : 'cInt', 'token_D' : 'cChar', 'token_E' : 'cFloat', 'token_F' : 'Ops' } arr = [] string = "" filex = open("q1.txt", "r") string = filex.read() arr = string.split( ) print(arr) filex.close() ans = None xo= None for word in arr: # pass to all of the validations # if true, let it be known what token type that word is print(word) for each in token.values(): try: # eval function xo = "validateToken_" + each + "(" + word + ")" # call each specific function to test same word. if(eval(xo)): ans = each print("TOKEN FOUND :", word, "is:", each, ans) except SyntaxError: pass print('\n') if __name__ == "__main__": main()
dc5c2c3645b680a13c5af07cfb859c1079eaee40
kettchansopon/atm-crud-system
/atm-crud-system.py
12,721
4.125
4
import sqlite3 import os import pickle from docx import Document def create_account(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() c.execute('CREATE TABLE customer (\ customerID TEXT NOT NULL PRIMARY KEY,\ name TEXT NOT NULL,\ surename TEXT NOT NULL,\ password TEXT NOT NULL,\ address TEXT NOT NULL,\ sex TEXT NOT NULL,\ age INT NOT NULL,\ email TEXT NOT NULL,\ education TEXT NOT NULL,\ money INT NOT NULL,\ interest INT NOT NULL\ )') c.execute('CREATE TABLE transactions(\ customerID TEXT NOT NULL, \ password TEXT NOT NULL,\ money INT NOT NULL, \ deposit INT,\ withdraw INT\ )' ) conn.commit() print("Database is connected") except Exception as e: print("{}".format(e)) def insert_account(): conn = sqlite3.connect('Account.sqlite') try: count = True c = conn.cursor() name = input("Enter your name: ") surename = input("Enter your surename: ") address = input("Enter your address: ") while(count): sex = input("Enter your gender[M/F]: ") if sex in ('M','F'): break age = int(input("Enter your age: ")) email = input("Enter your Email: ") education = input("Enter your education: ") while(count): money = int(input("Enter your money[first service 500 is minimum]: ")) if(money >= 500): break interest = int(input("Enter interest rate per year:")) cID = input("Enter your ID: ") password = input("Enter your password: ") data = (cID, name, surename, password, address, sex, age, email, education, money, interest) c.execute('INSERT INTO customer(\ customerID,\ name, \ surename, \ password, \ address, \ sex, \ age, \ email, \ education, \ money, \ interest\ ) VALUES (?,?,?,?,?,?,?,?,?,?,?)', data) c.execute('INSERT INTO transactions(customerID, password, money) VALUES (?,?,?)',(cID, password, money)) print("Account is created") except Exception as e: print("{}".format(e)) def show_data(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() for row in c.execute('SELECT * FROM customer'): print(row) except Exception as e: print("{}".format(e)) def withdraw(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() c.execute('SELECT password FROM customer') passwordtuple = c.fetchall() passwordlist = [] for a in passwordtuple: for i in a: passwordlist.append(i) c.execute('SELECT customerID FROM customer') IDtuple = c.fetchall() IDlist = [] for a in IDtuple: for i in a: IDlist.append(i) print("===========Withdraw============") cID = input("Enter your ID: ") cpassword = input("Enter your password: ") while(True): if(cpassword in passwordlist and cID in IDlist): c.execute('''SELECT money FROM customer WHERE password = ?''',(cpassword)) tupmon = c.fetchall() money = [] for t in tupmon: for a in t: money.append(a) print("Total Money: {} Baht.".format(money[0])) withdraw = int(input("How much do you want to withdraw: ")) while(True): if(withdraw <= money[0] and withdraw != 0): new = money[0] - withdraw c.execute('''UPDATE customer SET money = ? WHERE password = ?''',(new,cpassword)) print("Withdraw done") print("Total Money: {} Baht.\nThank you.".format(new)) c.execute('''INSERT INTO transactions( customerID, password, money, withdraw ) VALUES (?,?,?,?)''',(cID,cpassword,new,withdraw)) break elif(withdraw > money[0]): print("You don't have enough money") withdraw = int(input("How much do you want to withdraw: ")) elif(withdraw == 0): withdraw = int(input("Invalid value try again: ")) break else: cID = input("Your ID/password not match! try again.\nEnter your ID: ") cpassword = input("password: ") except Exception as e: print("{}".format(e)) def deposite(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() c.execute('SELECT password FROM customer') passwordtuple = c.fetchall() passwordlist = [] for x in passwordtuple: for i in x: passwordlist.append(i) c.execute('SELECT customerID FROM customer') IDtuple = c.fetchall() IDlist = [] for x in IDtuple: for i in x: IDlist.append(i) print("===========Deposite============") cID = input("Enter your ID: ") cpassword = input("Enter your password: ") while(True): if(cpassword in passwordlist and cID in IDlist): c.execute('SELECT money FROM customer WHERE password = ?',(cpassword)) tupmon = c.fetchall() money = [] for t in tupmon: for a in t: money.append(a) print("Total Money: {} Baht.".format(money[0])) dp = int(input('How many do you want to deposite:')) while(True): if(dp>0): new = money[0]+dp c.execute('UPDATE customer SET money = ? WHERE password = ?',(new,cpassword)) print("Deposite done") print("Total Money: {} Baht.\nThankyou".format(new)) c.execute('INSERT INTO transactions(\ customerID,\ password,\ money,\ deposite\ ) VALUES (?,?,?,?)',(cID,cpassword,new,deposite,)) break elif(deposite == 0): deposite = int(input("Invalid value try again: ")) break else: cID = input("Your ID/password not match! try again.\nEnter your ID: ") cpassword = input("password: ") except Exception as e: print("{}".format(e)) def daily_transaction(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() a = c.execute('SELECT customerID,\ sum(deposite),\ sum(withdraw),\ money FROM transactions group by customerID') s = a.fetchall() count = len(s) doc = Document() t = doc.add_table(rows = count + 1, cols = 5) t.style = "Table Grid" t.rows[0].cells[0].text = "Customer ID" t.rows[0].cells[1].text = "Total Money" t.rows[0].cells[2].text = "Total Transaction" t.rows[0].cells[3].text = "Total Deposite" t.rows[0].cells[4].text = "Total Withdraw" for x in range(count): if(x < count): row = t.rows[x+1] row.cells[0].text = "{}".format(s[x][0]) row.cells[1].text = "{}".format(s[x][3]) row.cells[2].text = "{}".format(s[x][1]+s[x][2]) row.cells[3].text = "{}".format(s[x][1]) row.cells[4].text = "{}".format(s[x][2]) doc.save("Account.docx") c.execute('drop table if exists transactions') c.execute('CREATE TABLE transactions(\ customerID TEXT NOT NULL,\ password TEXT NOT NULL,\ money INT NOT NULL,\ deposite INT,\ withdraw INT\ )''') except Exception as e: print("{}".format(e)) def interest_rate(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() cID = input("Enter your ID: ") c.execute('SELECT customerID FROM customer') IDtuple = c.fetchall() IDlist = [] for x in IDtuple: for i in x: IDlist.append(i) while(True): if(cID in IDlist): c.execute('UPDATE customer SET money = money + (money * (interest/100)) WHERE customerID = ?',(cID)) a = c.execute('select money from customer where customerID=?',(cID)).fetchall() mon = 0 for i in a: for x in i: mon = x print("Total money: {} Baht".format(mon)) break else: cID = input("Wrong ! Please enter your ID again: ") except Exception as e: print("{}".format(e)) def customer_document(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() a = c.execute('SELECT * from customer') s = a.fetchall() count = len(s) doc = Document() t = doc.add_table(rows = count + 1, cols = 11) t.style = 'Table Grid' t.rows[0].cells[0].text = 'Customer ID' t.rows[0].cells[1].text = 'Name' t.rows[0].cells[2].text = 'Surname' t.rows[0].cells[3].text = 'Password' t.rows[0].cells[4].text = 'Address' t.rows[0].cells[5].text = 'Sex' t.rows[0].cells[6].text = 'Age' t.rows[0].cells[7].text = 'Email' t.rows[0].cells[8].text = 'Education' t.rows[0].cells[9].text = 'Money' t.rows[0].cells[10].text = 'Interest rate' for x in range(count): if(x < count): row = t.rows[x + 1] row.cells[0].text = "{s[x][0]}".format(s[x][0]) row.cells[1].text = "{s[x][1]}".format(s[x][1]) row.cells[2].text = "{s[x][2]}".format(s[x][2]) row.cells[3].text = "{s[x][3]}".format(s[x][3]) row.cells[4].text = "{s[x][4]}".format(s[x][4]) row.cells[5].text = "{s[x][5]}".format(s[x][5]) row.cells[6].text = "{s[x][6]}".format(s[x][6]) row.cells[7].text = "{s[x][7]}".format(s[x][7]) row.cells[8].text = "{s[x][8]}".format(s[x][8]) row.cells[9].text = "{s[x][9]}".format(s[x][9]) row.cells[10].text = "{s[x][10]}".format(s[x][10]) doc.save('Customer.docx') except Exception as e: print("{}".format(e)) def dump(): conn = sqlite3.connect('Account.sqlite') try: c = conn.cursor() dump = [] b = c.execute('select * from customer').fetchall() customer_document() output = open("Account.bin","wb") pickle.dump(b, output) print("Dump Finish!") output.close() except Exception as e: print("{}".format(e)) def clear_screen(): os.system('cls') print() if __name__=='__main__': print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>WELCOME<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') create_account() count = True while count: choice = int(input("\n1) deposite\n2) withdraw\n3) create account\n4) exit\n\nchoice>>> ")) if choice == 1: deposite() elif choice == 2: withdraw() elif choice == 3: insert_account() elif choice == 4: # close the program exit() else: clear_screen() print("ERROR: Wrong choice\n") #show_data() #daily_transaction() #interest_rate() #customer_document() #dump()
1465259df7e87d5df881f870524a316093c37fe8
Grommash9/python_25_skillbox
/25_zadacha_4/people.py
3,498
3.796875
4
def text_check(some_text): for symbols in some_text: if not symbols.isalpha(): raise NameError(symbols, 'не являеться буквой') if len(some_text) < 3: raise NameError('Имя или фамилия не должны быть такими короткими') return some_text class Person: def __init__(self, name, surname, age): self.__name = self.set_name(name) self.__surname = self.set_name(surname) self.__age = self.set_age(age) def set_name(self, name): return text_check(name) def set_surname(self, surname): return text_check(surname) def set_age(self, age): if not 18 < int(age) < 99: raise ValueError('Возраст должен быть в диапазоне от 18 до 99') else: return int(age) def get_name(self): return self.__name def get_surname(self): return self.__surname def get_age(self): return self.__age class Employee(Person): def __init__(self, name, surname, age): super().__init__(name, surname, age) def earnings(self): return 0 class Manager(Employee): def __init__(self, name, surname, age): super().__init__(name, surname, age) def earnings(self): return 13000 def info(self): return 'My name is {name} {surname} i am {work} in this months i will get {money}'.format( name=self.get_name(), surname=self.get_surname(), work='Manager', money=self.earnings() ) class Agent(Employee): def __init__(self, name, surname, age, sales_volume=5000): super().__init__(name, surname, age) self.__sales_volume = self.set_sales_volume(sales_volume) def set_sales_volume(self, sales_volume): if sales_volume > 0: return sales_volume else: raise ValueError('Обьем продаж должен быть больше нуля') def get_sales_volume(self): return self.__sales_volume def earnings(self): return 5000 + self.__sales_volume * 0.5 def info(self): return 'My name is {name} {surname} i am {work} we made {sales} volume of sales' \ ' in this months i will get {money}'.format( name=self.get_name(), surname=self.get_surname(), work='Agent', sales=self.get_sales_volume(), money=self.earnings() ) class Worker(Employee): def __init__(self, name, surname, age, hours_worked=20): super().__init__(name, surname, age) self.__hours_worked = self.set_hours_worked(hours_worked) def set_hours_worked(self, hours_worked): if hours_worked > 0: return hours_worked else: raise ValueError('Отработанные часы не могут быть отрицательным значением') def get_hours_worked(self): return self.__hours_worked def earnings(self): return 100 * self.__hours_worked def info(self): return 'My name is {name} {surname} i am {work} i worked hard for {hours} hours' \ ' in this months i will get {money}'.format( name=self.get_name(), surname=self.get_surname(), work='Worker', hours=self.get_hours_worked(), money=self.earnings() )
37bb145d0f063f2c820004b0e127d3f63241d459
narendrapetkar/python
/2.dataStructures/1.linkedList/1.singlyLinkedList.py
1,651
3.578125
4
class node: def __init__(self, data = None, next = None): self.data = data self.next = next class singlyLinkedList: def __init__(self): self.start = None def displayList(self): print("-----------------------------------------") if self.start == None: print("cannot display : List empty!") else: tracer = self.start while tracer != None: print(tracer.data) tracer = tracer.next def insertAtStart(self, value): temp = node(value, self.start) self.start = temp def deleteFromStart(self): if self.start == None: print("cannot delete : list empty!") else: temp = self.start self.start = temp.next temp = None def insertAtEnd(self, value): temp = node(value) if self.start == None: temp.next = self.start self.start = temp else: tracer = self.start while tracer.next != None: tracer = tracer.next tracer.next = temp def deleteFromEnd(self): if self.start == None: print("cannot delete : list empty!") else: tr = self.start while (tr.next).next != None: tr = tr.next tr.next = None #driver code sll = singlyLinkedList() sll.displayList() sll.insertAtStart(10) sll.insertAtStart(20) sll.insertAtStart(30) sll.displayList() sll.insertAtEnd(40) sll.displayList() sll.deleteFromEnd() sll.displayList() sll.deleteFromStart() sll.displayList()
47608808b2736c157c41e81e69dd5e0ca8daa052
narendrapetkar/python
/2.dataStructures/2.stacks/1.stackUsingLinkedList.py
1,223
3.953125
4
class node: def __init__(self, data = None, next = None): self.data = data self.next = next class stack: def __init__(self, size=5): self.top = None self.size = size self.length = 0 def display(self): print("--------------------------------------------") if self.top == None: print("cannot display : stack empty!") else: tr = self.top while tr != None: print(tr.data) tr = tr.next def push(self, value): if self.size < self.length+1: print("cannot push : stack overflow!") return temp = node(value, self.top) self.top = temp self.length = self.length+1 def pop(self): if self.top == None: print("cannot pop : stack empty!") return temp = self.top self.top = temp.next temp = None self.length = self.length-1 s1 = stack() s1.display() s1.push(10) s1.display() s1.push(20) s1.push(30) s1.push(40) s1.push(50) s1.display() s1.push(60) s1.display() s1.pop() s1.display() s1.pop() s1.pop() s1.pop() s1.pop() s1.pop() s1.pop() s1.push(30) s1.display()
40f56600fec03f9964ac06360ae6eab602a5d7bd
narendrapetkar/python
/2.dataStructures/3.queues/1.queueUsingLinkedList.py
1,250
3.953125
4
class node: def __init__(self, prev=None, data=None, next=None): self.prev = prev self.data = data self.next = next class queue: def __init__(self): self.start = None self.end = None def display(self): print("-------------------------------------------------") if self.start == None: print("cannot display : queue empty!") return else: tr = self.start while tr != None: print(tr.data) tr = tr.next def enqueue(self, value): temp = node(data=value) temp.prev = self.end if self.start == None and self.end == None: self.start = temp self.end = temp else: self.end.next = temp self.end = temp def dequeue(self): if self.start==None and self.end == None: print("cannot deque : queue empty!") return temp = self.end self.end = temp.prev self.end.next = None temp = None # driver code q = queue() q.display() q.enqueue(10) q.display() q.enqueue(20) q.enqueue(30) q.enqueue(40) q.enqueue(50) q.display() q.dequeue() q.dequeue() q.display()
04a6cd5174c6519f585c799fcab887f7294d232a
dragon0/clock
/minimalist_clock.py
2,594
3.5625
4
from datetime import datetime from math import sin, cos, radians import pygame class Clock: def __init__(self, width=640, height=480): self._width = width self._height = height def run(self): self._startup() while self._running: self._input() self._update() self._draw() self._shutdown() def _startup(self): pygame.init() self._screen = pygame.display.set_mode((self._width, self._height)) self._font = pygame.font.SysFont(None, 30) self._clock = pygame.time.Clock() self._running = True def _shutdown(self): pass def _input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self._running = False elif event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: self._running = False def _update(self): self._clock.tick(60) self._now = datetime.now() def _draw_hand(self, color, center, width, increment, length): cx, cy = center box = pygame.Rect(0, 0, 0, 0) box.w = width box.h = width box.center = center right = radians(90) theta1 = 90 - (360 / length * increment) theta1 = radians(theta1) theta2 = 90 - (360 / length * (increment-1)) theta2 = radians(theta2) pygame.draw.arc(self._screen, color, box, theta1, theta2, 1) def _draw(self): self._screen.fill((0, 0, 0)) # line(surface, color, start_pos, end_pos, width) # ellipse(surface, color, rect) # arc(surface, color, rect, start_angle, stop_angle) center = pygame.Rect(200, 200, 200, 200) self._draw_hand( (150, 255, 100), (300, 300), 160, self._now.hour % 12, 12) self._draw_hand( (150, 100, 255), (300, 300), 180, self._now.minute, 60) self._draw_hand( (255, 100, 150), (300, 300), 200, self._now.second, 60) color = (255, 0, 0) datesurf = self._font.render( "{d.hour:02}:{d.minute:02}:{d.second:02}".format(d=self._now), False, color) datesurf_rect = datesurf.get_rect() datesurf_rect.topleft = (50, 50) self._screen.blits([ (datesurf, datesurf_rect), ]) pygame.display.flip() if __name__ == '__main__': clock = Clock() clock.run()
aa22158666ec55bbca8870b3716c4dff500454e4
Bernie-Mason/Writings
/python_notes/characterCount.py
247
3.65625
4
#!python # # Python Script : Bernie Mason # message = 'It was a bright cold day in April, and the clocks were striking thirteen' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 print(count)
98f0e692675fc4517abf2c7dfb94c6d12463f9c8
katti97/learningdatascience
/missing number in array.py
356
3.578125
4
a=[] print("Enter the no of test cases: ") tests = int(input()) for test in range(tests): print('Enter the array size:') n = int(input()) print('Enter array elements:') for i in range(n-1): no = int(input("num:")) a.append(int(no)) lisum = int(sum(a)) sum=int(n*(n+1)/2) print(int(sum-lisum))
5ed7472af54b4e92e4f8b8160dbdfa42fc8a0c7b
deepabalan/byte-of-python
/functions/function_varargs.py
720
4.15625
4
# When we declare a starred parameter such as *param, then all the # positional arguments from that point till the end are collected as # a tuple called 'param'. # Similarly, when we declare a double-starred parameter such as **param, # then all the keyword arguments from that point till end are collected # as a dictionary called 'param'. def total(a=5, *numbers, **phonebook): print ('a', a) # iterate through all the items in tuple for single_item in numbers: print('single_item', single_item) # iterate through all the items in dictionary for first_part, second_part in phonebook.items(): print(first_part, second_part) total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560)
8dd5344dc6cf65b54fa6982dfc8fd7b8989b35e0
Yurisbk/Codigos-Python
/Replace With Alphabet Position.py
473
3.921875
4
def alphabet_position(text): alphabet_numbers = [] for letra in text: if type(letra) == str: x = ord(letra.lower()) - 96 if '-' in str(x): pass else: alphabet_numbers.append(x) else: pass listToStr = ' '.join([str(numero) for numero in alphabet_numbers]) return str(listToStr) print(alphabet_position("The sunset sets at twelve o' clock."))
e2f198706079a03d282121a9959c8e913229d07c
hazydazyart/OSU
/CS344/Homework2/Problem4.py
959
4.15625
4
#Megan Conley #conleyme@onid.oregonstate.edu #CS344-400 #Homework 2 import os import sys import getopt import math #Function to check if a number is prime #Arguments: int #Return: boolean #Notes: a much improved function to find primes using the sieve, this time using the #square root hint from Homework 1. def isPrime(input): for i in range (2, int(math.sqrt(input))+1): if (input % i) == 0: return False return True #Function which finds and prints nth prime #Arguments: passed from command line #Return: none def findPrime(argv): count = 0 val = 2 if len(sys.argv) != 2: print 'Usage: python Problem4.py <number>' sys.exit(2) userInput = int(sys.argv[1]) #Loops until the number of primes founds reaches the user's input upper bound and prints it while count < userInput: if isPrime(val): count += 1 if count == userInput: print 'The ' + str(userInput) + 'th prime is ' + str(val) val += 1 if __name__ == '__main__': findPrime(sys.argv[1:])
dc4db3e0b382830e15bd1a9ddb6ee4cf0d2ea51f
hazydazyart/OSU
/CS344/Homework2/Problem5.py
780
3.734375
4
#Megan Conley #conleyme@onid.oregonstate.edu #CS344-400 #Homework 2 import os import subprocess if __name__ == '__main__': command = 'who' # Uses popen module to enter command and pipe output # I used http://www.saltycrane.com/blog/2008/09/how-get-stdout-and-stderr-using-python-subprocess-module/ as a reference for this problem. # That site has a much more complex example. For this assignment, since the only specification is to print the output of 'who', # I only piped stdout. The support for stdin and sterr will likely be useful in future assignments, but this one is hard coded to do # one task and do it correctly. popen_cmd = subprocess.Popen(command, stdout=subprocess.PIPE) #Prints the output that was piped through the Popen command output = popen_cmd.stdout.read() print output
7ea394326afb19d703362bb50c9b8eea783cd797
cjwawrzonek/Thesis
/model/inputSpaces.py
2,803
4
4
#!/usr/bin/python # Filename: inputSpaces.py import numpy as np from types import * import math class inputSpace: '''Number of input spaces''' numSpaces = 0 def __init__(self, size, name="Default Space"): '''The size must be odd''' if size % 2 == 0: raise Exception("The size of the side must be odd") '''The size of the input space along 1D''' self.size = size '''Name of this input space''' self.name = name '''the list of input coordinates in this space''' self.inputCoors = [] '''Represents a nxn grid of 2d space.''' self.grid = np.zeros((size,size)) inputSpace.numSpaces += 1 print "Total number of inputSpaces is: %d" % inputSpace.numSpaces def __del__(self): '''Deleting Space''' print 'Deleting Space %s.' % self.name inputSpace.numSpaces -= 1 if inputSpace.numSpaces == 0: print 'No more inputSpaces' else: print 'There are still %d inputSpaces left.' % inputSpace.numSpaces def createInputs(self, numInputs): assert type(numInputs) is IntType, "numInputs is not an integer: %r" % numInputs arclength = 360 / numInputs radius = int(round(self.size / 2)) self.inputCoors = [] for i in range(numInputs): coor = [] theta = i*arclength # print "Thetat: " + str(theta) dx = round(radius*math.cos(math.radians(theta))) x_coor = round(radius + dx) dy = round(radius*math.sin(math.radians(theta))) y_coor = round(radius - dy) # print "dx, dy: " + str(dx) + " " + str(dy) # print "coor: " + str(y_coor) + " " + str(x_coor) # print coor.append(y_coor) coor.append(x_coor) self.inputCoors.append(coor) # We know our total number of spaces is increased. # Get the input grid for any given input, or list of inputs def getInputGrid(self, inputs=[]): outgrid = np.zeros((self.size,self.size)) if type(inputs) is IntType: # just make a grid with this one input outgrid[self.inputCoors[inputs][0]][self.inputCoors[inputs][1]] = 1 elif len(inputs) == 0: # make a grid with all inputs for coor in self.inputCoors: outgrid[coor[0]][coor[1]] = 1 else: # make a grid with a set of inputs for i in inputs: assert i >= 0 and i < len(self.inputCoors), "Input %d does not exist" % i outgrid[self.inputCoors[i][0]][self.inputCoors[i][1]] = 1 return outgrid # get the coordinate of the specified input number def getCoor(self, i): assert i >= 0 and i < len(self.inputCoors), "Input %d does not exist" % i return self.inputCoors[i] # return all the input coordinates for this space def getCoors(self): return self.inuptCoors # print the input space including any set of given inputs def printSpace(self, inputs=[]): print "Input Coordinates:" print self.inputCoors outgrid = self.getInputGrid(inputs) for i in range(self.size): print outgrid[i]
a31f8bf711f1e742ba8432dae8125add1f6a7f27
lj960912/pythonlx
/test1.py
137
3.921875
4
#循环 while True: # 输入 story = input("说出你的故事") if len(story) <= 6: #输出 print(story) else: print("太墨迹了")
18444d7fbb2ea124b7065c60cad89489d87b4d02
rvaccarim/kakuro_combinations
/src/kakuro.py
4,282
3.78125
4
import itertools import collections from functools import reduce from typing import List KakuroData = collections.namedtuple('KakuroData', 'sum length factors') combinations: List['KakuroData'] = [] Style = collections.namedtuple('Style', 'text background') def find_combinations(): # we get all the possible combinations that have 2 to 9 factors numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for length in range(2, 10): for combination in itertools.combinations(numbers, length): total_sum = sum(combination) factors_str = "".join(map(str, combination)) data = KakuroData(sum=total_sum, length=length, factors=factors_str) combinations.append(data) combinations.sort() # alternative implementation # def find_combinations2(): # # we get all the possible combinations that have 2 to 9 factors # for length in range(2, 10): # for combination in itertools.combinations('123456789', length): # # reduce iterates through a collection and shortens it by applying a function to the two first elements, # # then applies the same function to the result and the next element # total_sum = reduce(lambda x, y: int(x) + int(y), combination) # factors_str = "".join(combination) # # data = KakuroData(sum=total_sum, length=length, factors=factors_str) # combinations.append(data) # # combinations.sort() def create_html(mode): black = "#000000" grey = "#999999" # 1 = color # 2 = monochrome with open('factors.html', 'w') as f: if mode == 1: # text color, background colors = [Style("", ""), Style("", ""), Style("000000", "#D0A9F5"), Style("000000", "#A9A9F5"), Style("000000", "#A9D0F5"), Style("000000", "#A9F5D0"), Style("000000", "#D0A9F5"), Style("000000", "#99FFFF"), Style("000000", "#F2F5A9"), Style("000000", "#F5A9A9")] else: colors = [Style("", ""), Style("", ""), Style("#FFFFFF", "#000000"), Style("#000000", "#FFFFFF"), Style("#FFFFFF", "#000000"), Style("#000000", "#FFFFFF"), Style("#FFFFFF", "#000000"), Style("#000000", "#FFFFFF"), Style("#FFFFFF", "#000000"), Style("#000000", "#FFFFFF")] f.write(open_html()) f.write(head()) f.write("<body>\n") f.write("<b>") f.write("<font size='3'>Kakuro factors</font>") f.write("</b>\n") f.write("<table>\n<tr>\n") for length in range(2, 10): f.write(table_row(f"{length}-factor ", colors[length].text, colors[length].background)) f.write("</tr>\n") f.write("</table>\n") f.write("<table border='1'>\n") previous = combinations[0][0] new_row = True for combination in combinations: if previous != combination.sum: f.write(table_row(previous, black, grey)) f.write("</tr>\n") new_row = True if new_row: f.write("<tr>\n") f.write(table_row(combination.sum, black, grey)) new_row = False i = combination.length f.write(table_row(combination.factors, colors[i].text, colors[i].background)) previous = combination.sum f.write(table_row(previous, black, grey)) f.write("</tr><P>\n") f.write("</table>\n") f.write("</body>\n") f.write("</html>\n") def open_html(): return "<!DOCTYPE html>\n<html>\n" def head(): return "<head>\n<title>\nKakuro factors\n</title>\n</head>\n" def table_row(text, text_color, bg_color): return f"<td align='center' bgcolor='{bg_color}'><font size='2' face='Arial' color='{text_color}'>{text}</font></td>\n" def main(): find_combinations() create_html(mode=1) print("Done!") if __name__ == "__main__": main()
d47970e2ac4ecf813fab315e24c80e8117b1cb08
startling/cytoplasm
/cytoplasm/controllers.py
1,437
3.65625
4
# -*- coding: utf-8 -*- '''These are the things used in making and using controllers. ''' import imp import os class Controller(object): """Controllers take data from some files, do stuff with it, and write it to the build directory.""" def __init__(self, site, data, destination, templates="_templates"): # take four arguments: the site, the source directory, the destination # directory, and optionally a directory wherein the templates reside. # assume these are relative pathnames. self.site = site self.data_directory = os.path.join(site.source, data) self.destination_directory = os.path.join(site.source, destination) self.templates_directory = os.path.join(site.source, templates) # create the destination directory, if it doesn't exist if not os.path.exists(self.destination_directory): os.mkdir(self.destination_directory) def __call__(self): # do whatever needs to be done here... pass def template(self, name): """Given a name, return the name of the file in the templates directory that fits it.""" # list of files that fit: files = [f for f in os.listdir(self.templates_directory) if f.startswith(name + ".")] # return the first file that matches, with the directory prepended. return os.path.join(self.templates_directory, files[0])
95a2c110eb814244f2dd7c4a6ac3e9a22bb26ef9
loochao/lch-emacs-1
/library/programming/python/lch_python5.py
347
3.828125
4
def make_squares(key, value=0): """Return a dictionary and a list""" d = {key:value} l = [key,value] return d, l def __init__(self, first, second, third, fourth, fifth, sixth): out = (first + second + third + fourth + fifth + sixth) try: print x except NameError: print "Something is wrong!" print 1 print x print 2
7f54290a49d1b50aacd0e17cebd218c741edac23
cflb/SistemasWEB-I-ifbaiano
/aula2 - manipulando strings/manipulando_string_com_funcao-INCOMPLETO.py
370
3.625
4
def invertePalavra(palavra): """ Funcao que retorna parte final da palavra invertida """ comprimento = len(palavra) palavra_invertida = palavra[::-1] nova_palavra = "" for letra in palavra_invertida: if letra == " ": pass else: nova_palavra = nova_palavra + letra return nova_palavra
1ba6bdbe1a38142ed97a360d607c33cc7c61a3bb
JXYXie/kattis
/python/stuck_in_a_time_loop.py
104
3.734375
4
#! /usr/bin/python3 days = int(input()) for i in range(1, days+1): print("%s Abracadabra" %i)
a5b0bcd93668247dbaeaa869de1e1f136aa32f28
emilyscarroll/MadLibs-in-Python
/MadLibs.py
593
4.21875
4
# Story: There once was a very (adjective) (animal) who lived in (city). He loved to eat (type of candy). #1) print welcome #2) ask for input for each blank #3) print story print("Hello, and welcome to MadLibs! Please enter the following words to complete your story.") adj = input("Enter an adjective: ") animal = input("Enter a type of animal: ") city = input( "Enter the name of a city: ") candy = input("Enter a type of candy: ") \n print("Thank you! Your story is:") \n print("There once was a very " + adj + " " + animal + " who lived in " + city + ". He loved to eat " + candy + ".")
f41baf09646cb49661b3f54acaf289e49426b9bc
PriyanshiPanchal/python
/Matplotlib/Cinema Entertainment/Cinema_Interface.py
1,849
3.8125
4
import Cinema_Functions restart = ['Yes', 'YES', 'Y', 'yes'] while restart not in ['NO', 'No', 'no', 'N', 'nO', 'n']: choice1 = int(input('1.Yearly Collection Of All Branchesn\n2.Quaterly Collection(Gross)\n' '3.Quaterly Collection(Branch Wise)\n4.Performance of a Branch on given Date Range\n' '5.Collection of Whole Year For Selective Branch\n' '6.Find Total shares of all branches with reeespect to Revenue Type(MonthWise)')) if choice1 == 1: Cinema_Functions.yearly_Colection() elif choice1 == 2: Cinema_Functions.quaterly_Collection() elif choice1 == 3: b_name =input("Enter Branch Name") Cinema_Functions.quaterly_Collectio(b_name) elif choice1 == 4: d_from=input('From:') d_to=input('To') Cinema_Functions.perfomance(d_from, d_to) elif choice1 == 5: b_name= input("Enter Branch Name") Cinema_Functions.collection_Whole_Year(b_name) elif choice1 == 6: choice2 = int(input('1.Screen-1\n2.Screen-2\n3.Screen-3\n4.Food & Beverages\n5.Advertisment')) if choice2==1: r_name='Screen-1' Cinema_Functions.revenue_Type(r_name) elif choice2==2: r_name='Screen-2' Cinema_Functions.revenue_Type(r_name) elif choice2==3: r_name='Screen-3' Cinema_Functions.revenue_Type(r_name) elif choice2==4: r_name='Food & Beverages' Cinema_Functions.revenue_Type(r_name) elif choice2==5: r_name='Advertisment' Cinema_Functions.revenue_Type(r_name) else: print("Invalid Choice") else: print('Invalid Choice') restart=input("Do you want to continue?")
4ee92676919794308b6c16d822bac420f819156e
PriyanshiPanchal/python
/Matplotlib/Water Supply Management System/D.py
185
3.515625
4
import matplotlib.pyplot as plt import csv import numpy as np import pandas as pd df = pd.read_csv("D.csv") df.head() df.plot.bar(x='Condition',y=['Before','After']) plt.show()
2bfee7b8a357fe2dc8c8b700b6232b156e92bb2c
Volseth/astroevents
/astro.py
2,937
3.53125
4
import datetime import math MJD_JD_CONVERSION_VALUE = 2400000.5 LONGITUDE_MINUTES_VALUE = 4.0 DEFAULT_DATE_FORMAT = "%Y-%m-%d" AUTO_CONVERSION_JD_MJD_VALUE = 1721060.5 def find_corresponding_night(JD: float, Lon: float) -> datetime: """ From range [0,AUTO_CONVERSION_JD_MJD_VALUE] JD is treated as MJD (years 4713 BC to year 0 AC) From range [AUTO_CONVERSION_JD_MJD_VALUE, inf) there is no conversion Supported MJD years are from 1858-11-17 0:00:00 to 6570-12-24 12:00:00 Years are configurable via AUTO_CONVERSION_JD_MJD_VALUE """ if JD - AUTO_CONVERSION_JD_MJD_VALUE <= 0: JD = mjd_to_jd(JD) greenwich_date_time = jd_to_datetime_object(JD) longitude_time_difference = abs(Lon * LONGITUDE_MINUTES_VALUE) time_delta = datetime.timedelta(minutes=longitude_time_difference) local_solar_time = greenwich_date_time + time_delta if Lon >= 0.0 else greenwich_date_time - time_delta if local_solar_time.hour >= 12: night = local_solar_time.strftime(DEFAULT_DATE_FORMAT) else: night = (local_solar_time - datetime.timedelta(days=1)).strftime(DEFAULT_DATE_FORMAT) return night def mjd_to_jd(MJD: float) -> float: return MJD + MJD_JD_CONVERSION_VALUE def jd_to_date(JD: float) -> (int, int, float): # Conversion to Greenwich calendar date using method from book "Practical Astronomy with your # Calculator or Spreadsheet" # math.trunc -> remove fractional part of a number if JD < 0: raise ValueError("Invalid argument for JD to date conversion") JD = JD + 0.5 fractional_part, integer_part = math.modf(JD) integer_part = int(integer_part) if integer_part > 2299160: A = math.trunc((integer_part - 1867216.25) / 36524.25) B = integer_part + 1 + A - math.trunc(A / 4.) else: B = integer_part C = B + 1524 D = math.trunc((C - 122.1) / 365.25) E = math.trunc(365.25 * D) G = math.trunc((C - E) / 30.6001) day = C - E + fractional_part - math.trunc(30.6001 * G) month = G - 1 if G < 13.5 else G - 13 year = D - 4716 if month > 2.5 else D - 4715 return year, month, day def day_to_hour_minutes_seconds(day: float) -> (int, int, int): if day > 1.0: raise ValueError("Invalid argument for day conversion") # Get hours from day, fractional part is minutes left, then fractional part from minutes is seconds hours = day * 24. hours, hour = math.modf(hours) minutes = hours * 60. minutes, mins = math.modf(minutes) seconds = minutes * 60. seconds, sec = math.modf(seconds) return int(hour), int(mins), int(sec) def jd_to_datetime_object(JD: float) -> datetime: year, month, day = jd_to_date(JD) fractional_day, day = math.modf(day) day = int(day) hours, minutes, seconds = day_to_hour_minutes_seconds(fractional_day) return datetime.datetime(year, month, day, hours, minutes, seconds)
e12de86b8fb4ac44eec683c173b3493618a03fb0
ericmburgess/maruchamp
/ramen/action.py
6,638
3.921875
4
"""An `Action` is a small, self-contained unit of activity, such as: * A kickoff * A front (or other) flip * Pointing the wheels down while in midair It also may be an ongoing activity, such as: * Chasing the ball * Driving to a particular place on the field The major distinction between an `Action` and a `Task` is that actions do not have score functions. Therefore the agent never executes them directly--they are run only when invoked by a task (or another action). By default, actions are not interruptible. Until the action completes, the agent will not be able to switch off of the Task that started it. This is what we want for e.g. a half-flip, because stopping that in the middle will leave our car upside-down and/or pointed the wrong way. However, it doesn't (probably) make sense for a "ball chase" action. Any action that *should* be interrupted when the agent wants to switch away from it should have its `interruptible` attribute set to `True`. """ from vitamins.match.match import Match class Action: current_step = 0 interruptible: bool = False done = False countdown: int = 0 tick: 0 wake_time: float = 0 sub_action: "Action" = None done_after_sub_action = False first_step = None def __init__(self): self.stepfunc = self.step_0 self.status = "" if self.first_step is not None: self.step(self.first_step) def __str__(self): name = type(self).__name__ sub = f" -> {self.sub_action}" if self.sub_action else "" if self.done: return f"{name}: DONE" elif self.status: return f"{name}:{self.current_step} [{self.status}] {sub}" else: return f"{name}:{self.current_step} {sub}" def run(self): """Run the current step.""" if not self.done: if self.sub_action is not None: self.before() self.sub_action.run() self.after() if self.sub_action.done: self.sub_action = None self.done = self.done or self.done_after_sub_action elif Match.time < self.wake_time: self.when_paused() elif self.countdown: self.when_paused() self.countdown -= 1 else: self.before() self.stepfunc() self.after() # If we were marked done, run the when_done event: if self.done: self.when_done() def step(self, step_name, ticks: int = 0, ms: int = 0): """Moves execution to the given step. Calling this does not end execution of the current step (if there are more statements below the call to `step`, they will be executed), and execution of the next step does not happen until the next game tick. In the language of state machines, this is how state transitions are made. If `ticks` is specified and positive, then execution is suspended for that many ticks before picking up at the new step. o If `ms` is specified and positive, then execution is suspended until that many in-game milliseconds have elapsed. If `ms` is less than the duration of a single frame (16.67ms at 60fps, 8.33ms at 120fps), there will be no pause in execution. During ticks in which normal execution is suspended, the `when_paused` method is called instead of the current step method. """ self.current_step = step_name self.sleep(max(ticks, 0), max(ms, 0)) self.stepfunc = getattr(self, f"step_{step_name}", None) if self.stepfunc is None: self.done = True raise UndefinedStepError(f"{step_name} is not defined.") def busy(self): """Return True if this action should not be interrupted. Even if this action is marked as interruptible, it may have a sub-action (or sub-sub-...-action) which is not interruptible. This method will return True if any action in the chain is not interruptible. """ return (not self.interruptible and not self.done) or ( self.sub_action is not None and self.sub_action.busy() ) def do_action(self, sub_action: "Action", step=None, done=False): """Start doing another action. Execution will pick up where it left off once the new action is complete. The `before` and `after` methods will continue to run for this action while the sub-action is in progress. If `step` is given, execution of this action will resume at that step after the sub-action is done. If `done` is True, this action will be done as soon as the sub-action finishes. """ if self.sub_action is None: self.sub_action = sub_action self.done_after_sub_action = done if step is not None: self.step(step) else: raise ActivityError("Can't start a sub-action, one is alredy in progress.") def sleep(self, ticks=0, ms=0): """Pause execution for a specified number of ticks or milliseconds. The `when_paused` method will be called each tick in place of normal execution. """ self.countdown = max(self.countdown, ticks) if ms > 0: self.countdown = 0 self.wake_time = Match.time + ms / 1e3 def wake(self): """Cancel any pause in progress.""" self.countdown = 0 self.wake_time = 0.0 def before(self): """This will be called every tick before the current step (or sub-action) is executed.""" def after(self): """This will be called every tick after the current step (or sub-action) is executed.""" def when_paused(self): """This will be called instead of the current step when `self.step` has been invoked with a wait which hasn't finished yet.""" def when_done(self): """Called only once, at the end of the tick in which `self.done` is set to True. """ def step_0(self): pass def step_1(self): pass def step_2(self): pass def step_3(self): pass def step_4(self): pass def step_5(self): pass def step_6(self): pass def step_7(self): pass def step_8(self): pass def step_9(self): pass def step_10(self): pass class UndefinedStepError(Exception): pass class ActivityError(Exception): pass
4f82dfb7a6b951b9a5fed1546d0743adb4109fbd
kkeller90/Python-Files
/newton.py
335
4.375
4
# newtons method # compute square root of 2 def main(): print("This program evaluates the square root of 2 using Newton's Method") root = 2 x = eval(input("Enter number of iterations: ")) for i in range(x): root = root - (root**2 - 2)/(2*root) print(root) main()
9b404bc765ffe2809bc713acc67a488018014f2b
roksanapoltorak/tester_school_dzien_7
/bank_account.py
891
3.96875
4
""" """ class BankAccount(): def __init__(self, balance): if balance <= 0: raise ValueError('Balance less than 0.') self.balance = balance def withdraw(self, amount): if self.balance < amount: raise ValueError('You have too little money.') if amount < 0: raise ValueError('You can`t withdraw less than 0...') return self.balance - amount def deposite(self, amount): if amount < 0: raise ValueError('You cant`t deposit less than 0...') return self.balance + amount account = BankAccount(1500) print("Your balance after withdraw: ", account.withdraw(600)) print("Your balance after deposite: ", account.deposite(1800)) second = BankAccount(-500) print("Your balance after withdraw: ", second.withdraw(100)) print("Your balance after deposite: ", second.deposite(1200))
35a1dde2f54c79e8bdb80f5cd0b0d727c3ee1e4f
Rurelawati/pertemuan_12
/message.py
1,000
4.1875
4
# message = 'Hello World' # print("Updated String :- ", message[:6] + 'Python') # var1 = 'Hello World!' # penggunaan petik tunggal # var2 = "Python Programming" # penggunaan petik ganda # print("var1[0]: ", var1[0]) # mengambil karakter pertama # print("var2[1:5]: ", var2[1:5]) # karakter ke-2 s/d ke-5 # Nama : Rurelawati # Kelas : TI.20.A2 # Mata Kuliah : Bahasa Pemrograman txt = 'Hello World' print(80*"=") print(len(txt)) print(txt[10]) # Ambil Karakter Terakhir print(txt[2:5]) # Ambil Karakter index ke-2 sampai index ke-4 (llo) print(txt[:5]+'World') # Hilangkan Spasi pada text menjadi (HelloWorld) print(txt.upper()) # Merubah txt menjadi huruf besar print(txt.lower()) # Merubah txt menjadi huruf kecil print(txt.replace("H", "J")) # Merubah (H) menjadi (J) print(80*"=") # Latihan 2 print("============>>>>> LATIHAN 2") print("______________________________") umur = 20 txt = 'Hello, nama saya Mitchel, umur saya {} tahun' print(txt.format(umur)) print(80*"=")
ab28ad7aa2a605209e30a81b1d3af97c92a4f21d
Jokmonsimon/holbertonschool-web_back_end
/0x00-python_variable_annotations/3-to_str.py
264
4
4
#!/usr/bin/env python3 "To string Function" def to_str(n: float) -> str: """ -------------- METHOD: to_str -------------- Description: Method that returns an string from a float stored in @n: """ return str(n)
fc13cdd991c7a08aa3375666edc78c19f77479a7
Jokmonsimon/holbertonschool-web_back_end
/0x02-python_async_comprehension/0-async_generator.py
483
3.78125
4
#!/usr/bin/env python3 """Async Generator""" import random import asyncio from typing import Generator async def async_generator() -> Generator[float, None, None]: """ ----------------------- METHOD: async_generator ----------------------- Description: Generates and returns a float n number of times to an async generator call in main() """ for i in range(10): await asyncio.sleep(1) yield random.uniform(0, 10)
f3a58f7aa8c0eefb13ea7ebdeb529254f5d8eb4e
songming05/algorithm_with_python
/pythonProject/fastCampus/psByType/MusicNote.py
579
3.71875
4
# listCase1 = 1 2 3 4 5 6 7 8 # listCase2 = 8 7 6 5 4 3 2 1 # listCase3 = 8 1 7 2 6 3 5 4 # print("Start") # if int("1") == 1 : # print("true") # else: # print("false") desc = [8, 7, 6, 5, 4, 3, 2, 1] asc = [1, 2, 3, 4, 5, 6, 7, 8] p = list(map(int, input().split(" "))) # print(p[1]) isAsc = True isDesc = True for i in range(len(p)): if isAsc: if p[i] != asc[i]: isAsc = False if isDesc: if p[i] != desc[i]: isDesc = False if isAsc: print("ascending") elif isDesc: print("descending") else: print("mixed")
e7c49138ab5debbf3dd5a951779420e2e2084c38
jamargolden/Computer-Science-Portfolio
/Bank Security Program/safebank.py
2,050
3.734375
4
class Account: ID = 1 counter = 0 def __init__(self, initial_deposit): self.balance = initial_deposit def withdraw(self, amount): for i in range(0, 3): check = int(input("What is your account ID? : ")) if not check == self.ID: self.counter += 1 if self.counter == 3: print("This account is locked. Please call again.") else: if amount > self.balance: self.counter = 0 return 0 else: self.balance -= amount self.counter = 0 return amount def deposit(self, amount): for i in range(0, 3): check = int(input("What is your account ID? : ")) if not check == self.ID: self.counter += 1 if self.counter == 3: print("This account is locked. Please call again.") else: self.balance += amount return self def current_balance(self): return self.balance class Bank(Account): def __init__(self, name, initial_deposit): self.name = name Account.__init__(self, initial_deposit) self.ID = Account.ID Account.ID += 1 self.locked_out = False def get_balamce(self): for i in range (0, 3): check = int(input("What is your account ID? : ")) if check == self.ID: self.counter = 0 return "Name:" + self.name + " " + "Balance: " + str(self.balance) else: self.counter += 1 if self.counter == 3: print("This account is locked. Please call again.") def __str__(self): return "Name: {0} ID: {1} Balance: {2}".format(self.name, self.ID, self.current_balance()) x1 = Bank("Kaiser", 100) x2 = Bank("Ursala", 200) x3 = Bank("Shilah", 75) print(x3.deposit(2))
7ed4c213849fa8f5656a452ee713b432a2dc91c6
smspillaz/seg-reg
/segmention_with_channel_regularization/utils/visualization.py
731
3.71875
4
"""/segmentation_with_channel_regularization/utils/visualization.py Helper utiliities for visualizing images and segmentations. """ import numpy as np from PIL import Image def black_to_transparency(img): """Convert black pixels to alpha.""" x = np.asarray(img.convert('RGBA')).copy() x[:, :, 3] = (255 * (x[:, :, :3] != 0).any(axis=2)).astype(np.uint8) return Image.fromarray(x) def overlay_segmentation(image, segmentation_image, blend_alpha=0.3): """Overlay the segmentation on the original image Black pixels are converted to alpha. """ return Image.blend(image, black_to_transparency(segmentation_image).convert('RGB'), alpha=blend_alpha)
7099f0a2ad696634535880c7d8adf5f35578b7f9
seongjin605/python-algorithm
/leetcode/1.easy/merge-two-sorted-lists.py
809
3.953125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # Base Case if l1 == None: return l2 if l2 == None: return l1 # Recurson Relation node = ListNode( None ) if l1.val < l2.val: node.val = l1.val node.next = self.mergeTwoLists( l1.next, l2 ) else: node.val = l2.val node.next = self.mergeTwoLists( l1, l2.next ) return node # if not l1 or (l2 and l1.val > l2.val): # l1, l2 = l2, l1 # if l1: # l1.next = self.mergeTwoLists(l1.next, l2) # return l1
adc95eba280979fa1eec9be767a9034db906ab3b
seongjin605/python-algorithm
/leetcode/2.medium/binary-tree-level-order-traversal.py
837
3.78125
4
# Definition for a binary tree node. import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] tree_nodes = collections.deque([root]) result = [] while len(tree_nodes) > 0: current = collections.deque([]) tree_size = len(tree_nodes) for i in range(tree_size): node = tree_nodes.popleft() if node.left: tree_nodes.append(node.left) if node.right: tree_nodes.append(node.right) current.append(node.val) result.append(current) return result
11063b2725df077b031ac43d38356537d6aef6bf
Prdcc/StudentShapers
/RealFunctions/InvertibilityIntro.py
2,649
3.53125
4
from manimlib.imports import * def doubling_line(x): return 2*x def hidden_flat_line(x): return 0 def parabola(x): return x**2 class LinearIsInvertible(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -11, "y_max" : 11, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=True) graph_object = self.get_graph(hidden_flat_line,self.function_color) line_obj = self.get_graph(doubling_line,self.function_color) vert_line = self.get_vertical_line_to_graph(2,line_obj,color=YELLOW) #this might be made to go to graph_obj if you use ReplacementTransform in previous line hori_line = self.get_graph(lambda x : 4, color = YELLOW, x_min = 2, x_max = 0) #reversing axes works exactly the way i want here self.play(ShowCreation(graph_object)) self.play(Transform(graph_object,line_obj)) self.play(ShowCreation(vert_line)) self.wait() self.play(ShowCreation(hori_line)) class ParabolaNotInvertible(GraphScene): CONFIG = { "x_min" : -5.5, "x_max" : 5.5, "y_min" : -11, "y_max" : 11, "graph_origin" : ORIGIN , "function_color" : BLUE , "axes_color" : GREEN, "x_labeled_nums" : range(-5,5,1), "center_point" : 0 } def construct(self): self.setup_axes(animate=True) graph_object = self.get_graph(hidden_flat_line,self.function_color) parabola_obj = self.get_graph(parabola,self.function_color) #vert_line = self.get_vertical_line_to_graph(2,line_obj,color=YELLOW) hori_line_to_right = self.get_graph(lambda x : 4, color = YELLOW, x_min = 0, x_max = 2) hori_line_to_left = self.get_graph(lambda x : 4, color = YELLOW, x_min = 0, x_max = -2) #vert_line_right = self.get_vertical_line_to_graph(2,sneaky_line_obj) vert_line_right = Line(self.coords_to_point(2, 4), self.input_to_graph_point(2, graph_object),color =YELLOW) vert_line_left = Line(self.coords_to_point(-2, 4), self.input_to_graph_point(-2, graph_object),color =YELLOW) self.play(ShowCreation(graph_object)) self.play(Transform(graph_object,parabola_obj)) self.wait() self.play(ShowCreation(hori_line_to_right),ShowCreation(hori_line_to_left)) self.play(ShowCreation(vert_line_right),ShowCreation(vert_line_left))
05088e67d2f20f00af0cfb0ad1f81203dec73830
prachichouksey/Hashing-2
/409_Longest_Palindrome.py
1,678
3.953125
4
# Leetcode problem link : https://leetcode.com/problems/longest-palindrome/ # Time Complexity : O(n) # Space Complexity : O(n) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach ''' Basic approach : O(n2) => check for each character and add its count to a hashmap. At the end get all even counts and check if odd count value keys are also present Optimized approach: The main idea of this approach is to maintain a set of characters. Add the character to hashset if its not already present. If the character is already present that means even characters can form a valid palidrome and hence remove from the hashset and increase the length by 2. If only even characters are present then hashset will be empty at the end. If one or more characters are left i.e. odd characters then any one can be used to form a valid palindrome ''' class Solution: def longestPalindrome(self, s: str) -> int: # initialize set and max length char_set = set() max_len = 0 # iterate through character string for char in s: # if char is present in the set increase count by 2 (for already present character and current character) and also remove for future characters if char in char_set: max_len +=2 char_set.remove(char) # else add to the set else: char_set.add(char) # return max length of set is empty or pick any one character with odd count and 1 return max_len + 1 if len(char_set) > 0 else max_len
cde6e96b795b24308364326c0985720133129b98
Colonello56/ICC700
/src/main/java/codeforces/PetyaAndString.py
106
3.8125
4
a = input().lower() b = input().lower() if a < b: print('-1') elif a > b: print('1') else: print('0')
dfbbc780f565a00034a58c4a76f58cbba6d66c6f
Garmider008/kolokvium2
/36.py
604
3.515625
4
''''' Знайти суму додатніх елементів лінійного масиву цілих чисел. Розмірність масиву - 10. Заповнення масиву здійснити з клавіатури. Гармідер Анастасія 122В ''''' import numpy as np#импортируем библиотеку нампи s = 0 b=np.zeros(5,dtype=int) for i in range(5):#проходимся по елементам масива b[i] = int(input('Введите ваши элементы ')) for k in range(5):#снова проходимся if b[k]>0: s+=b[k] print(s)
f553f8bffae621e2f6ef1207cba8ce523f4421d3
Garmider008/kolokvium2
/8.py
667
3.59375
4
''''' Створіть цілочисельний масив А [1..15] за допомогою генератора випадкових чисел з елементами від -15 до 30 і виведіть його на екран. Визначте найбільший елемент масиву і його індекс. Гармідер Анастасія 122В ''''' import numpy as np import random p = 0 h = 0 a = np.zeros(12, dtype=int) for i in range(12): a[i] = random.randint(1, 15) print('Рандомні числа масиву', a) for i in range(len(a)): if a[i] > h: h = a[i] p = i print("Максимум:", h) print("Його індекс", p+1)
7d30f856847d8378a31f668dd6c53c0038df0299
Garmider008/kolokvium2
/23.py
1,099
3.609375
4
''' Знайти суму всіх елементів масиву цілих чисел, які менше середнього арифметичного елементів масиву. Розмірність масиву - 20. Заповнення масиву здійснити випадковими числами від 150 до 300. Гармідер Анастасія 122В ''' import numpy as np#импортируем библиотеку нампи import random u=[] c=0 b=np.zeros(20,dtype=int)#инициализируем матрицу масив и присваеиваем типу данных тип данных инт for i in range(20):#проходимся по елементам масива b[i] = random.randint(150,300)#генерируем значения s=np.mean(b) #ищем среднее арифметическое for k in range(20):#снова проходимся l=b[k]#помещаем элементы в пустую переменную if l<s: c+=l print('Среднее арифметическое',s) print('Сумма всех элементов',c)
ce5158d7d150c8aebe274404a4087084a5caee29
Garmider008/kolokvium2
/2.py
1,043
3.765625
4
''''' Введіть з клавіатури п'ять цілочисельних елементів масиву X. Виведіть накран значення коріння і квадратів кожного з елементів масиву. Гармідер Анастасія 122В ''''' import numpy as np#импортируем библиотеку нампи b=np.zeros(5,dtype=int)#инициализируем матрицу нулями и присваеиваем типу данных тип данных инт u=[] u1=[] for i in range(5):#проходимся по елементам матрицы b[i] = int(input('Введите ваши элементы: '))# for k in range(5):#снова проходимся по нашей матрице l=b[k]**2 # подносим к квадрату l1=b[k]**0.5 #корень u.append(l)#добавляем в список квадрат u1.append(l1)# добавляем в список корень print('Значения в квадрате',u) print('Корень',u1)
f2cd13048bd193cd249deb047c2a72e94ca3f00c
Garmider008/kolokvium2
/38.py
706
3.84375
4
''' Дані про направлення вітру (північний, південний, східний, західний) і силі вітру за декаду листопада зберігаються в масиві. Визначити, скільки днів дув південний вітер з силою, що перевищує 8 м / с. Гармідер Анастасія 122В ''' c=0 for i in range(10): #діапазон b=str(input('направлення')) j=int(input('швидкість')) if b=='південь' and j>8: #умова c+=1 #лічильник print(' Стільки днів дув південний вітер з силою, що перевищує 8 м / с:',c)
15c227a247320477806e3eb2df121380f0386a6a
Garmider008/kolokvium2
/6 (2).py
943
3.671875
4
''''' Створіть масив А [1..8] за допомогою генератора випадкових чисел зелементами від -10 до 10 і виведіть його на екран. Підрахуйте кількість від’ємних елементів масиву. Гармідер Анастасія 122В ''''' import numpy as np#импортируем библиотеку нампи import random count=0 b=np.zeros(8,dtype=int)#инициализируем масив нулями и присваиваем типу данных тип данных инт for i in range(8):#проходимся по елементам масива b[i] = random.randint(-10,10) for k in range(8):#снова проходимся if b[k]<0: #если элементы меньше 0,счетчик увеличивается на 1 count+=1 print('Количество отрицательных элементов',count)
4994ecb59234cb1ab07c1af793617249db19d5cc
Garmider008/kolokvium2
/42.py
594
3.765625
4
''' Підрахувати кількість елементів одновимірного масиву, для яких виконується нерівність i*i<ai<i! Гармідер Анастасія 122В ''' import math e=0 for i in range(10):#діапазон c=math.factorial(i)# факторіал іерції d=i*i#квадртат ітерації b = int(input('Введіть число:')) # масив print(f'{c} меньше за b') print(f'{d} больше за b') if d<b<c:#умова e+=1#лічильник print('Кількість елементів: ', e)
825790a0a32fec4fae31165076de7de15717d478
mario21ic/python_curso
/session2/11_listas_operaciones.py
829
3.96875
4
# -*- coding: utf-8 -*- print "#"*3 +" Listas operaciones "+"#"*3 print "" print "## Eliminar ##""" lista = [1, '2', ['tres', 4], '5', '6'] del(lista[2]) print "del(lista[2]):",lista print "" print "## Fusionar ##""" lista = lista + ['x','d'] + ['x','y'] print "lista:",lista print "" print "## Copiar ##""" a = [3, 4, 5, 6] b = a print "b = a\na is b:",a is b b = a[:] print "b = a[:]\na is b:",a is b b = list(a) print "b = list(a)\na is b:",a is b print "" print "## Comparacion ##""" print "[1, 2, 3] == [1, 2] => ",[1, 2, 3] == [1, 2] print "[1, 2, 3] == [1, 2, 3] => ",[1, 2, 3] == [1, 2, 3] print "[1, 2, 3] == [1, 2, 4] => ",[1, 2, 3] == [1, 2, 4] print "[1, 2, 3] < [1, 3, 2] => ",[1, 2, 3] < [1, 3, 2] print "[10, 20, 30] > [1, 3, 2] => ",[10, 20, 30] > [1, 3, 2] print "[1, 2, 3] < [1, 2] => ",[1, 2, 3] < [1, 2]
dcf6a2221c0bdfeefabddcf2e4d88f0fc2c5de39
mario21ic/python_curso
/session2/14_funciones.py
1,160
3.71875
4
# -*- coding: utf-8 -*- print "#"*3 +" Funciones "+"#"*3 print "" print "## Simple ##""" def funcion_simple(): return "Funcion simple" print funcion_simple() print "" print "## Parametros ##""" def funcion_parametros(cadena): if cadena is not None: return cadena return False print funcion_parametros("Funcion parametros") print "" print "## Parametros default ##""" def funcion_param_default(cadena1, cadena2='cad2', cadena3='cad3'): return cadena1 + " " + cadena2 + " " + cadena3 print funcion_param_default('micad1', cadena3='micad3') print funcion_param_default('micad1', 'franco') print "" print "## Multi parametros ##""" def funcion_multi_param(cadena1, cadena2='cad2', cadena3='cad3', *args): print "args:",args return cadena1+" "+cadena2+" "+cadena3 print funcion_multi_param('xD', 'micad2', 'micad3', 'micad4', 'micad5') print "" print "## Multi key parametros ##""" def funcion_multi_key_param(cadena1, cadena2='cad2', cadena3='cad3', **kwargs): print "kwargs:",kwargs return cadena1+" "+cadena2+" "+cadena3 print funcion_multi_key_param('xD', 'micad2', 'micad3', cad4='micad4', cad5='micad5')
7a31bc4557b531080976b053c795494b5163e8fb
mario21ic/python_curso
/session1/6_condicionales.py
835
4.09375
4
# -*- coding: utf-8 -*- print "#"*3 +" Condicionales "+"#"*3 print "if:" if True: print "Example if" print "\nelse:" valor = int(raw_input("Ingrese valor < 10: ")) if valor > 10: print "Example if" else: print "Example else" print "\nelif:" valor = int(raw_input("Ingrese valor < 10 y > 5: ")) if valor > 10: print "Example if" elif valor > 5: print "Example elif" else: print "Example else" print "\nswitch case:" valor = raw_input("Ingrese valor 10 o 5: ") resultado = { '10': 'Example if', '5': 'Example elif' } print resultado[valor] print "\nswitch case funciones:" valor = int(raw_input("Ingrese valor 10 o 5: ")) def diez(): print 'Example if' def cinco(): print 'Example elif' resultado = { 10: diez, 5: cinco } try: resultado[valor]() except: print 'Example else'
5ef369a1af4bdcb5765dffec6ed6db0458e3625c
C-CCM-TC1028-111-2113/homework-4-shanimucar
/assignments/28Fibonacci/src/exercise.py
304
3.75
4
def main(): #escribe tu código abajo de esta línea index = int(input("Enter the index: ")) a = 0 b = 1 n = 1 suma = 0 while n <= index: n = n + 1 a = b b = suma suma = a + b print(suma) if __name__=='__main__': main()
3c94682c1e805fe089cc1d1f38442918fef8bcbd
ZzzwyPIN/python_work
/chapter2_exercise/mingyan.py
135
3.625
4
sentence = ' once said,"A person who ... new."' name = "albert einstein" print(name.title()+sentence) name1 = "\tSmith Cooper\t" print(name1.strip())
15fbdde473d21906552ec8add054cb74a09a7ce7
ZzzwyPIN/python_work
/chapter5/Demo5_2.py
223
3.703125
4
anwser = 17 if anwser != 42: print("That is not the correct anwser. Please try again!") StringArr = ['a','h','r','g','n'] print('h' in StringArr) arr1 = 'k' if arr1 not in StringArr: print(arr1.title()+" is a good boy.")
bb83df21cb7dc89440d61876288bfd6bafce994d
ZzzwyPIN/python_work
/chapter9/Demo9_2.py
1,137
4.28125
4
class Car(): """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """返回整洁的描述性信息""" long_name = str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading)+" miles on it.") def updat_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): if miles >= 0: self.odometer_reading += miles else: print("You can't roll back the odometer!") # ~ my_new_car = Car('audi','a4','2016') # ~ print(my_new_car.get_descriptive_name()) # ~ my_new_car.read_odometer() # ~ my_new_car.odometer_reading = 23 # ~ my_new_car.read_odometer() # ~ my_new_car.updat_odometer(80) # ~ my_new_car.read_odometer() # ~ my_new_car.increment_odometer(100) # ~ my_new_car.read_odometer() # ~ my_new_car.updat_odometer(38) # ~ my_new_car.increment_odometer(-1)
e2c9e4c0ae0bf9d4afe46d0e75343d26784fcc33
kvartak2/Data-Structures
/LinkedList/singly_circular_linked_list.py
1,803
4.03125
4
class Node: def __init__(self, data): self.data = data self.next = self class LinkedList: def __init__(self): self.head = None def printlist(self): temp=list.head while(temp.next!=list.head): print(temp.data) temp=temp.next print(temp.data) def append(self,val): temp=Node(val) p=list.head while(p.next!=list.head): p=p.next p.next=temp temp.next=list.head def insert(self,val,pos): if(list.head.next==list.head): list.append(val) else: temp=Node(val) npos=0 p=list.head q=list.head.next while(npos!=pos-1): p=p.next q=q.next npos=npos+1 p.next=temp temp.next=q def delete(self,pos): if(pos==0 or list.head.next==list.head): print("can't delete head node") else: p=list.head q=list.head.next npos=0 while(npos!=pos-1): p=p.next if(q.next==list.head): print("exceeded noeds") return q=q.next npos=npos+1 p.next=q.next q=q.next list=LinkedList() list.head=Node(10) list.printlist() print("---------") list.append(20) list.printlist() print("---------") list.append(30) list.printlist() print("---------") list.append(40) list.printlist() print("---------") list.append(50) list.printlist() print("---------") list.insert(22,2) list.printlist() print("---------") list.delete(3) list.printlist() print("---------")
b9b62c981f6e2c7a03d12c6ef483a610971ab94a
hartvigmarton/kattis-exercises
/Python/Spavanac.py
239
3.8125
4
time = input() time = time.split(" ") hour = int(time[0]) minutes = int(time[1]) if minutes < 45: minutes = 60 - abs(minutes - 45) hour -= 1 else: minutes = minutes - 45 if hour < 0: hour = 24 + hour print(hour,minutes)
7dd73b9813b37013d35de4e8c9558187375ad90b
hartvigmarton/kattis-exercises
/Python/Datum.py
216
3.859375
4
from _datetime import date import calendar testInput = input() testInput = testInput.split() day = int(testInput[0]) month = int(testInput[1]) myDate = date(2009,month,day) print(calendar.day_name[myDate.weekday()])
a60763d3c614acf94940564ec264949abf0899ff
Leedong-uk/Programers
/twonumbers-plus.py
343
3.671875
4
def solution(numbers): answer = [] total=[] n=len(numbers) for i in range(0,n): for j in range (i+1,n): k=numbers[i]+numbers[j] if k not in total: total.append(k) total.sort() return total print(solution([2,1,3,4,1])) print(solution([5,0,2,7]))
b1975fd0595de181338af2471a9135ba3c29c625
derekwright29/Chaotic-Dynamics
/hw1/logistic_a.py
574
3.609375
4
import matplotlib.pyplot as plt def logistic_a(x0, R, m): """ First part returns the current state of the system, xn as a function of time, n """ cur_state = x0 xn = [cur_state] n = range(0,m+1) for i in n[1::]: next_state = cur_state * R * (1 - cur_state) # logistic equation xn.append(next_state) cur_state = next_state plt.grid(True) plt.scatter(n, xn, s=10, lw=0) plt.title("X0 = " + str(x0) + "; R = " + str(R) + "; m = " + str(m)) plt.xlabel("n") plt.ylabel("xn") return xn, n
2785927c8c0c73534d66a3e2742c334e3c9c67bd
rocksolid911/lucky13
/weight_change.py
314
4.21875
4
weight = int(input("enter your weight: ")) print(f'''your weight is {weight} is it in pound or kilos ?''') unit = input("(l)pound or (k)kilogram: ") if unit.upper() == "L": convert = weight * 0.45 print(f"you are {convert} kilos") else: convert = weight / 0.45 print(f"you are {convert} pound")
eac160ec897eed706fd6924ef2c55bef93159034
AlirieGray/Tweet-Generator
/qu.py
1,052
4.21875
4
from linkedlist import LinkedList from linkedlist import Node class Queue(LinkedList): def __init__(self, iterable=None): super().__init__(iterable) def enqueue(self, item): """Add an object to the end of the Queue.""" self.append(item) def dequeue(self): """Remove and return the object at the beginning of the Queue.""" if self.is_empty(): raise IndexError("Cannot dequeue from empty queue") temp = self.head.data self.head = self.head.next return temp def peek(self): if self.is_empty(): raise IndexError("Cannot peek from empty queue") return self.head.data def toTuple(self): q_list = [] current = self.head while current: q_list.append(current.data) current = current.next return tuple(q_list) if __name__ == '__main__': q = Queue(["Hello", "world,", "I", "am", "a", "queue!"]) print(q.toTuple()) while not q.is_empty(): print(q.dequeue())
e77a731539b98851b980f44a9c867a3396fe1ba3
Kantarian/GITHUB
/HT_2/HT_2_4.py
1,057
3.5625
4
#4. Створiть 3 рiзних функцiї (на ваш вибiр). Кожна з цих функцiй повинна повертати якийсь результат. #Також створiть четверу ф-цiю, яка в тiлi викликає 3 попереднi, обробляє повернутий ними результат та також повертає результат. #Таким чином ми будемо викликати 1 функцiю, а вона в своєму тiлi ще 3 def show_tree(): picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0] ] for image in picture: for pixel in image: if (pixel): print('*', end ="") else: print(' ', end ="") print(' ') def pass_all(): print('-------') def grass(): print('########') def all_function(): pass_all() show_tree() grass() all_function()
4a19086325066692792bd5e8d6a9fab2349ad5e2
Kantarian/GITHUB
/HT_3/HT_3_4.py
596
3.828125
4
#4. Написати функцію < prime_list >, яка прийматиме 2 аргументи - початок і кінець діапазона, і вертатиме список простих чисел всередині цього діапазона. def prime_list (start, end): list_prime = [] for num in range(start, end + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: list_prime.append(num) return print(list_prime) prime_list (900,1000)
ff5c8aaf1b14f4f40633f2aeb26ed964da679620
Kantarian/GITHUB
/HT_4/HT_4_2.py
1,995
4
4
#2. Створіть функцію для валідації пари ім'я/пароль за наступними правилами: # - ім'я повинно бути не меншим за 3 символа і не більшим за 50; # - пароль повинен бути не меншим за 8 символів і повинен мати хоча б одну цифру; # - щось своє :) # Якщо якийсь із параментів не відповідає вимогам - породити виключення із відповідним текстом. def password_check(passwd): SpecialSym =['$', '@', '#', '%'] val = True if len(passwd) < 3: print('length should be at least 3') val = False if len(passwd) > 8: print('length should be not be greater than 8') val = False if not any(char.isdigit() for char in passwd): print('Password should have at least one numeral') val = False if not any(char.isupper() for char in passwd): print('Password should have at least one uppercase letter') val = False if not any(char.islower() for char in passwd): print('Password should have at least one lowercase letter') val = False if not any(char in SpecialSym for char in passwd): print('Password should have at least one of the symbols $@#') val = False if val: return val def name_check(username): val = True if len(username) < 3: print('length should be at least 3') val = False if len(username) > 50: print('length should be not be greater than 50') val = False if val: return val def main(): passwd = 'Geek12@' username = 'username' if (password_check(passwd) and name_check(username)): print("Password and Username is valid") if not name_check(username): print("Invalid Username!") else: print("Invalid Password!") if __name__ == '__main__': main()
09a979bccf9cce42b1fa77cf88cf8fa889037879
michaelworkspace/AdventOfCode2020
/day01.py
1,277
4.40625
4
from typing import List def find_product(inputs: List[int]) -> int: """Given a list of integers, if the sum of two element is 2020, return it's product.""" # This is the classic Two Sum problem # This is not good solution because it is O(n^2) # for x in INPUTS: # for y in INPUTS: # if x + y == 2020: # ans = x * y # return ans # This is the optimal solution because its time complexity is O(n) needs = {2020 - x for x in inputs} for num in inputs: if num in needs: ans = num * (2020-num) return ans """--- PART 2 --- """ def find_product_part2(inputs: List[int]) -> int: """Given a list of integers, if the sum of three element is 2020, return it's product.""" n = len(inputs) # This is the classic Three Sum problem # Naive run time is O(n^3) cube which is not very efficient for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if inputs[i] + inputs[j] + inputs[k] == 2020: ans = inputs[i] * inputs[j] * inputs[k] return ans with open("Inputs/day01.txt") as f: inputs = [int(line.strip()) for line in f] print(find_product(inputs)) print(find_product_part2(inputs))
87cc1e1a2dd9cb48913508d3c5c9d098333345fd
honghainguyen777/Learning
/Harvard_CS50_Introduction_to_CS/CS50-Pset6-master/cash.py
363
3.71875
4
# import get_float from cs50 from cs50 import get_float user_money = 0 # get positive amount of money from user while (user_money <= 0): user_money = get_float("Change owned: ") # convert money into coin unit u = user_money * 100 # converting to number of coins num_coins = u//25 + (u % 25)//10 + ((u % 25) % 10)//5 + ((u % 25) % 10) % 5 print(int(num_coins))
da703dbeef7ca35bd961260077dfff5f1b7ac925
saimadhu-polamuri/leetcode_30_days_challenge_may2020
/number_complement_day04.py
819
3.546875
4
class Solution: def findComplement(self, num: int) -> int: if num == 0: number= self.bit_complement(num) else: remiders = list() while num >= 1: reminder = num % 2 num = num // 2 remiders.append(self.bit_complement(reminder)) number = self.binary_to_decimal(remiders) return number def bit_complement(self, bit): return 1 - bit def binary_to_decimal(self, binary_array): array_len = len(binary_array) number = 0 for i in range(array_len-1, -1, -1): number = number + binary_array[i] * pow(2, i) return number test_solution = Solution() print(test_solution.findComplement(1)) # print(test_solution.get_bit_complement(0))
911a3f3cefa2ad3f23954e3d1b62b64470d6ed5b
saimadhu-polamuri/leetcode_30_days_challenge_may2020
/majority_element_day06.py
1,136
3.515625
4
__author__ = "saimadhu.polamuri" import math class Solution: # Approach 01 def majorityElement(self, nums) -> int: array_len = len(nums) if array_len > 0: majority_element = nums[0] majority_element_frequency = 1 if array_len > 1: hash_map = dict() threshhold_num = math.floor(array_len / 2) for i in range(0, array_len): if nums[i] in hash_map.keys(): hash_map[nums[i]] += 1 if hash_map[nums[i]] > majority_element_frequency: majority_element = nums[i] majority_element_frequency = hash_map[nums[i]] else: hash_map[nums[i]] = 1 return majority_element # Approach 02 def majorityElement(self, nums) -> int: nums.sort() length = len(nums) // 2 return nums[length] test_solution = Solution() # a = [3,2,3] # a = [2,2,1,1,1,2,2] # a = [1] # a = [6,6,6,7,7] a = [6,6,6,7,7,7] print(test_solution.majorityElement(a))
53016fdc1655182955e960160d4e70800dd44a9f
saimadhu-polamuri/leetcode_30_days_challenge_may2020
/k_closest_points_to_origin_day30.py
754
3.5625
4
__author__ = "saimadhu.polamuri" import math class Solution: def kClosest(self, points, K): total_points = len(points) distance_dict = {} for i in range(total_points): distance_dict[i] = self.get_distance_with_origin(points[i]) # sort the dictionary keys by values keys = sorted(distance_dict, key = lambda x: distance_dict[x]) result_points = [] for i in range(k): result_points.append(points[keys[i]]) return result_points def get_distance_with_origin(self, point): distance = math.sqrt(pow(point[0], 2) + pow(point[1], 2)) return distance test_solution = Solution() # points = [[3,3],[5,-1],[-2,4]] # k = 1 points = [[1,3],[-2,2]] k = 1 print(test_solution.kClosest(points, k))
cee847cc2834b5fc5d1adca2cafcf9631621d449
saimadhu-polamuri/leetcode_30_days_challenge_may2020
/sort_characters_by_frequency_day22.py
654
3.75
4
__author__ = "saimadhu.polamuri" class Solution: def frequencySort(self, s): # Frequency dict frequency_dict = {} for element in s: if element in frequency_dict: frequency_dict[element] += 1 else: frequency_dict[element] = 1 # Sorting the dict sorted_list = sorted(frequency_dict, key= lambda x: frequency_dict[x], reverse=True) result_string = '' for key in sorted_list: result_string += key * frequency_dict[key] return result_string test_solution = Solution() s = "tree" print(test_solution.frequencySort(s))
3ecb2d008a9e9048f8f0305deae58ae363e47da6
huixuant/adventofcode20
/day6/part1.py
372
3.71875
4
def main(): with open('input', 'r') as file: answers = [line.rstrip() for line in file] answers.append('') group = "" count = 0 for ans in answers: if (ans == ''): count += len(set(group)) group = "" else: group += ans print(count) if (__name__ == '__main__'): main()
0ad185da2701617e9580000faad35f2c31df8c9a
YasmineCodes/Interview-Prep
/recursion.py
2,641
4.3125
4
# Write a function fib, that finds the nth fibonacci number def fib(n): assert n >= 0 and int(n) == n, "n must be a positive integer" if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) print("The 4th fibonacci number is: ", fib(4)) # 2 print("The 10th fibonacci number is: ", fib(10)) # 34 # Write a recursive function to find the sum all the digits in a positive number n # For example: the number 223 shoudl return 7 def sum_digits(n): # Constraint assert n >= 0 and int(n) == n, "n must be a positive int" # Base case if n < 10: return n else: # recursion case return n % 10 + sum_digits(int(n/10)) print("The sum of digits in the number 100 is: ", sum_digits(100)) # 1 print("The sum of digits in the number 112 is: ", sum_digits(11234)) # 11 print("The sum of digits in the number 23 is: ", sum_digits(23)) # 5 # Write recursive function that finds the Greates Common Denominator using Euclidean Algorithm (https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm) def gcd(n1, n2): assert int(n1) == n1 and int(n2) == n2, 'numbers must be integers' a = max(n1, n2) b = min(n1, n2) if a < 0: a = a*-1 if b < 0: b = b*-1 if a % b == 0: return b else: return gcd(b, a % b) print("The GCD for 8 and 12 is: ", gcd(8, 12)) print("The GCD for 10 and 85 is: ", gcd(20, 85)) print("The GCD for 48 and 18 is: ", gcd(48, 18)) # Write a function that uses recursion to find the binary representation of a number def binary(n): if n == 0: return "" else: return binary(int(n/2)) + str(n % 2) print("The binary representation of 10 is: ", binary(10)) # 1010 print("The binary representation of 13 is: ", binary(13)) # 1101 def binary2(n): if int(n/2) == 0: return n % 2 else: return n % 2 + 10*binary2(int(n/2)) print("Using binary2: The binary representation of 10 is: ", binary2(10)) # 1010 print("Using binary2: The binary representation of 13 is: ", binary2(13)) # 1101 # Write a recursive function called power that returns the base raised to the exponent # 2, 4 : 2 * power(2, 3) # 2 * power(2, 2) # 2 * power(2, 1) #2* power(2, 0) # 1 def power(base, exponent): if exponent == 0: return 1 else: return base * power(base, exponent-1) print("3 raised to the power of 0 is : ", power(3, 0)) # 1 print("2 raised to the power of 2 is : ", power(2, 2)) # 4 print("5 raised to the power of 4 is : ", power(2, 4)) # 625
5a7de5bcb76641823ad023af5b1c9fc14788e4a5
samkimuel/problem-solving
/코테기출/2020카카오인턴십/키패드누르기v2.py
1,318
3.6875
4
""" @file 키패드누르기v2.py @brief 2020 카카오 인턴십 1번 @desc 구현 두 번째 풀이 - 키패드 위치를 자료구조로 저장 (리스트, 딕셔너리) - 키패드 위치 """ numbers = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] hand = "right" def solution(numbers, hand): answer = '' # 키패드 0~9의 위치 position = [[1, 3], [0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1], [0, 2], [1, 2], [2, 2]] # 처음 손가락 위치 l = [0, 3] r = [2, 3] for i in numbers: if i in [1, 4, 7]: answer += 'L' l = position[i] elif i in [3, 6, 9]: answer += 'R' r = position[i] else: point = position[i] dL = abs(l[0] - point[0]) + abs(l[1] - point[1]) dR = abs(r[0] - point[0]) + abs(r[1] - point[1]) if dL < dR: answer += 'L' l = point elif dL > dR: answer += 'R' r = point else: if hand == 'left': answer += 'L' l = point else: answer += 'R' r = point return answer print(solution(numbers, hand))
3d3c2ea76d310e4dafa304e356b8233f440990a4
samkimuel/problem-solving
/Programmers/K번째수.py
225
3.546875
4
""" @file K번째수.py @brief 정렬 - Level 1 @desc """ def solution(array, commands): answer = [] for i in commands: arr = sorted(array[i[0]-1:i[1]]) answer.append(arr[i[2]-1]) return answer
1e0219ee39944e82af499dfd1f1434582e020b56
misleadingTitle/ProvaBot
/MembroBot/MembroBot/MembroLogic.py
172
3.640625
4
import re keywords = ['cazzo'] def containsKeyword(inputString): if re.match(r'.*?\bcazzo\b.*?', inputString): return True else: return False
044bca938380e92f9de20b91eb94984d3749ae57
LuisAlbertoZepedaHernandez/Mision_02
/misDatos.py
578
3.625
4
# Autor: Luis Alberto Zepeda Hernandez, A01328616 # Descripcion: Elabora un algoritmo y escribe un programa que muestre: Nombre completo, matricula, carrera, escuela de procedencia, y una breve descipcion presonal. # Escribe tu programa después de esta línea. print("Nombre:") print("Luis Alberto Zepeda Hernandez") print("Matricula:") print("A01328616") print("Carrera:") print("LAD") print("Escuela de procedencia:") print("Prepa Tec, Bicultural") print("Descripcion:" ) print("Practico Basqeutbol, me gusta modelar en 3d, escucho todo tipo de musica.") print("Me gusta jugar videojuegos y me considero autodicacta")
81fb27b95ba0d74fcf80132f50c78f1d693baaeb
toledoneto/Python-TensorFlow
/02 TensorFlow Basics/10. Saving and Restoring Models.py
2,019
3.640625
4
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt np.random.seed(101) tf.set_random_seed(101) # Full Network Example # # Let's work on a regression example, we are trying to solve a very simple equation: # # y = mx + b # # y will be the y_labels and x is the x_data. We are trying to figure out the slope and the intercept for the line # that best fits our data! # Artifical Data (Some Made Up Regression Data) x_data = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) print(x_data) y_label = np.linspace(0, 10, 10) + np.random.uniform(-1.5, 1.5, 10) plt.plot(x_data, y_label, '*') # Variables np.random.rand(2) m = tf.Variable(0.39) b = tf.Variable(0.2) # Cost Function error = tf.reduce_mean(y_label - (m * x_data + b)) # Optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) train = optimizer.minimize(error) # Initialize Variables init = tf.global_variables_initializer() # Saving The Model saver = tf.train.Saver() # Create Session and Run! with tf.Session() as sess: sess.run(init) epochs = 100 for i in range(epochs): sess.run(train) # Fetch Back Results final_slope, final_intercept = sess.run([m, b]) # ONCE YOU ARE DONE # GO AHEAD AND SAVE IT! # Make sure to provide a directory for it to make or go to. May get errors otherwise # saver.save(sess,'models/my_first_model.ckpt') saver.save(sess, 'new_models/my_second_model.ckpt') # Evaluate Results x_test = np.linspace(-1, 11, 10) y_pred_plot = final_slope * x_test + final_intercept plt.plot(x_test, y_pred_plot, 'r') plt.plot(x_data, y_label, '*') # Loading a Model with tf.Session() as sess: # Restore the model saver.restore(sess, 'new_models/my_second_model.ckpt') # Fetch Back Results restored_slope, restored_intercept = sess.run([m, b]) x_test = np.linspace(-1, 11, 10) y_pred_plot = restored_slope * x_test + restored_intercept plt.plot(x_test, y_pred_plot, 'r') plt.plot(x_data, y_label, '*') plt.show()
0cc1a20a886dec2e2d65d8187a6eb1e6f92814b6
Abhi7865/python-projects
/cal.py
1,101
4
4
import numpy def add(): num1=int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1+num2; def sub(): num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1-num2; def multi(): num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1*num2; def div(): num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1/num2; def mod(): num1 = int(input("enter number 1:")) num2 = int(input("enter number 2:")) return num1%num2; print("1. Addition") print("2. Substraction") print("3. Multiplication") print("4. Division") print("5. Mode") op = int(input("enter operation number from above (1,2,3,4,5):")) if (op==1): print( "addition: ",add()); elif(op==2): print("Substraction:", sub()) elif(op==3): print("Multiplication:", multi()) elif(op==4): print("division: ", div()) elif(op==5): print("MODE: ", mod()) else: print("invalid option...")
e3382c4e700995d5decef3245d859372123decae
b21727795/Programming-with-Python
/Quiz2/quiz2_even_operation.py
596
4.3125
4
import sys def choose_evens(input_string): evens = [int(element) for element in input_string.split(',') if(int(element)> 0 and int(element) % 2 == 0) ] all_numbers = [int(element) for element in input_string.split(',') if int(element)> 0] even_number_rate = sum(evens) / sum(all_numbers) print("Even Numbers: "+'"'+','.join([str(x) for x in evens])+'"') print("Sum of Even Numbers:", str(sum(evens))) print("Even Number Rate:{:.3f}".format(even_number_rate)) def main(input_string): choose_evens(input_string) if __name__ == "__main__": main(sys.argv[1])
983d13c3603604f8a5274bffd019be4410cf025d
Konan33/Word_Processing_Service
/main.py
1,585
3.96875
4
#Intro print('*'*56) print('* CHÀO MỪNG QUÝ KHÁCH ĐÃ ĐẾN VỚI DỊCH VỤ XỬ LÝ VĂN BẢN *') print('*'*56) OldString = input('Quý khách vui lòng cho chúng tôi xem văn bản cần xử lý: ') #Lại là Intro while True: print('-'*40) print('Chúng tôi có những dịch vụ sau đây\n1. Trộm long tráo phụng\n2. Triệu hồi Thánh Gióng\n3. Cải trang vi hành\n4. Hiệu triệu tướng lĩnh\n5. Trợ giúp từ xa\n6. Triệu hồi qua gương\n7. Cách ly tối đa\n8. Vào nhầm dịch vụ') print('-'*40) x = int(input('Quý khách vui lòng chọn số: ')) #Kiểm tra lựa chọn if (x == 1): a = input('Vui lòng nhập từ cần thay thế: ') b = input('Vui lòng nhập từ thay thế: ') NewString = OldString.replace(a,b) print('Sau khi trộm long tráo phụng: ',NewString) elif (x == 2): print('Sau khi triệu hồi Thánh Gióng: ',OldString.upper()) elif (x == 3): print('Sau khi cải trang vi hành: ',OldString.lower()) elif (x == 4): print('Sau khi hiệu triệu tướng lĩnh: ',OldString.capitalize()) elif (x == 5): a = input('Vui lòng nhập ký tự cần thêm: ') b = input('Vui lòng nhập vị trí ký tự cần thêm: ') print('Sau khi được trợ giúp từ xa: ',a.join(b)) elif (x == 6): print('Văn bản sau khi triệu hồi qua gương: ',''.join(reversed(OldString))) elif (x == 7): print('Văn bản sau khi cách ly: ',OldString.split(' ')) else: print('Cảm ơn quý khách đã lướt qua!') break
64f6b88bd332f6ca317d0a22ada0ce2f045f9035
VeenaArv/PythonPractice
/denominations.py
2,724
3.515625
4
import random from itertools import combinations def getExactChangeNum(d): # d1,d2,d3,d4 is the 4 denominations from least to greatest changes = [] # fill array with the amt of change itself for i in range(239): changes.append(i) # change array to reflect actual exact change num for j in range(239): if (j == d[0] - 1 or j == d[1] -1 or j == d[2] - 1 or j == d[3] - 1 ): changes[j] = 1 # print("exact change " + str(changes[j])) continue else: if (j >= d[3]): d1 = changes[j - d[3]] + 1 # print("d1 " + str(d1)) else: # print("exact change " + str(changes[j])) continue if (j >= d[2]): d2 = changes[j - d[2]] + 1 # print("d2 " + str(d2)) else: changes[j] = d1 # print("exact change " + str(changes[j])) continue if (j >= d[1]): d3 = changes[j - d[1]] + 1 # print("d3 " + str(d3)) else: changes[j] = min(d1,d2) # print("exact change " + str(changes[j])) continue if (j >= d[0]): d4 = changes[j - d[0]] + 1 changes[j] = min(d1,d2,d3,d4) else: changes[j] = min(d1,d2,d3) return changes #calculates ever single possible change and sums it def sumExactChangeNum(ch ,N): sum = 0 for num in range(239): if ((num + 1)%5 == 0): sum += (N*ch[num]) else: sum += ch[num] return sum # generates denominations def generate(poundValue, N): optimalDenom = [] optimalChange = 100000 # max for the largest denomination max = int(poundValue/2) # every single combination of denoms up till max comb = list(combinations(range(4, max, 1),3)) for l in comb: # sort in reversed order denom = sorted(l, reverse=True) denom.append(1) # impractical for denomications to be close to each other or super big if (denom[1] < 50 and denom[2] < 30 and denom[0] - denom[1] > 15 and denom[1] - denom[2] > 15): values = getExactChangeNum(denom) num = sumExactChangeNum(values, N) if (num < optimalChange): print(denom) print(num) optimalDenom = denom optimalChange = num print(optimalChange) return optimalDenom while(True): n = int(input("Enter N")) print(sumExactChangeNum(getExactChangeNum([55,35,5,1]),n)) print(generate(240, n))
aa92573b123c0f334eca8304adae5b1410f108e5
Xia-Sam/hello-world
/rock paper scissors game against computer.py
1,714
4.3125
4
import random rand_num=random.randint(1,3) if rand_num==1: com_side="rock" elif rand_num==2: com_side="paper" else: com_side="scissors" i=0 while i<5: print("You can input 'stop' at anytime to stop the game but nothing else is allowed.") user_side=input("Please input your choice (R P S stands for rock paper scissors respectively):") if user_side=="R" or user_side=="P" or user_side=="S": if user_side=="R": if rand_num==1: print(" Game is a tie. Try again. 5 more chances") elif rand_num==2: print("Computer win. You lose. ") i+=1 print(5-i," chances left.") else: print("You win. You can continue playing.") elif user_side=="P": if rand_num==2: print(" Game is a tie. Try again. 5 more chances") elif rand_num==1: print("You win. You can continue playing.") else: print("Computer win. You lose. ") i += 1 print(5 - i, " chances left.") else: if rand_num==1: print("Computer win. You lose. ") i += 1 print(5 - i, " chances left.") elif rand_num==2: print("You win. You can continue playing.") else: print(" Game is a tie. Try again. 5 more chances") elif user_side=="stop": break else: print("You can only input R, S or P!! ") print("Try again. You only have 5 chances totally. ") i+=1 print(5-i," chances left") print("Game over. Thank you for playing my game.")
d004b64afb686aa77878e871a9a0ccbafcb21414
ipavel83/Python
/006fileRead.py
386
3.796875
4
#py3.7 from sys import argv script, filename = argv[0], argv[1] print(f"args: {argv}") txt = open(filename) print(f'file named "{filename}" contents:') print(txt.read()) print(f'file named "{filename}" contents by line by line in list:') txt = open(filename) print(txt.readlines()) print("type the filename to read again:") anotherFile = input("> ") print(open(anotherFile).read())
bb0cedf5307d70e5dc8bbc712c890dccc0e7dd37
ipavel83/Python
/014with.py
1,364
3.859375
4
#!/usr/bin/env python3 #py3.7 with open('hello_foo.txt', 'w') as f: f.write('hello, world!') #same as: # f = opent('hello_foo.txt', 'w') # try: # f.wtite('hello, world') # finally: # f.close() with open('hello_foo.txt', 'r') as f: print(f.read()) print() #more advanced: from contextlib import contextmanager import os @contextmanager # https://stackoverflow.com/a/3012921 def working_directory(path): current_dir = os.getcwd() os.chdir(path) try: yield except: print(f"directory {path} not found") finally: os.chdir(current_dir) #Pavel: enclosed with block to get rid of error if directory is not found #should think later if possible to handle such things inside "with" block try: with working_directory("data/stuff"): # do something within data/stuff print('Hi') except: print('problem with with of directory data/stuff') finally: print('first try final') # here I am back again in the original working directory print() #Another way: https://stackoverflow.com/a/5205878/5233335 try: f = open('foo.txt') except IOError: print('error open "foo.txt"') else: with f: print('foo opened') print(f.readlines()) # # some_code #
d3d4f238cba24f0af180985c4f13d5661a0685b5
ipavel83/Python
/011dictionary.py
1,861
3.625
4
#py3.7 print( {True: 'yes', 1: 'no', 1.0: 'maybe'} ) #prints {True: 'maybe'} #dictionary creation overwrites values of same key, key is not updated due optimization #bool is subclass of int, so True is 1 print(True == 1 == 1.0 ) #True print( (hash(True), hash(1), hash(1.0)) ) #(1, 1, 1) ####back to dict :) d = {} print(d) str = 'myKey' str2 = 'myKey2' d[str]=1 d[str2]=5 d[str]+=2 d['another'] = 'string of *&^%' d['myKey5']=0 print(d) e =d.pop('another') print(e) print(d) ######combining dictionarys d2 = {'wow': 8, 'myKey5': 99, 'myKey4':44} print(d2) dComb = {} dComb.update(d) dComb.update(d2) print('one way to combine dictionary: ', dComb) print('another way to combine dictionary: ', {**d, **d2}) ###### access if keys not in dict #one way try: print(d['noSuchKey']) except KeyError: print ('Key error happen, but it was catched') #and another print(d.get('keyNotInDict', 'default If Not foutd')) ###sort by value using lambda dTupSorted= sorted(d.items(), key=lambda x: x[1]) dfromSorted = dict(dTupSorted) print('sorted by value tuple from dict:',dTupSorted, 'And dict from it:', dfromSorted) ###### check if key is in dict: if str in d: print (f'{str} is in {d}') else: print (f'ERR {str} not found is in {d}') if 'myKey2' in d: print (f'myKey2 is in {d}') else: print (f'ERR myKey2 not found is in {d}') if 'another' not in d: print('another not in d') else: print('ERR another is FOUND in d') #also can check item using method get #dict.get(key[, default]) if d.get("test") != None: print("Yes 'test' key exists in dict") else: print("No 'test' key does not exists in dict") print('loop1') for i in d: print(i, d[i]) print('loop2') for k, v in d.items(): print(k, v) d.clear() print(d)
36741092d47d028bac059ff0c10e1eb2449f58fe
2pushkaraj3/AILab
/Lab2/main.py
588
3.5
4
from enviroment import next_move import random from PriorityQueue import PriorityQueue if __name__ == '__main__': myQueue = PriorityQueue() start = list(range(0,9)) random.shuffle(start) start2 = list(range(0,9)) random.shuffle(start2) print("start+>",start) myQueue.insert(start,12) myQueue.insert(start,1) myQueue.insert(start,14) myQueue.insert(start2,7) print(myQueue) myQueue.update(start2,10) print(myQueue.isPresent(start2)) print(myQueue) while not myQueue.isEmpty(): print(myQueue.pop())
0e1d92a3893b3b1bf2b2b820da11fd5949278629
GOD-A01375315/Tarea-05
/Divisbles.py
335
3.5
4
#encoding: UTF-8 #Autor: Genaro Ortiz Durán #Descripción: Escribir una función que calcule cuántos cnúmeros de 4 dígitos son divisibles entre 29. def calcularNumeros(): n=0 for k in range(1000,100000): if k%29==0: n+=1 return k def main(): print("Los numeros divisibles son:",calcularNumeros()) main()
4d86d3e307f5ad156be080c829c0917e85669c7c
aravindnatarajan/InsightProject
/reanalyze.py
978
3.921875
4
import sys def bubbleSort(dummy,A): # Bubble Sort Algorithm for i in range(len(A)): for j in range(i+1, len(A)): if A[j] > A[i]: A[j],A[i] = A[i],A[j] dummy[j],dummy[i] = dummy[i],dummy[j] return dummy,A listWords = [(word.split())[0] for word in open("weights.dat")] listWeights = [int((word.split())[1]) for word in open("weights.dat")] words = [(word.split())[0] for word in open(sys.argv[1])] num = [int((word.split())[1]) for word in open(sys.argv[1])] freq = [float((word.split())[2]) for word in open(sys.argv[1])] newWeights = [] newWords = [] for whichWord in range(0,len(words)): for i in range(0,len(listWords)): if words[whichWord] == listWords[i]: newWeights.append(freq[whichWord]*(float(num[whichWord])/float(listWeights[i]))) newWords.append(words[whichWord]) sortedWords, sortedWeights = bubbleSort(newWords,newWeights) for i in range(0,len(newWords)): print sortedWords[i], sortedWeights[i]
8b7fd28162687ac356f9e21383bbd9d2c0027dbf
jbjulia/SDEV300
/Project2/lottery.py
1,866
4.09375
4
import sys from random import randint def display_menu(): menu_items = [ "[ 1 ] Generate 3-digit lottery number", "[ 2 ] Generate 4-digit lottery number", "[ x ] Quit (Exit application)" ] print("Please select an option from the following menu:\n") # Print directions for item in menu_items: print(item) # Display selection menu get_user_selection() # Get user input def get_user_selection(): lottery_number = 0 selection = input("\n") # User input while selection.lower() != "x": if selection == "1": print("\nGenerating 3-digit lottery number...") lottery_number = pull_lever(3) # Generate random 3-digit lottery number elif selection == "2": print("\nGenerating 4-digit lottery number...") lottery_number = pull_lever(4) # Generate random 4-digit lottery number else: print("\nPlease make a selection from the following menu by entering '1', '2' or 'x' in your terminal.\n") display_menu() # Return to selection menu print("\nYour random", len(str(lottery_number)), # Get length of lottery number "-digit lottery number is: ", lottery_number, "\n") # Print random lottery number display_menu() # Return to selection menu exit_game() # Exit game def pull_lever(digits): range_start = 10 ** (digits - 1) # Define length of random integer range_end = (10 ** digits) - 1 return randint(range_start, range_end) # Returns random 3/4-digit integer def exit_game(): print("\nThank for playing, and always gamble responsibly! Goodbye!") sys.exit() # Exit application if __name__ == "__main__": print("You're playing the Pick-3, Pick-4 Lottery Generator!\n\n") display_menu()
7801cf25e5a1f6eb4060288b9df814c22485272b
Merovizian/Aula13
/Desafio056.py
2,074
3.515625
4
print(f"\033[;1m{'Desafio 056 - Nome idade e sexo':*^70}\033[m") masculino_database = ('m','M','Masculino','MASCULINO') masculino_have = 0 feminino_have = 0 feminino_database = ('f','F','Feminino','FEMININO') quantidade = int(input("Quantas pessoas cadastrar: ")) media = 0 homem_velho = 0 homem_velho_aux = 0 mulher_menos20 = 0 mulher_aux = 0 for c in range(0, quantidade): usuario_nome = input(f"Qual o nome do usuário {c+1}: ") usuario_sexo = input(f"Qual o sexo do usuário {c+1}: ") for d in range(0, 4): if usuario_sexo == masculino_database[d]: masculino_have += 1 if usuario_sexo == feminino_database[d]: feminino_have += 1 if masculino_have == 0 and feminino_have == 0: print("\033[1;31mVocê informou um sexo incorreto!\033[;m") usuario_sexo = input(f"Tente novamente. Qual o Sexo do Usuário {c + 1}: ") for d in range(0, 4): if usuario_sexo == masculino_database[d]: masculino_have += 1 if usuario_sexo == feminino_database[d]: feminino_have += 1 if masculino_have >= 1: masculino_have = 0 usuario_idade = int(input(f"Qual a idade do usuário {c+1}: ")) media += usuario_idade if usuario_idade > homem_velho: homem_velho = usuario_idade homem_velho_aux = usuario_nome if feminino_have >= 1: feminino_have = 0 usuario_idade = int(input(f"Qual a idade do usuário {c+1}: ")) media += usuario_idade mulher_aux = 1 if usuario_idade < 20: mulher_menos20 += 1 print('\n') print(f"A média de idade do grupo é: {media/quantidade}") if homem_velho != 0: print(f"O homem mais velho é o usuário {homem_velho_aux} com {homem_velho} anos") else: print("\033[1;33mNão há lista_homens no grupo!\033[m") if mulher_aux == 1 and mulher_menos20 != 0: print(f"No grupo existem {mulher_menos20} Mulher(es) com menos de 20 anos.") else: print("\033[1;33mNão há lista_mulheres com menos de 20 anos no grupo!")
802016a285b2ed02a03e154ab1f16cedfa401532
Merovizian/Aula13
/Desafio054.py
1,639
3.921875
4
from datetime import datetime import calendar print(f"\033[;1m{'Desafio 054 - Pessoas que atingiram Maioridade':*^70}\033[m") quant = int(input("Quantas pessoas: ")) maioridade = 0 menoridade = 0 for c in range(0, quant): nascimento = input("Digite a sua idade (dd/mm/aaaa): ") dia = int(nascimento[0:2]) mes = int(nascimento[3:5]) ano = int(nascimento[6:10]) ## Verifica se a pessoa ja nasceu e se a data é possivel if dia > 31 or mes > 12 or (ano > datetime.now().year or (ano == datetime.now().year and mes > datetime.now().month) or (ano == datetime.now().year and mes == datetime.now().month and dia > datetime.now().day)): print("\033[1;31mInforme uma data correta!") ## Verifica se o mês tem a limite_cadastro de dias certo if dia > (calendar.monthrange(ano,mes)[1]): print(f"O Mês {mes} do ano {ano} não tem {dia} dias e sim {calendar.monthrange(ano,mes)[1]} dias\n\033[1;31mInforme uma data correta!") ## Calcula a sua idade em dia, mes e anos idade_ano = datetime.now().year - ano idade_mes = datetime.now().month - mes idade_dia = datetime.now().day - dia if idade_dia < 0: idade_mes = idade_mes - 1 idade_dia = calendar.monthrange(ano,mes)[1] + idade_dia if idade_mes < 0: idade_ano = idade_ano - 1 idade_mes = 12 + idade_mes print(f"Você tem {idade_ano} anos, {idade_mes} meses e {idade_dia} dias de vida") if idade_ano >= 21: maioridade += 1 else: menoridade += 1 print(f"Entre as {quant} pessoas inseridas, {maioridade} são maior de idade e {menoridade} são menores de idade")