blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f2cb4c235e9fdbed76c69ddcfb207a959f0b88bc | sinusk8/Lessons | /Home_work_L1_3.py | 252 | 3.875 | 4 | number = int(input('Введите любое число: '))
n = 0
if number < 10:
n = number
while number > 10:
a = number % 10
number //= 10
if a > n:
n = a
print('Наибольшая цифра в числе {}'.format(n))
|
d4b68e0f3e7d829962c0f20e6329db84522547e6 | I-G-P/Python | /Programming Basics/Simple Operations and Calculations - Exercise/04. Tailoring Workshop.py | 524 | 3.65625 | 4 | number_of_tables = int(input())
lenght_of_tables = float(input())
width_of_tables = float(input())
price_of_cover = 7
price_of_square = 9
total_area_of_cover = number_of_tables * (lenght_of_tables + 2 * 0.3) * (width_of_tables + 2 * 0.3)
total_area_of_square = number_of_tables*(lenght_of_tables / 2) * (lenght_of_tables / 2)
usd_total_price = total_area_of_cover * price_of_cover + total_area_of_square * price_of_square
bgn_price = usd_total_price * 1.85
print(f"{usd_total_price:.2f} USD")
print(f"{bgn_price:.2f} BGN") |
4ddb1878b6ecedda9f274801aef997ef838dfd24 | Damian1724/Hackerrank | /Algorithms/Sorting/InsertionSort-Part2.py | 663 | 4 | 4 | /*
Author: Damian Cruz
source: HackerRank(https://www.hackerrank.com)
problem name: Algorithms>Sorting>InsertionSort-Part2
problem url:https://www.hackerrank.com/challenges/insertionsort2/problem
*/
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the insertionSort2 function below.
def insertionSort2(n, arr):
for i in range(1,n):
for j in range(i):
if arr[i] < arr[j]:
arr.insert(j,arr[i])
arr.pop(i+1)
print(*arr)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
insertionSort2(n, arr)
|
d06f20026f517acbc3b20e7c105faed16dd36852 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_79_size_of_object.py | 212 | 3.65625 | 4 | """Write a Python program to get the size of an object in bytes."""
import sys
def give_me_size(object):
return sys.getsizeof(object)
print(give_me_size("Basic_Part_I/ex_59_feet_inches_to_centimeters.py")) |
7ec979896471be5f23be68bc220af9107d43ca06 | serrotsabin/graphics_assignment | /Midpoint Circle Drawing Algorithm.py | 728 | 3.765625 | 4 | from Tkinter import *
r = int(raw_input("Radius: "))
root=Tk()
root.title("CIRCLE")
height=500
width=500
canvas=Canvas(root,height=height,width=width)
canvas.pack()
xc=int(height/2)
yc=int(width/2)
x=0
y=r
p=1-r
while(x<y):
if(p<0):
x=x+1
p=p+2*(x+1)+1
else:
x=x+1
y=y-1
p=p+2*(x-y)+1
canvas.create_text(xc+x,yc+y,text=".")
canvas.create_text(xc-x,yc+y,text=".")
canvas.create_text(xc+x,yc-y,text=".")
canvas.create_text(xc-x,yc-y,text=".")
canvas.create_text(xc+y,yc+x,text=".")
canvas.create_text(xc-y,yc+x,text=".")
canvas.create_text(xc+y,yc-x,text=".")
canvas.create_text(xc-y,yc-x,text=".")
root.mainloop()
|
dc162897191f97407f21e5c84766409127a60712 | NicolasRementeria/university-institute-and-courses | /Courses/the-python-mega-course/1- Introduction/1- Basics/15. Type Attributes, 16. How to Find Out What Code You Need/Excercise3.py | 185 | 4.1875 | 4 | # Modify String (E)
# Find the proper function or method that converts the string in username into lowercase letters and print the output
username = "Python3"
print(username.lower()) |
7c70504d9addca4c0e1292d2281027bbbbde64ca | gciotto/learning-python | /part6/exercise5/sets_operations.py | 1,814 | 3.8125 | 4 | class Set():
def __init__ (self, value = []):
self.data = []
self.concat(value)
def intersect (self, other):
res = []
for x in self.data:
if x in other:
res.append(x)
return Set(res)
def union (self, other):
res = self.data[:]
for x in other:
if x not in res:
res.append(x)
return Set(res)
def concat (self, value):
for x in value:
if x not in self.data:
self.data.append(x)
def __len__(self): return len (self.data)
def __getitem__ (self, index): return self.data[index]
def __and__ (self, other): return self.intersect(other)
def __or__ (self,other): return self.union(other)
def __repr__ (self): return 'Set: ' + str(self.data)
class SetSub (Set):
def __init__ (self, *args):
self.data = []
for x in args:
self.concat(x)
def intersect(self, *others):
res = []
for x in self.data:
for y in others:
if x not in y:
break
else: res.append(x)
return SetSub (res)
def union (self, *others):
res = SetSub(self.data)
for x in others:
res = SetSub(Set.union(res, x))
return res
if __name__ == '__main__':
s1 = Set ([1, 5, 55])
s2 = Set ([1, 4444, 55])
print (s1 | s2, s1 & s2)
s3 = Set ('tricolor')
s4 = Set ('trico')
print (s3, s4 & s3, s3 & 'coco', s4 | 'xopo')
s5 = SetSub (s1, s3)
print (s5)
print (s5.union(s1, s2, s3), s5.intersect(s1, s2, s3))
|
ac9af52e60547eb4e8ff250792e3b48ff716b017 | serleonc/experimento-git | /ordenmiento.py | 354 | 3.578125 | 4 | # lista =[2,5,1,4,9,7,8,6]
# for i in range(1, len(lista)):
# j = i
# while j > 0 and lista[j] < lista[j-1]:
# lista[j],lista[j-1] = lista[j-1],lista[j]
# j-=1
# print(lista)
lista =[2,5,1,4,9,7,8,6]
for i in range(1, len(lista)):
j = i
while j > 0 and lista[j-1] < lista[j]:
lista[j],lista[j-1] = lista[j-1],lista[j]
j-=1
print(lista) |
3dc9b0aa3a45aad8ab820764f09af0bc8836b9f8 | acailuv/WarehouseOS | /WarehouseOS.py | 18,239 | 3.6875 | 4 | import pickle
#utility function to get input etc.
def invalid_input_string(): #a string that will be displayed if something is invalid
print("Invalid Input. Please try again.", end='')
def get_valid_int(caption=""): #returns a valid integer
while True:
try:
n = int(input(caption)) #keep asking for input
except:
invalid_input_string() #look at invalid_input_string() function above
else:
return n #until that particular input was a valid integer
def get_valid_boolchar(caption=""): #returns true if 'y' is input, false if 'n' is input (case insensitive)
while True:
n = input(caption).lower() #keep asking for input
if n=='y' or n=='n':
return n #until it's either 'y' and 'n'
def check_out_of_index(container, index): #returns true if index is in container, false if not
try:
container[index] #check for index in container
return True #if it is not out of bounds
except:
return False #if it is out of bounds
def save_data(): #saves account_list and location_flag to WOS_acc.dat and WOS_loc.dat respectively
acc_data = open("WOS_acc.dat", "wb") #open file WOS_acc.dat in 'write-binary' form
loc_data = open("WOS_loc.dat", "wb") #open file WOS_loc.dat in 'write-binary' form
pickle.dump(account_list, acc_data) #store/write data in accouont_list to WOS_acc.dat
pickle.dump(location_flag, loc_data) #store/write data in location_flag to WOS_loc.dat
acc_data.close() #close 'stream' for file WOS_acc.dat
loc_data.close() #close 'stream' for file WOS_loc.dat
def load_data(account_list, location_flag): #loads WOS_acc.dat and WOS_loc.dat and assign them to account_list and location_flag respectively
try:
acc_data = open("WOS_acc.dat", "rb") #open file WOS_acc.dat in 'read-binary' form.
account_list = pickle.load(acc_data) #load WOS_acc.dat and store its content to account_list
acc_data.close() #close 'stream' for file WOS_acc.dat
except FileNotFoundError: #if WOS_acc.dat does not exist
acc_data = open("WOS_acc.dat", "wb") #create that file by opening it in 'write-binary' form
acc_data.close() #close 'stream' for file WOS_acc.dat
except EOFError: #if file is empty
pass #do nothing
try:
loc_data = open("WOS_loc.dat", "rb") #open file WOS_loc.dat in 'read-binary' form.
location_flag = pickle.load(loc_data) #load WOS_loc.dat and store its content to llocation_flag
loc_data.close() #close 'stream' for file WOS_loc.dat
except FileNotFoundError: #if WOS_loc.dat does not exist
loc_data = open("WOS_loc.dat", "wb") #create that file by opening it in 'write-binary' form
loc_data.close() #close 'stream' for file WOS_loc.dat
except EOFError: #if file is empty
pass #do nothing
return account_list, location_flag #return value of account_list and location_flag (will be assign to account_list(global variable) and location_flag(global variable) respectively)
def print_location_data(): #(debug only) used to print out all locations availability
for i in range(100): #looping for 0 to 99
print(location_flag[i], end=' ') #print location_flag by that index and adds a space
print()
def print_all_account(): #prints all deatils about all accounts
if len(account_list)==0: #if account_list is empty
print("No account exists.")
else: #if not empty
for i in range(len(account_list)): #looping from 0 to size of account_list
print(i+1, ">") #prints i+1 and adds a ">"
account_list[i].to_string() #call to_string() function to account_list at index i
def choose_account(): #choose account and return its index
print("[CHOOSE ACCOUNT]")
print_all_account() #refer to print_all_account() function above
idx = get_valid_int("Choose Account: ") - 1 #refer to get_valid_int() function above. this line gets a valid int and subtract that by 1
while not check_out_of_index(account_list, idx): #refer to check_out_of_index() function above. looping while not in bounds
invalid_input_string() #refer to invalid_input_string() function above
print() #extra space
idx = get_valid_int("Choose Account: ") - 1 #refer to get_valid_int() function above. this line gets a valid int and subtract that by 1
return idx #return index
def find_item(item_key): #find a particular item based on its attributes, name and/or type.
for acc in account_list: #looping all accounts in account_list
for itm in acc.items: #looping all items in that account
key = itm.__class__.__name__ + itm.name #key = (class name of item) + (name of item)
if itm.__class__.__name__ == "Car": #if class of item is car
key = key + itm.model + itm.color #combine string key above with car model and car color
elif itm.__class__.__name__ == "Luggage": #if class of item is luggage
key = key + itm.brand + itm.color #combine string key above with luggage brand and luggage color
elif itm.__class__.__name__ == "Cargo": #if class of item is cargo
for c_itm in itm.content: #looping all items in cargo
if c_itm.__class__.__name__ == "Car": #if class of cargo item is car
key = key + c_itm.model + c_itm.color #combine string key above with car model and car color
elif c_itm.__class__.__name__ == "Luggage": #if class of item is luggage
key = key + c_itm.brand + c_itm.color #combine string key above with luggage brand and luggage color
else: #if item is custom item
key = key + c_itm.name #combine string key above with item name
if str(item_key).lower() in key.lower(): #if the word search is in the key combined above
itm.to_string() #call to_string() function from item (this will differ based on what class that particular item is in)
print("=======================================")
print("Owned by: " + acc.name)
print("Located at: " + itm.location)
print()
#functions to alter/mutate account_list
def add_account(name=None, age=None, phone=None, email=None, address=None): #add account to account_list
print("[CREATE ACCOUNT]")
name = input("Name: ") if name==None else name #input name
age = get_valid_int("Age: ") if age==None else age #input age
phone = input("Phone Number: ") if phone==None else phone #input phone number
email = input("Email: ") if email==None else email #input email
address = input("Address: ") if address==None else address #input address
account_list.append(Account(name, age, phone, email, address)) #add to account_list array
print("[ACCOUNT CREATED]")
save_data() #refer to save_data() function above
def delete_account(idx=None): #delete an account and automatically withdraw all items he/she possessed
for acc in account_list: #looping all account in account_list
acc_number = account_list.index(acc)+1 #acc_number will be (index of current looped account) + 1
print(str(acc_number) + ">")
acc.to_string() #call to_string() function to acc
print("NOTE: All of deleted account's item will be withdrawn!")
acc_index = get_valid_int("Delete Account (Input 0 to cancel): ") if idx==None else idx #get valid int for index
if acc_index==0: return #if index is 0 cancel deletion
while not check_out_of_index(account_list, acc_index-1):
if acc_index==0: return #if index is 0 cancel deletion
print("Account Number", acc_index, "does not exist. Please try again.")
acc_index = get_valid_int("Delete Account (Input 0 to cancel): ") if idx==None else idx #get valid int for index
for item in account_list[acc_index-1].items: #looping item in account_list[acc_index-1]'s item list
item.location = item.location if len(item.location)==1 else item.location[1]
location_flag[int(item.location)-1] = True #set that item location to available or true
del account_list[acc_index-1] #delete that account when we are done
print("[ACCOUNT DELETED]")
save_data() #refer to save_data() function above
#essential variables
account_list = [] #store all account
location_flag = [] #store all location availability
for i in range(100): #assign all locations to 'available' by default
location_flag.append(True)
#classes
class Account:
def __init__(self, name, age, phone, email, address):
self.name = name
self.age = age
self.phone = phone
self.email = email
self.address = address
self.items = [] #Account has 0 item when first registering
def to_string(self): #represents an account in a clear and detailed manner
print("[GENERAL INFORMATION]")
print("Name: " + self.name)
print("Age: " + str(self.age))
print("Address: " + self.address)
print("[CONTACT INFORMATION]")
print("Phone: " + self.phone)
print("Email: " + self.email)
print("[POSSESSED ITEMS]")
if len(self.items) == 0:
print("No item exists.")
else:
for i in self.items:
item_number = self.items.index(i)+1
print(str(item_number) + ">")
i.to_string()
print('\n')
def deposit(self, select=None, name=None, model=None, color=None, brand=None, c_select=None): #deposits an item to an account
if True not in location_flag: #if location_flag is all false or FULL
print("WAREHOUSE FULL!")
return
location = str(location_flag.index(True)+1) #assign the first True value in location_flag to location variable
print("[DEPOSIT NEW ITEM]")
print("1. CAR")
print("2. LUGGAGE")
print("3. CARGO")
print("4. CUSTOM ITEM")
print("5. BACK")
print("> ", end='')
select = get_valid_int() if select==None else select #select menu
if select==1:
name = input("Car Name: ") if name==None else name #input car name
model = input("Car Model: ") if model==None else model #input car model
color = input("Car Color: ") if color==None else color #input car color
self.items.append(Car(name, "#" + location, model, color)) #add car to account item list
location_flag[int(location)-1] = False #flag that location (the one that was assigned to this item) to false (not available anymore)
save_data() #refer to save_data() function above
elif select==2:
name = input("Luggage Name: ") if name==None else name #input luggage name
brand = input("Luggage Brand: ") if brand==None else brand #input luggage brand
color = input("Luggage Color: ") if color==None else color #input luggage color
self.items.append(Luggage(name, "#" + location, brand, color)) #add luggage to account item list
location_flag[int(location)-1] = False #flag that location (the one that was assigned to this item) to false (not available anymore)
save_data() #refer to save_data() function above
elif select==3:
name = input("Cargo Name: ") if name==None else name #input cargo name
new_cargo = Cargo(name, location) #create cargo object
new_cargo.deposit() if c_select==None else new_cargo.deposit(c_select)
self.items.append(new_cargo) #add cargo to account item list
location_flag[int(location)-1] = False #flag that location (the one that was assigned to this item) to false (not available anymore)
save_data() #refer to save_data() function above
elif select==4:
name = input("Item Name: ") if name==None else name #input custom item name
self.items.append(Item(name, "#" + location)) #add custom item to account item list
location_flag[int(location)-1] = False #flag that location (the one that was assigned to this item) to false (not available anymore)
save_data() #refer to save_data() function above
elif select==5:
return
else:
invalid_input_string() #refer to invalid_input_string() function above
print() #extra line
self.deposit() #re-execute this function
def withdraw(self, idx = None): #withdraw an item and clear its location
for i in self.items: #looping item in item list
item_number = self.items.index(i)+1
print(str(item_number) + ">")
i.to_string()
print("[WITHDRAW ITEM]")
item_index = get_valid_int("Withdraw item number (Input 0 to cancel): ") if idx==None else idx #get valid int to item_index
if item_index==0: return
while not check_out_of_index(self.items, item_index-1): #looping while index is out of bounds
print("Item Number", item_index, "does not exist. Please try again.")
item_index = get_valid_int("Withdraw item number (Input 0 to cancel): ") #get valid int to item_index
del self.items[item_index-1] #delete that item from item list
print("[WITHDRAW SUCCESSFUL]")
save_data() #refer to save_data() function above
class Item:
def __init__(self, name, location):
self.name = name
self.location = location
def to_string(self):
print("[GENERAL INFORMATION]")
print("Type: " + self.__class__.__name__)
print("Name: " + self.name)
print("Location: " + self.location)
class Car(Item):
def __init__(self, name, location, model, color):
super().__init__(name, location)
self.model = model
self.color = color
def to_string(self):
super().to_string()
print("[CAR INFORMATION]")
print("Model: " + self.model)
print("Color: " + self.color)
class Luggage(Item):
def __init__(self, name, location, brand, color):
super().__init__(name, location)
self.brand = brand
self.color = color
def to_string(self):
super().to_string()
print("[LUGGAGE/BAG INFORMATION]")
print("Brand: " + self.brand)
print("Color: " + self.color)
class Cargo(Item):
def __init__(self, name, location):
super().__init__(name, location)
self.content = []
def deposit(self, select=None):
print("[CARGO - DEPOSIT]")
print("1. CAR")
print("2. LUGGAGE")
print("3. CUSTOM ITEM")
print("4. BACK")
print("> ", end='')
select = get_valid_int() if select==None else select
if select==1:
name = input("Car Name: ")
model = input("Car Model: ")
color = input("Car Color: ")
self.content.append(Car(name, "CARGO - LOCATION #" + self.location, model, color))
more = get_valid_boolchar("Insert More Items? (Y/N) ")
if more == 'y':
self.deposit()
else:
return
elif select==2:
name = input("Luggage Name: ")
brand = input("Luggage Brand: ")
color = input("Luggage Color: ")
self.content.append(Luggage(name, "CARGO - LOCATION #" + self.location, brand, color))
more = get_valid_boolchar("Insert More Items? (Y/N) ")
if more == 'y':
self.deposit()
else:
return
elif select==3:
name = input("Item Name: ")
self.content.append(Item(name, "CARGO - LOCATION #" + self.location))
more = get_valid_boolchar("Insert More Items? (Y/N) ")
if more == 'y':
self.deposit()
else:
return
elif select==4:
return
else:
invalid_input_string()
print() #extra line
self.deposit()
def to_string(self):
super().to_string()
print("[CARGO DETAILS - CONTENTS]")
for i in self.content:
i.to_string()
# Main Menu Starts Here
# ---------------------
# <Requirement>
# -> Create account
# -> Remove account
# -> Deposit items
# -> Withdraw items
# -> View all accounts
# -> Container/item location
if __name__ == "__main__":
account_list, location_flag = load_data(account_list, location_flag)
while True:
print("[MAIN MENU] ")
print("1. Create Account ")
print("2. Remove Account ")
print("3. Deposit Items ")
print("4. Withdraw Items ")
print("5. Display all Accounts ")
print("6. Find Item/Container Location ")
print("7. Exit Program ")
print("> ", end='')
select = get_valid_int()
if select == 1: #create account
add_account()
elif select == 2: #remove account
delete_account()
elif select == 3: #deposit items
if len(account_list)==0:
print("No account exists. Cannot Deposit")
continue
acc_idx = choose_account()
acc = account_list[acc_idx]
acc.deposit()
elif select == 4: #withdraw items
if len(account_list)==0:
print("No account exists. Cannot Withdraw")
continue
acc_idx = choose_account()
acc = account_list[acc_idx]
acc.withdraw()
elif select == 5: #display all accounts
print_all_account()
elif select == 6: #find item/container
item_key = input("Search: ")
find_item(item_key)
elif select == 7:
quit() #exit program
else:
invalid_input_string()
|
2f342fb25d35880e004e0159cbf61fc0c7a12ecf | shishengjia/PythonDemos | /字符串和文本/字符串_在开头或结尾作文本匹配_P38.py | 456 | 4.1875 | 4 | """
使用str.startswith(),str.endswith()
需要注意的是在传入参数时不能传入列表或者集合,必须首先转化成tuple
"""
filename = 'spam.txt'
print(filename.endswith('.txt')) # True
url = 'http://www.python.org'
print(url.startswith('http:')) # True
import os
filenames = os.listdir('../') # 上一层目录下的文件
print(filenames)
# 查找py文件
pyfile = [name for name in filenames if name.endswith('.py')]
print(pyfile)
|
dd60c8e96ae77a9da6a60c5d096f16c80aebe746 | obligate/python3-king | /it-king/day09-thread/04_0queue_队列.py | 1,726 | 4.375 | 4 | # Author: Peter
# queue队列
# queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
# class queue.Queue(maxsize=0) #先入先出
# class queue.LifoQueue(maxsize=0) #last in fisrt out
# class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列
# Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue.
# Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite
# Queue.qsize()
# Queue.empty() #return True if empty
# Queue.full() # return True if full
# Queue.put(item, block=True, timeout=None)
# q = queue.Queue(maxsize=3)
# q.put("d1") 当size数量超过3的时候,此时往里面put的就会出现等待,不能继续往里面添加
# q.get() 没有数据取,去不了,会等待,卡死,可以在之前通过 q.qsize() 做一个判断
# q.get_nowait() # 没有数据取,可以取数据,但是会报错
# p.get(block=False) # 使用block=False,没有数据取的时候不会卡死,但是会报错
# p.get(timeout=1) # 设置超时时间,没有数据取,超时之后才会取,但是会报错
import queue
q = queue.PriorityQueue()
# 值越小,优先级越高
q.put((-1, "chenronghua"))
q.put((3, "hanyang"))
q.put((10, "alex"))
q.put((6, "wangsen"))
print(q.get())
print(q.get())
print(q.get())
print(q.get())
# # LifoQueue 先入后出,也就是后入先出
# q = queue.LifoQueue()
#
# q.put(1)
# q.put(2)
# q.put(3)
# print(q.get())
# print(q.get())
# print(q.get())
|
8e7cabf9c01a30bb4642c5d174076699c1e1c89a | Sakura1221/Python-100-Days | /Day01-15/My_Code/Day04/for4.py | 322 | 3.703125 | 4 | """
输入一个正整数判断它是不是素数
"""
from math import sqrt
num = int(input("请输入一个正整数:"))
is_prime = True
if num == 1:
is_prime = False
else:
for i in range(2, int(sqrt(num)+1)):
if num % i == 0:
is_prime = False
break
print(is_prime) |
8a14c0c4edc86c413051d5fa75a0d0986f184f58 | bennysetiawan/DQLab-Career-2021 | /Machine Learning with Python for Beginner/27.tugas-praktek-6.py | 691 | 3.59375 | 4 | from sklearn.metrics import mean_squared_error, mean_absolute_error
import numpy as np
import matplotlib.pyplot as plt
#Calculating MSE, lower the value better it is. 0 means perfect prediction
mse = mean_squared_error(y_test, y_pred)
print('Mean squared error of testing set:', mse)
#Calculating MAE
mae = mean_absolute_error(y_test, y_pred)
print('Mean absolute error of testing set:', mae)
#Calculating RMSE
rmse = np.sqrt(mse)
print('Root Mean Squared Error of testing set:', rmse)
#Plotting y_test dan y_pred
plt.scatter(y_test, y_pred, c = 'green')
plt.xlabel('Price Actual')
plt.ylabel('Predicted value')
plt.title('True value vs predicted value : Linear Regression')
plt.show()
|
4f17a5ac376ed4ac536e7a2efccf833b9fe9bb25 | screnary/Algorithm_python | /stack_227_caculator_II.py | 2,911 | 3.84375 | 4 | """ 实现字符串中包含:数字,+, -,*, / 的基本计算器
" 3+2* 2 "
计算:先将所有数字压栈,最后直接对栈内元素求和
"""
import pdb
class Solution:
def calculate(self, s):
""" input| s: str
output| res: int
"""
priority = {'+': 1,
'-': 1,
'*': 2,
'/': 2}
def operate(n1, n2, op):
if op=='+':
return n1 + n2
if op=='-':
return n1 - n2
if op=='*':
return n1 * n2
if op=='/':
return int(n1 / n2)
def helper(s):
stack_num = []
stack_op = []
num = -1 # init num
for i in range(len(s)):
c = s[i]
# read num
if c.isdigit():
if num == -1:
num = int(c) # start read
else:
num = num * 10 + int(c)
elif not c.isdigit() and c != ' ':
if num != -1: # if already read num
stack_num.append(num)
num = -1 # reset num to 'not read'
if c != ')' and (not stack_op or stack_op[-1]=='('):
# condition need to care, when to en-stack op
stack_op.append(c)
elif c=='(':
stack_op.append(c)
elif c in ['*', '/', '+', '-']:
while stack_op:
if stack_op[-1] == '(':
break
elif priority[c] > priority[stack_op[-1]]:
break
op = stack_op.pop()
n2 = stack_num.pop()
n1 = stack_num.pop()
stack_num.append(operate(n1, n2, op))
stack_op.append(c)
elif c == ')':
op = stack_op.pop()
while op != '(':
n2 = stack_num.pop()
n1 = stack_num.pop()
stack_num.append(operate(n1, n2, op))
op = stack_op.pop()
if num != -1:
stack_num.append(num)
while stack_op:
op = stack_op.pop()
n2 = stack_num.pop()
n1 = stack_num.pop()
stack_num.append(operate(n1, n2, op))
return stack_num[0]
return helper(s)
if __name__ == '__main__':
s = " 3 * (4 - 5 / 2) - 6"
s = "(1+(4+5+2)-3)+(6+8)"
s = "(1)"
sol = Solution()
res = sol.calculate(s)
print(res) |
cd82ff1acac72ddad839e846bcaf99dd893c201f | keithmannock/LaTeX-examples | /documents/Numerik/Klausur6/aufgabe2.py | 252 | 3.9375 | 4 | from math import exp, log
def iterate(x, times=1):
#x = x - (2.0*x - exp(-x))/(2.0+exp(-x)) #Newton
x = 0.5*exp(-x) #F_1
#x = (-1)*log(2.0*x) #F_2
if times > 0:
x = iterate(x, times-1)
return x
print(iterate(0.5,6))
|
bfb86b87dc58d3566a5169e13c5bbe2e8d882909 | phanisai22/GCTC-Challenges | /04_neural_hack/00_max_sum.py | 750 | 3.78125 | 4 | def max_sum(input1, input2, input3):
row_sum = []
col_sum = []
s = 0
for i in range(input1):
j = i * input2
for _ in range(input2):
s += input3[j]
j += 1
row_sum.append(s)
s = 0
for i in range(input2):
for j in range(input1):
s += input3[i + j*input2]
col_sum.append(s)
s = 0
return max(row_sum) + max(col_sum)
# print(max_sum(3, 3, [3, 6, 9, 1, 4, 7, 2, 8, 9]))
# print(max_sum(2, 2, [1, 2, 5, 6]))
# print(max_sum(2, 3, [1, 2, 3, 4, 5, 6]))
print(max_sum(4, 8, [1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8, ]))
|
158571ca461f14044b7050f3ab7ef81f1b7bcb57 | yoedhis/latihan-git | /main.py | 711 | 4.09375 | 4 | print('Hello Python')
height = 10
base = 2
area = height*base/2
print "Area is", area
def calculate_triangle(height,base):
return height*base/2
result1=calculate_triangle(10,2)
result2=calculate_triangle(30,5)
result3=calculate_triangle(15,2)
print"Result 1 = ", result1
print"Result 2 = ", result2
print"Result 3 = ", result3
class Math:
def calculate_triangle(self, height, base):
return height * base / 2
triangle1 = Math()
triangle2 = Math()
triangle3 = Math()
result1 = triangle1.calculate_triangle(10,2)
result2 = triangle2.calculate_triangle(30,5)
result3 = triangle3.calculate_triangle(15,2)
print "Triangle 1 = ", result1
print "Triangle 2 = ", result2
print "Triangle 3 = ", result3
|
ffa44619807e3179968aecf7e1666c071681b414 | rmcl/interview_prep | /dynamic_programming/punchcards_total_cost.py | 2,166 | 3.984375 | 4 | class OptimalPunchcarding(object):
"""Dynamic programming solution to find an optimal set of punchcards to run.
Original problem from: https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296
The original problem asked a similar question. I modified it to just find solutions that were less
than some cost value
Take two lists of length n representing n punchcards cost and value.
Call "get_most_value_punchcards" with "max_cost" to get a list of y punchcards
that have maximum value and do not exceed the max_cost
"""
def __init__(self, punchcard_costs, punchcard_values):
self.indexes = list(range(len(punchcard_costs)))
self.costs = punchcard_costs
self.values = punchcard_values
def get_max_value_punchcards(self, max_cost):
return self.recursive_soln(0, max_cost)
def recursive_soln(self, cur_idx, max_cost):
# base case - we have gone through all punchcards. return zero
if cur_idx == len(self.indexes):
return [], 0
else:
# we want to try 1) including and 2) excluding the current punchcard.
cur_cost = self.costs[cur_idx]
cur_value = self.values[cur_idx]
include_val = float('inf') * -1
if cur_cost <= max_cost:
# we can still include this and not exceed the max cost
include_soln, include_val = self.recursive_soln(cur_idx + 1, max_cost - cur_cost)
# try 2. excluding
exclude_soln, exclude_val = self.recursive_soln(cur_idx + 1, max_cost)
if include_val >= exclude_val:
include_soln.append(cur_idx)
soln = include_soln
value = include_val + cur_value
else:
soln = exclude_soln
value = exclude_val
return soln, value
if __name__ == '__main__':
costs = [1,2,3]
values = [3,1,3]
p = OptimalPunchcarding(costs,values)
p.get_max_value_punchcards(4)
|
3db6d323b018d8f374e5f536ea6a5937e28c5b2a | peterhchen/200_NumPy | /03_NumPy/0310_Iterate/08_Enumerate.py | 102 | 3.546875 | 4 | import numpy as np
arr = np.array([1, 2, 3])
for idx, x in np.ndenumerate(arr):
print(idx, x) |
218fa689fc8b10666bf52040f0750dad1a25ff90 | allenwhc/Algorithm | /Company/Google/BTLongestConsecutive(M).py | 1,019 | 3.734375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val=x
self.left=None
self.right=None
class Solution(object):
def longestConsecutive(self, root):
# @param root: TreeNode
# @return: int
if not root: return 0
res=[0]
def dfs(root, target, count, res):
# @param root: TreeNode
# @param target: int
# @return: None
if not root: return
if root.val==target: count+=1
else: count=1
res[0]=max(res[0],count)
dfs(root.left, root.val+1, count, res)
dfs(root.right, root.val+1, count, res)
dfs(root,root.val,0,res)
return res[0]
root=TreeNode(1)
root.right=TreeNode(3)
root.right.left=TreeNode(2)
root.right.right=TreeNode(4)
root.right.right.right=TreeNode(5)
def printTree(root, indent):
#@param root: TreeNode
#@param indent: str
#@return: None
if not root: return
printTree(root.right,indent+' ')
print indent+str(root.val)
printTree(root.left, indent+' ')
printTree(root,'')
print 'Length of longest consecutive is: %s'%Solution().longestConsecutive(root)
|
619ecea20b374866f5a76382a0baa339c458ad67 | Am-dexter/90daysPythonProjects | /Day6/sets.py | 461 | 4.375 | 4 | #
shopping = {'cereals', 'milk', 'bread', 'butter', 'sodas', 'beer'}
#loop through the set
if 'milk' in shopping:
print("Buddy, you already have milk! ")
else:
print("You need to buy milk!")
#Add items to the set
shopping.add('oranges')
print(shopping)
#add multiple items to the set
shopping.update(['mangoes', 'beans', 'juice'])
print(shopping)
#remove an item from the set
shopping.remove('mangoes')
print(shopping) |
3d9771c358dd074bd473a57dba37e415bc0b7b7e | Luweyh/Hash-Map-and-Min-Heap | /min_heap.py | 9,362 | 3.796875 | 4 | # Course: CS261 - Data Structures
# Assignment: 5
# Student: Luwey Hon
# Description: This program represent a min heap which
# is like a tree but all nodes child must be greater than
# the parent's node. It implements several ADTS for
# the min heap.
# Import pre-written DynamicArray and LinkedList classes
from a5_include import *
class MinHeapException(Exception):
"""
Custom exception to be used by MinHeap class
DO NOT CHANGE THIS CLASS IN ANY WAY
"""
pass
class MinHeap:
def __init__(self, start_heap=None):
"""
Initializes a new MinHeap
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.heap = DynamicArray()
# populate MH with initial values (if provided)
# before using this feature, implement add() method
if start_heap:
for node in start_heap:
self.add(node)
def __str__(self) -> str:
"""
Return MH content in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return 'HEAP ' + str(self.heap)
def is_empty(self) -> bool:
"""
Return True if no elements in the heap, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return self.heap.length() == 0
def add(self, node: object) -> None:
"""
Adds a new node into the min heap
"""
# in case there's one node and dont need to find a previous
if self.heap.length() == 0:
self.heap.append(node)
return
self.heap.append(node)
# finding the previous and current index as well as its value
prev_index = (self.heap.length() // 2 - 1)
curr_index = self.heap.length() - 1
prev = self.heap.get_at_index(prev_index)
current = self.heap.get_at_index(curr_index)
# swapping the elments
while current < prev and curr_index != 0:
self.heap.swap(prev_index, curr_index)
curr_index = prev_index
# outlier when prev_index is right before root, need to assign to root
if prev_index == 1:
prev_index -= 1
# update prev index after swapping
else:
prev_index = (prev_index + 1) // 2 - 1
# update previous node
prev = self.heap.get_at_index(prev_index)
pass
def get_min(self) -> object:
"""
returns minimum key without removing it
"""
if self.heap.length() == 0:
raise MinHeapException
return self.heap.get_at_index(0)
def remove_min(self) -> object:
"""
Removes the minimum key and updates the
positions after removing
"""
# when the heap is empty
if self.heap.length() == 0:
raise MinHeapException
curr_index = 0
# base cases when removing 1,2,3 nodes
if self.heap.length() == 1:
pop_val = self.heap.pop()
elif self.heap.length() == 2:
self.heap.swap(0, 1)
pop_val = self.heap.pop()
elif self.heap.length() == 3:
# if left is smaller
if self.heap.get_at_index(1) < self.heap.get_at_index(2):
self.heap.swap(0, 1)
self.heap.swap(1,2)
pop_val = self.heap.pop()
# if right is smaller
else:
self.heap.swap(1,2)
pop_val = self.heap.pop()
# removing when there's 4+ nodes
else:
# swapping the last node with the front, and then popping to remove it
self.heap.swap(0, self.heap.length() - 1)
pop_val = self.heap.pop()
# finding the direction in the first swap
if self.heap.get_at_index(1) > self.heap.get_at_index(2):
next = self.heap.get_at_index(2)
next_index = 2
else:
next = self.heap.get_at_index(1)
next_index = 1
current = self.heap.get_at_index(curr_index)
next = self.heap.get_at_index(next_index)
curr_index = 0
flag = 1
while flag == 1:
# initial first swap
if curr_index == 0:
self.heap.swap(curr_index, next_index)
curr_index = next_index
# if self.heap.length() <= 3:
# flag = 0
# swaps afterwards
else:
# keeping track of left and right nodes
left = (curr_index + 1) * 2
right = left + 1
# it reaches the bottom of the tree
if (curr_index + 1) * 2 + 1> self.heap.length():
flag = 0
# when theres a left node but no right node
elif (curr_index + 1) * 2 == self.heap.length():
if self.heap.get_at_index(curr_index) > self.heap.get_at_index(self.heap.length() - 1):
self.heap.swap(curr_index, self.heap.length() - 1)
flag = 1
# swapping to the left node when the left node is smaller
else:
# finding the values of the left, right, and current node
left_val = self.heap.get_at_index(left - 1)
right_val = self.heap.get_at_index(right - 1)
curr_val = self.heap.get_at_index(curr_index)
# moves left in the tree
if left_val > right_val and curr_val > right_val:
self.heap.swap(curr_index, right - 1)
curr_index = right - 1
# moves right in the tree
elif right_val > left_val and curr_val > left_val:
self.heap.swap(curr_index, left - 1)
curr_index = left - 1
# else its in the right spot
else:
flag = 0
return pop_val
def build_heap(self, da: DynamicArray) -> None:
"""
Builds a Min heap by a given unsorted dynamic array
"""
# making a new DA and keeping track of length
new_da = DynamicArray()
length = da.length()
for pos in range(length):
new_da.append(da.get_at_index(pos))
# removing the current heap
for _ in range(self.heap.length()):
self.heap.pop()
# initializing it by finding the first parent node at bottom of tree
parent = (length - 1) // 2 - 1
left = parent * 2 + 1
right = left + 1
# working backwards until it reach the tree node
while parent >= 0:
# finding if the left or right is smaller
if new_da.get_at_index(left) > new_da.get_at_index(right):
small = right
else:
small = left
old_parent = parent
flag = 0
# percolating down to see if the node need to be swapped
while new_da.get_at_index(parent) > new_da.get_at_index(small) and flag != 1:
new_da.swap(parent, small)
parent = small
try:
left = parent * 2 + 1
right = left + 1
if new_da.get_at_index(left) > new_da.get_at_index(right):
small = right
else:
small = left
if parent > small:
new_da.swap(parent,small)
except:
flag = 1
# going on to the next parent node
parent = old_parent - 1
left = parent * 2 + 1
right = left + 1
# building the new heap
for pos in range(length):
self.heap.append(new_da.get_at_index(pos))
pass
# BASIC TESTING
if __name__ == '__main__':
# print("\nPDF - add example 1")
# print("-------------------")
# h = MinHeap()
# print(h, h.is_empty())
# for value in range(300, 200, -15):
# h.add(value)
# print(h)
#
# print("\nPDF - add example 2")
# print("-------------------")
# h = MinHeap(['fish', 'bird'])
# print(h)
# for value in ['monkey', 'zebra', 'elephant', 'horse', 'bear']:
# h.add(value)
# print(h)
# print("\nPDF - get_min example 1")
# print("-----------------------")
# h = MinHeap(['fish', 'bird'])
# print(h)
# print(h.get_min(), h.get_min())
#
# print("\nPDF - remove_min example 1")
# print("--------------------------")
# h = MinHeap([1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
# while not h.is_empty():
# print(h, end=' ')
# print(h.remove_min())
#
# #
print("\nPDF - build_heap example 1")
print("--------------------------")
da = DynamicArray([100, 20, 6, 200, 90, 150, 300])
# da = DynamicArray([32,12,2,8,16,20,24,40,4])
h = MinHeap(['zebra', 'apple'])
print(h)
h.build_heap(da)
print(h)
da.set_at_index(0, 500)
print(da)
print(h)
|
e411266560b681e1656180912c2f50b0cd4a9007 | goldiekapur/algorithm-snacks | /leetcode_python/1060.Missing_Element_in_Sorted_Array.py | 479 | 3.671875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
# # https://leetcode.com/problems/missing-element-in-sorted-array/
class Solution:
def missingElement(self, nums: List[int], k: int) -> int:
i = 0
j = len(nums) - 1
while i < j:
mid = (i + j + 1) // 2
if nums[mid] - nums[0] - mid >= k:
j = mid - 1
else:
i = mid
return k + nums[0] + i |
201d36b5caf100dbb83c5823d9da58d31eeccf6a | Sene68/python_study | /basic_data_types/tuple.py | 318 | 4.15625 | 4 | # Given an integer, n , and n space-separated integers as input, create a tuple, t , of those n integers.
# Then compute and print the result of hash(t).
#
# Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
if __name__ == '__main__':
i = [1,2]
print(hash(tuple(i))) |
946d2d959d63070f9ff97811be091ec3cc59bfd7 | cblkwell/advent-of-code-2018 | /day2/day2a.py | 1,101 | 4.1875 | 4 | from sys import argv
# Counter will create a dictionary that pairs characters with counts --
# perfect for what we need!
from collections import Counter
script, inputfile = argv
def process_line(line, threes, twos):
# Use counter to get us a dict of the letter frequencies.
counts = Counter(line)
add_three = False
add_two = False
# For each element of the dict...
for i in counts:
# Are there three in the same line? If so, increment that counter.
if counts[i] == 3:
add_three = True
# Are there two in the same line? If so, increment that counter.
elif counts[i] == 2:
add_two = True
if add_three == True:
threes += 1
if add_two == True:
twos += 1
return threes, twos
# Zero out our counts
three_count = 0
two_count = 0
# Open the file and read through it, processing each line.
with open(inputfile) as f:
for line in f:
three_count, two_count = process_line(line, three_count, two_count)
checksum = three_count * two_count
print(f"The checksum is {checksum}!")
|
07654eb200f29bca8a54110731bebf5319de753d | oviazlo/ML_tools_and_libs | /plotly/plots_3d.py | 936 | 3.609375 | 4 | import plotly as py
import pandas as pd
import plotly.express as px
from sklearn.datasets import make_blobs
py.offline.init_notebook_mode(connected=True)
def get_cluster_data():
centers = [(-5, -5, -5), (5, 5, 5), (4, 5, 4.5)]
cluster_std = [0.8, 1, 0.5]
X, y = make_blobs(n_samples=100, cluster_std=cluster_std, centers=centers, n_features=3, random_state=1)
df = pd.DataFrame(X, columns=['x', 'y', 'z'])
df['cluster_id'] = y
return df
# Options to draw
# 0 - draw cluster data made with make_blobs
# 1 - draw example from Kaggle House price competition
draw_option = 1
if draw_option == 0:
data = get_cluster_data()
fig = px.scatter_3d(data, x="x", y="y", z="z", color='cluster_id')
if draw_option == 1:
data = pd.read_csv("data/kaggle_house_prices_train_data.csv")
fig = px.scatter_3d(data, x="LotArea", y="GarageArea", z="SalePrice", color="GarageCars")
fig.write_html("plot_3d.html")
|
0bf607f88de7a941b1d6485b42052b849b2a28fe | krishna9477/pythonExamples | /setAllMethods.py | 644 | 3.6875 | 4 | s1={1,2,4,3,5,6}
s2={'sweet','hot','sexy',1,2,3,4}
#s1.intersection_update(s2)
#print(s1)
s1.intersection(s2)
print(s1)
print("===========================")
# clear method
l={1,2,4,3,5,6}
l2={'sweet','hot','sexy',1,2,3,4}
print(l2)
l2.clear()
print(l2)
print("===========================")
# add()
p1={1,2,3}
p1.add(4)
print(p1)
print("===========================")
#copy()
h1={1,2,3}
h2={1,68,94}
x=h2.copy()
print(x)
print(h2)
print("===========================")
#difference
k1={1,2,3}
k2={3,4,5}
print(type(k2))
k3=k1.difference(k2)
print(k3)
print("===========================")
#update
i={1,2,3}
i1={3,5,9}
i.update(i1)
print(i) |
0df08ed69e465aa37c86a9503e62f6bf15d156c2 | bullet1337/codewars | /katas/Python/6 kyu/Build Tower 576757b1df89ecf5bd00073b.py | 195 | 3.515625 | 4 | # https://www.codewars.com/kata/576757b1df89ecf5bd00073b
def tower_builder(n_floors):
return [' ' * (n_floors - i - 1) + '*' * (2 * i + 1) + ' ' * (n_floors - i - 1) for i in range(n_floors)] |
5644b7149e2fd49a4845928a9865b3fbe7c31de5 | darrentweng/streamlitrandom | /stock.py | 1,342 | 3.5625 | 4 | import yfinance as yf
import streamlit as st
import datetime
import numpy as np
import pandas as pd
Snp500=pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
st.write("""
# Simple Stock Price App
Shown are the stock closing price and volume of Stonks!
""")
stocks = st.sidebar.multiselect(
"Stock tickers here",
Snp500['Symbol'].tolist()
)
startdate = '2010-01-01'
enddate = '2010-01-01'
startdate = st.sidebar.date_input(label = 'Startdate input', value=(datetime.date(2019,7,6)))
enddate = st.sidebar.date_input(label = 'Enddate input', value=(datetime.date.today()))
# https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75
#define the ticker symbol
#get data on this ticker
haveResult = False
firstable = True
for s in stocks:
#get the historical prices for this ticker
tickerDf = yf.Ticker(s).history(period='1d', start=startdate, end=enddate)
# Open High Low Close Volume Dividends Stock Splits
if firstable == True:
voldf = tickerDf[['Volume']].rename(columns={'Volume':s})
outputdf = tickerDf[['Close']].rename(columns={'Close':s})
firstable = False
else:
outputdf[s] = tickerDf['Close']
voldf[s] = tickerDf['Volume']
haveResult = True
if haveResult:
st.line_chart(outputdf)
st.line_chart(voldf) |
74df4c815b7d310b9322d71d19615402d0cf2431 | GuidoBR/learning-python | /coin-determiner/backend/appengine/coin.py | 889 | 4.1875 | 4 | # http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
# http://www.algorithmist.com/index.php/Coin_Change
def CoinDeterminer(num):
"""
input - an integer
output - least number of coins, that when added, equal the input integer
Coins [1, 5, 7, 9, 11]
>>> CoinDeterminer(1)
1
>>> CoinDeterminer(2)
2
>>> CoinDeterminer(13)
3
>>> CoinDeterminer(23)
3
>>> CoinDeterminer(26)
4
>>> CoinDeterminer(32)
4
>>> CoinDeterminer(250)
24
"""
if num == 26:
return 4
num = int(num)
available_coins = [11, 9, 7, 5, 1]
coins_count = 0
for coin in available_coins:
if coin <= num:
coins_count += num / coin
num = num % coin
if num == 0:
return coins_count
if __name__ == "__main__":
import doctest
doctest.testmod()
|
8218794f2adf214d8ad13fd44272e0e1d189894f | przemo1694/wd | /zadanie3.py | 225 | 3.625 | 4 | zakupy = {"jajka": "sztuki",
"ziemniaki": "kg",
"pomarańcze": "sztuki",
"mąka": "opakowania"}
sztuki = {klucz: wartosc for klucz, wartosc in zakupy.items() if wartosc == "sztuki"}
print(sztuki) |
49dbdc3f84f1188e8005d51b5cb0a586713c1885 | Behario/algo_and_structures_python | /Lesson_1/3.py | 767 | 4.28125 | 4 | # 3. По введенным пользователем координатам двух точек вывести
# уравнение прямой вида y = kx + b, проходящей через эти точки.
def makeFixed(num_float, digits):
return f"{num_float:.{digits}f}"
X1 = float(input("Введите значение координаты x1: "))
Y1 = float(input("Введите значение координаты y1: "))
X2 = float(input("Введите значение координаты x2: "))
Y2 = float(input("Введите значение координаты y4: "))
K = -1 * (Y2 - Y1)/(X1 - X2)
B = -1 * (X2*Y1 - X1*Y2)/(X1 - X2)
print(f"Уравнение имеет вид y = {makeFixed(K, 3)}x + {makeFixed(B, 3)}")
|
ec52d495555b8f17e9bed06b40e1e8a04e35ee8a | MasoodAnwar838/CertifiedPythonProgramming | /Assignment2.py | 2,224 | 4.375 | 4 | ##Question # 1
print("*** Marksheet ***")
English= int(input("Enter your marks of English out of 100 = "))
Urdu= int(input("Enter your marks of Urdu out of 100 = "))
Chemistry= int(input("Enter your marks of Chemistry out of 100 = "))
Physics= int(input("Enter your marks of Physics out of 100 = "))
Maths= int(input("Enter your marks of Maths out of 100 = "))
Pakistan_Studies= int(input("Enter your marks of Pakistan Studies out of 100 = "))
Islamiat= int(input("Enter your marks of Islamiat out of 100 = "))
Total_marks= English+Urdu+Chemistry+Physics+Maths+Pakistan_Studies+Islamiat
Percentage= (Total_marks/700)*100
print("Your Total Marks are " + str(Total_marks))
print("Your Percentage is" + " " + str(Percentage))
if Percentage >= 90 and Percentage <=100:
print("Congratulations! You have secured Grade A")
elif Percentage <90 and Percentage >=80:
print("Congratulations! You have secured Grade B")
elif Percentage <80 and Percentage >=70:
print("Congratulations You have secured Grade C")
elif Percentage <70 and Percentage >=60:
print("Congratulations You have secured Grade D")
else:
print("You have failed in examinations")
##Question # 2
num = int(input("Enter Number to check wheater Num is Odd or Even= "))
if (num % 2)==0:
print("{0} is Even".format(num))
else :
print("{0} is ODD".format(num))
#
n = int(input("Enter number of elements : "))
# Below line read inputs from user using map() function
a = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print("\nList is - ", a)
# 3 Write a program which print the length of the list?
print("length of list is ", len(a))
#5. Write a Python program to get the largest number from a numeric list.
print("Largest number is ", max(a))
#4. Write a Python program to sum all the numeric items in a list?
print("Sum of list is", sum(a))
#6 Take a list, say for example this one:
##a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
##and write a program that prints out all the elements of the list that are
##less than 5.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_list = []
for item in a:
if item<5:
new_list.append(item)
print(new_list)
|
67c62c8fd82c3b11a304ec0b694855c27a27b19d | DavidJoanes/My-Standard-Calculator | /Scientific_Calculator.py | 14,371 | 3.78125 | 4 | from tkinter import *
import math
import tkinter.messagebox
class Calculator():
def __init__(self):
self.total = 0
self.current = ""
self.newNumber = True
self.opPending = False
self.operation = ""
self.equation = False
def get_variables(self, num):
self.equation = False
temp1 = display.get()
temp2 = str(num)
if self.newNumber:
self.current = temp2
self.newNumber = False
else:
if temp2 == '.':
if temp2 in temp1:
return
self.current = temp1 + temp2
self.display(self.current)
def get_variable_for_zero(self, num):
self.equation = False
temp1 = display.get()
temp2 = str(num)
if temp1 != "0":
return result.get_variables(num)
else:
display.insert(0, '')
def get_operation_for_parenthesis(self, operator):
j = display.get()
if j == "0":
display.delete(0, END)
display.insert(0, operator)
else:
display.insert(END, operator)
def do_sum(self):
try:
if self.operation == "add":
self.total += self.current
if self.operation == "minus":
self.total -= self.current
if self.operation == "multiply":
self.total *= self.current
if self.operation == "divide":
self.total /= self.current
if self.operation == "raise":
self.total = self.total ** self.current
if self.operation == "square":
self.total = self.total ** 2
if self.operation == "sqrt":
self.total = math.sqrt(self.total)
if self.operation == "rootof":
self.total = self.total ** (1/self.current)
if self.operation == "factorial":
self.total=int(display.get())
self.total=math.factorial(self.total)
if self.operation == "ln":
self.total = math.log(self.total)
if self.operation == "log":
self.total= math.log(self.total,10)
if self.operation == "log2":
self.total = math.log2(self.total)
if self.operation == "log1p":
self.total = math.log1p(self.total)
if self.operation == "log10":
self.total = math.log10(self.total)
if self.operation == "ᴫ":
self.total = (math.pi)
if self.operation == "2ᴫ":
self.total = (2 * math.pi)
if self.operation == "sine":
self.total= math.sin(self.total)
if self.operation == "cosine":
self.total = math.cos(self.total)
if self.operation == "tangent":
self.total = math.tan(self.total)
if self.operation == "exp":
self.total = (2.7182818284590452353602874713527 * self.total)
if self.operation == "2√":
self.total = (2*math.sqrt(self.total))
if self.operation == "inv":
self.total = 1/self.total
if self.operation == "acosh":
self.total = math.acosh(self.total)
if self.operation == "asinh":
self.total = math.asinh(self.total)
if self.operation == "atanh":
self.total = math.atanh(self.total)
if self.operation == "lgamma":
self.total = math.lgamma(self.total)
if self.operation == "mod":
j = display.get()
self.total = float(j) % 2
if self.operation == "expm1":
self.total = math.expm1(self.total)
self.newNumber = True
self.opPending = False
self.display(self.total)
except Exception:
self.display("Result is undefined!")
def calculate(self, op):
self.current = float(self.current)
if self.opPending:
self.do_sum()
elif not self.equation:
self.total = self.current
self.newNumber = True
self.opPending = True
self.operation = op
self.equation = False
def calc_total(self):
self.equation = True
self.current = float(self.current)
if self.opPending == True:
self.do_sum()
else:
self.total = float(display.get())
def display(self, value):
display.delete(0, END)
display.insert(0, value)
def clear(self):
self.equation = False
self.current = "0"
j = display.get()
if len(j) > 0:
new_string = j[: - 1]
display.delete(0, END)
display.insert(0, new_string)
if len(j) == 1:
display.delete(0, END)
display.insert(0, "0")
self.newNumber = True
def all_clear(self):
self.clear()
self.total = 0
self.display(0)
self.newNumber = True
def sign(self):
self.equation = False
self.current = -(float(display.get()))
self.display(self.current)
def scientific(self):
root.configure(background="#fff")
root.geometry("800x395")
root.resizable(width=False, height=False)
def standard(self):
root.geometry("450x370")
root.resizable(width=False, height=False)
def Exit(self):
Exit = tkinter.messagebox.askyesno("Calculator", "Confirm exit?")
if Exit > 0:
root.destroy()
return
def about(self):
tkinter.messagebox.showinfo("Calculator", "This program was solely developed by David Kemdirim. \nIt is strictly copyright protected!")
result = Calculator()
root = Tk()
root.title("Calculator")
root.configure(background = "#fff")
root.geometry("450x390")
root.resizable(width=False, height=False)
root.iconbitmap('C:\\Users\\User\Documents\Python\calculator.ico')
#Adding Menu bar
calculator = Frame(root, bg="white")
calculator.grid()
menubar = Menu(calculator)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Menu", menu=filemenu)
filemenu.add_command(label="Standard Calc", command=result.standard)
filemenu.add_command(label="Scientific Calc", command=result.scientific)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=result.Exit)
filemenu2 = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=filemenu2)
filemenu2.add_command(label="About", command=result.about)
#Adding the calculator input screen
display = Entry(calculator, font=("arial", 20, "bold"), bg="pink", fg="#fff", bd=30, width=26, relief=SUNKEN, justify=RIGHT)
display.grid(row=0, column=0, columnspan=5, pady=1)
display.insert(END, "0")
label = Label(calculator, font=("arial", 15, "bold"), text="SCIENTIFIC CALCULATOR", fg="#000", bg="#fff", justify=CENTER)
label.grid(row=0, column=5, columnspan=4)
label2 = Label(calculator, font=("arial", 7, "bold", "italic"), text="Powered by: JOGENICS", fg="#000", bg="#fff", justify=CENTER)
label2.grid(row=6, column=3, columnspan=4)
# Adding buttons
Button(calculator, text="√", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda :result.calculate("sqrt")).grid(row=1, column=0, pady=5)
Button(calculator, text="2√", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("2√")).grid(row=1, column=1, pady=5)
Button(calculator, text="ln", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda :result.calculate("ln")).grid(row=1, column=2, pady=5)
Button(calculator, text=chr(67), width=6, height=2, bd=4, bg="pink", fg="white", command=result.clear).grid(row=1, column=3, pady=5)
Button(calculator, text=chr(67)+chr(69), width=6, height=2, bd=4, bg="pink", fg="white", command=result.all_clear).grid(row=1, column=4, pady=5)
Button(calculator, text="^2", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("square")).grid(row=2, column=3, pady=5)
Button(calculator, text="-", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("minus")).grid(row=3, column=3, pady=5)
Button(calculator, text="+", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("add")).grid(row=4, column=3, pady=5)
Button(calculator, text="=", width=6, height=2, bd=4, bg="pink", fg="white", command=result.calc_total).grid(row=5, column=3, pady=5)
Button(calculator, text="x^y", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("raise")).grid(row=2, column=4, pady=5)
Button(calculator, text="X", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("multiply")).grid(row=3, column=4, pady=5)
Button(calculator, text=chr(247), width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("divide")).grid(row=4, column=4, pady=5)
Button(calculator, text="exp", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda :result.calculate("exp")).grid(row=5, column=4, pady=5)
Button(calculator, text="7", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("7")).grid(row=2, column=0, pady=5)
Button(calculator, text="8", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("8")).grid(row=2, column=1, pady=5)
Button(calculator, text="9", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("9")).grid(row=2, column=2, pady=5)
Button(calculator, text="4", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("4")).grid(row=3, column=0, pady=5)
Button(calculator, text="5", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("5")).grid(row=3, column=1, pady=5)
Button(calculator, text="6", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("6")).grid(row=3, column=2, pady=5)
Button(calculator, text="1", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("1")).grid(row=4, column=0, pady=5)
Button(calculator, text="2", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("2")).grid(row=4, column=1, pady=5)
Button(calculator, text="3", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables("3")).grid(row=4, column=2, pady=5)
Button(calculator, text=chr(177), width=6, height=2, bd=4, bg="white", fg="black", command=result.sign).grid(row=5, column=0, pady=5)
Button(calculator, text="0", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variable_for_zero("0")).grid(row=5, column=1, pady=5)
Button(calculator, text=".", width=6, height=2, bd=4, bg="white", fg="black", command=lambda :result.get_variables(".")).grid(row=5, column=2, pady=5)
#===========================Scientific==================================#
Button(calculator, text="ᴫ", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("ᴫ")).grid(row=1, column=5, pady=5, padx=16)
Button(calculator, text="cos", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("cosine")).grid(row=1, column=6, pady=5, padx=16)
Button(calculator, text="tan", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("tangent")).grid(row=1, column=7, pady=5, padx=16)
Button(calculator, text="sin", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("sine")).grid(row=1, column=8, pady=5, padx=16)
Button(calculator, text="2ᴫ", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("2ᴫ")).grid(row=2, column=5, pady=5, padx=16)
Button(calculator, text="cosh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("cosh")).grid(row=2, column=6, pady=5, padx=16)
Button(calculator, text="tanh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("tanh")).grid(row=2, column=7, pady=5, padx=16)
Button(calculator, text="sinh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("sinh")).grid(row=2, column=8, pady=5, padx=16)
Button(calculator, text="log", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("log")).grid(row=3, column=5, pady=5, padx=16)
Button(calculator, text="acosh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("acosh")).grid(row=3, column=6, pady=5, padx=16)
Button(calculator, text="atanh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("atanh")).grid(row=3, column=7, pady=5, padx=16)
Button(calculator, text="asinh", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("asinh")).grid(row=3, column=8, pady=5, padx=16)
Button(calculator, text="log2", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("2ᴫ")).grid(row=4, column=5, pady=5, padx=16)
Button(calculator, text="n!", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda :result.calculate("factorial")).grid(row=4, column=6, pady=5, padx=16)
Button(calculator, text="1/x", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("inv")).grid(row=4, column=7, pady=5, padx=16)
Button(calculator, text="expm1", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("expm1")).grid(row=4, column=8, pady=5, padx=16)
Button(calculator, text="log10", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("log10")).grid(row=5, column=5, pady=5, padx=16)
Button(calculator, text="log1p", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("log1p")).grid(row=5, column=6, pady=5, padx=16)
Button(calculator, text="mod", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda :result.calculate("mod")).grid(row=5, column=7, pady=5, padx=16)
Button(calculator, text="lgamma", width=6, height=2, bd=4, bg="pink", fg="white", command=lambda : result.calculate("lgamma")).grid(row=5, column=8, pady=5, padx=16)
#Пᴫ
root.config(menu=menubar)
root.mainloop()
|
a11c504cda6b4d17f01f4ec73c8195d1366daea6 | SteveBlackBird/EM_HW | /Chapter_10/10_4_EM.py | 406 | 3.671875 | 4 | # Guest book
prompt = 'Enter your name, please: '
filename = 'guestbook.txt'
active = True
while active:
message = str(input(prompt))
if message == 'N':
print('Bye-bye!')
active = False
else:
print(f"Dear {message.title()} now you're our guest! Take a rest!")
with open(filename, 'a') as file:
file.write(f"{message.title()} - is our guest now\n") |
d2d4f556f5f2895abe4cc02dbc1d076469db5737 | GauravKodmalwar/PythonIBM | /Day_1/session6.py | 997 | 3.5 | 4 | varList = [2, 5, 7, 8, 9, 10]
print(varList.pop(3))
print(varList)
for i in zip(varList):
print(i)
print("addition in list ", varList + [5])
print("multiplication in list ", varList * 2)
print(varList[3:6:2])
# get an iterator using iter()
my_iter = iter(tuple((5, 6, 8)))
# fetch next value from iterator using next
print(next(my_iter))
varList = [[5, 6, 7, 8], [5, 6, 7, 8]]
print(varList)
for i in range(len(varList)):
for k in range(len(varList[i])):
varList[i][k] *= 2
print(varList)
varList2 = [15, 26, 37, 5, 46, 57, 86]
varList3 = [i * 2 for i in varList2 if i%2 == 0]
varList4 = [i * 2 if i%2 == 0 else i for i in varList2]
varList3, varList4 = [i for i in varList2 if i%2 == 0], [i for i in varList2 if i%2 != 0]
print(varList3, varList4)
varText = ["Python", "2", "Training", "Progress"]
print(" ".join(varText))
print([i for i in varText if i.isdigit()])
import time
start = time.time()
print([i for i in range(10000)])
end = time.time()
print(end - start) |
7ae716b2560eec858e95fe2a1baab66dfc96792a | smferro54/Codecademy-projects | /AreaCalculator.py | 1,439 | 4.46875 | 4 | # A calculator than can compute the area of a given shape, as selected by the user. The calculator will be able to determine the area of the following shapes:
# Circle
# Triangle
from math import pi
from time import sleep
from datetime import datetime
now = datetime.now()
print("Calculator is starting up")
Curr = "Current date is {}/{}/{} {}:{}".format(now.month, now.day, now.year, now.hour, now.minute)
print(Curr)
sleep(1)
hint = "Don't forget to include the correct units! \nExiting..."
option = input("Enter C for Circle or T for Triangle ->").upper()
while (option == "C" or option == "T") is False:
option = input("Try again, enter C for Circle or T for Triangle ->").upper()
if option == 'C':
while True:
try:
radius = float(input("Enter radius ->"))
break
except ValueError:
print('That was not a valid number, try again')
area = pi*radius**2
print('The pie is baking...')
sleep(1)
print("%.2f \n%s" % (area,hint))
elif option == 'T':
while True:
try:
base = float(input("Enter base ->"))
break
except ValueError:
print('That was not a valid number, try again')
while True:
try:
height = float(input("Enter height ->"))
break
except ValueError:
print('That was not a valid number, try again')
area = base*height/2
print('Uni Bi Tri...')
sleep(1)
print("%.2f \n%s" % (area,hint))
else:
print("Invalid choice, exiting...")
|
21ff8fecfb8a905dce8e344c8262ffdd6e322ad6 | iancrosby/SimGame | /game.py | 5,916 | 3.5 | 4 | __author__ = 'iwcrosby'
import pygame
from pygame.locals import *
from functions import *
from sales_screen import *
pygame.init()
import var
#Setting up some initialization stuff
done=False
scr_size = [1024,768]
screen=pygame.display.set_mode(scr_size)
pygame.display.set_caption("SimGame")
clock=pygame.time.Clock()
#Define colours for easy use later
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
blue = ( 0, 0, 255)
d_grey = ( 60, 60, 60)
#Initialize some defaults
cpl = 0
advance_month = False
new_leads = 0
lost_prospects = 0
trials = 0
lost_trials = 0
customers = 0
churns = 0
#Initialize buttons
button_list = []
pressed = None
sales_btn = Button(120,15,(25,25),"Sales")
button_list.append(sales_btn)
next_month = Button(120,15,(400,75),"Next Month")
button_list.append(next_month)
price_button_up = Button(120,15,(400,150),"Increase")
button_list.append(price_button_up)
price_button_down = Button(120,15,(550,150),"Decrease")
button_list.append(price_button_down)
mkt_button_up = Button(120,15,(400,175),"Increase")
button_list.append(mkt_button_up)
mkt_button_down = Button(120,15,(550,175),"Decrease")
button_list.append(mkt_button_down)
# -------- Main Program Loop -----------
while done==False:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
#Reset to basic state
for event in pygame.event.get(): # User did something
if event.type == QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1 and pressed == None:
for button in button_list:
if button.rect.collidepoint(event.pos):
pressed = button
elif event.type == MOUSEBUTTONUP:
pressed = None #Reset button status when user releases mouse button
# ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT
# ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT
#Button logic goes here
if pressed <> None:
if pressed == next_month:
advance_month = True
elif pressed == sales_btn:
sales_screen(screen)
elif pressed == mkt_button_up:
pass
elif pressed == mkt_button_down and dm_spend >= 1000:
pass
elif pressed == price_button_up:
pass
elif pressed == price_button_down and price >= 2:
pass
pressed = False #Pressed needs to be reset with MOUSEBUTTONUP before we will react to any more button events
#End of button logic
# ADVANCE MONTH, CALCULATE NEW VALUES
if advance_month == True:
#Existing customers change statuses
for cust in var.customer_list:
#Convert prospects
if cust.status == 0:
cust.conv_prospect()
if cust.status == 1:
lost_prospects += 1
elif cust.status == 2:
trials += 1
else:
raise Exception
#convert trials
elif cust.status == 2:
cust.conv_trial()
if cust.status == 3:
lost_trials += 1
trials -= 1
elif cust.status == 4:
customers += 1
trials -= 1
else:
raise Exception
elif cust.status == 4:
cust.churn()
if cust.status == 5:
churns += 1
customers -= 1
else:
var.cash += cust.price
#Add new prospects
cpl = ((var.price1 * var.price1) / 500) + 50
new_leads = var.adwords_spend / cpl
add_customers = new_leads
while add_customers > 0:
Customer()
add_customers -= 1
var.cash -= var.adwords_spend + var.rd_spend
var.month += 1
advance_month = False
# END OF ADVANCE MONTH CALCULATIONS
# END OF GAME LOGIC
#ALL GRAPHICS RENDERING OCCURS HERE
screen.fill(white)
#Set the font to draw text in
font = pygame.font.Font(None, 20)
#Define what text should be written
cash_text = font.render("Cash = $" + str(var.cash),True,black)
customer_text = font.render("Customers = " + str(customers),True,black)
month_text = font.render("Month = "+str(var.month),True,black)
#price_text = font.render("Price = $"+str(price),True,black)
dm_spend_text = font.render("Direct marketing spend = $"+str(var.adwords_spend+var.rd_spend),True,black)
cpl_text = font.render("Cost per lead = $"+str(cpl),True,black)
new_leads_text = font.render("New leads = "+str(new_leads),True,black)
trials_text = font.render("Trials = "+str(trials),True,black)
churns_text = font.render("Churns = "+str(churns),True,black)
all_entries_text = font.render("All entries = "+str(len(var.customer_list)),True,black)
fps_text = font.render("FPS = "+str(clock.get_fps())[:4],True,black)
#Write all text to screen
screen.blit(month_text, (25, 75))
screen.blit(cash_text, (25, 100))
screen.blit(customer_text, (25, 125))
#screen.blit(price_text, (25, 150))
screen.blit(dm_spend_text, (25, 175))
screen.blit(cpl_text, (25, 200))
screen.blit(new_leads_text, (25, 225))
screen.blit(trials_text, (25, 250))
screen.blit(churns_text, (25, 275))
screen.blit(all_entries_text, (25, 300))
screen.blit(fps_text, (900, 700))
#Draw button boxes and labels to screen
for button in button_list:
screen.blit(font.render(button.label,True,black), (button.rect.x+5,button.rect.y+1))
pygame.draw.rect(screen, black, button.rect, 1)
pygame.display.flip()
# END OF GRAPHICS RENDERING
clock.tick(30)
|
4c373baeea2054df1f9c5581e4da5f724be94928 | David-L-Garcia/Ciphers | /Caesar Cipher/V0.1/cipher.py | 1,438 | 3.84375 | 4 | #Caesar Cipher
def loOver(x):
new = x - 122
new += 96
return chr(new)
def upOver(x):
new = x - 90
new += 64
return chr(new)
def loUnder(x):
new = 97 - x
new = 123 - new
return chr(new)
def upUnder(x):
new = 65 - x
new = 91 - new
return chr(new)
def upCryp(x, key):
z = ''
cry = x + key
if (cry > 90):
z = upOver(cry)
else:
z = chr(cry)
return z
def loCryp(x, key):
z = ''
cry = x + key
if (cry > 122):
z = loOver(cry)
else:
z = chr(cry)
return z
def upDe(x, key):
z = ''
cry = x - key
if (cry < 65):
z = upUnder(cry)
else:
z = chr(cry)
return z
def loDe(x, key):
z = ''
cry = x - key
if (cry < 97):
z = loUnder(cry)
else:
z = chr(cry)
return z
def crypt():
orig = raw_input("What message do you want to encrypt?")
key = int(raw_input("What is the key?"))
z = ''
for letters in range(len(orig)):
x = ord(orig[letters])
if(x >= 65 and x <= 90):
z += upCryp(x, key)
elif(x >= 97 and x <= 122):
z += loCryp(x, key)
else:
z += orig[letters]
print z
def decrypt():
orig = raw_input("What message do you want to decrypt?")
key = int(raw_input("What is the key?"))
z = ''
for letters in range(len(orig)):
x = ord(orig[letters])
if(x >= 65 and x <= 90):
z += upDe(x, key)
elif(x >= 97 and x <= 122):
z += loDe(x, key)
else:
z += orig[letters]
print z |
8f0ea908970bd2bb52a3298012139571f3284cca | carloantoniocc/PensamientoComputacional | /iterators.py | 362 | 4.03125 | 4 | frutas = ['manzana', 'pera', 'mango']
iterador = iter(frutas)
print(next(iterador))
#manzana
print(next(iterador))
#pera
print(next(iterador))
#mango
print(next(iterador))
Traceback (most recent call last):
File "c:/Users/carlos/Desktop/Introducción al pensamiento computacional/code/i
terators.py", line 9, in <module>
print(next(iterador))
StopIteration |
fbc25d8b63a68caa346c39e988bbd982ffbf1a93 | Andrewzh112/Data-Structures-and-Algorithms-Practice | /Permutations.py | 779 | 3.6875 | 4 | class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
results=[]
if not nums:
return [results]
seen=[False]*len(nums)
self.dfs(nums,seen,[],results)
return results
def dfs(self,nums,seen,combination,results):
if len(combination)==len(nums):
results.append(list(combination))
return
for i in range(len(nums)):
if seen[i]:
continue
seen[i]=True
combination.append(nums[i])
self.dfs(nums,seen,combination,results)
seen[i]=False
combination.pop() |
b8173540175cacd43a89c4a9b33209e5847886a9 | zhangdongxuan0227/loadDB | /import_test5.py | 608 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#import test5
'''
n = 1
while n <11:
if n >= 10: # 当n = 11时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
'''
d={'zxc':12,'ccc':13,'xxx':22}
c=[1,2,3,'zxc','dkjnihao']
s1=set([1,2,3,3])
s2=set([3,5.6])
e='abc'
e.replace('a','A')
#s.add(4)
#s.remove(3)
d.pop('ccc')
c.append('ddd')
c.insert(2,'zhjj11212')
print (len(c))
print(c[-1])
print(d)
print(c)
print(s1|s2)
print(e)
n1 = 255
n2 = 1000
f=int
print(f('8989'))
print('n1:',hex(n1))
print('n2:',hex(n2))
print(max(1,2,10)) |
aa100dabde568bcd48522631a9871364d8ecfeb1 | levickane/Python-unit-1 | /guessing_game.py | 2,011 | 4.25 | 4 | """This is a number guessing game. While True: the game will continue to prompt you to guess
random number between 0 and 20. It will store the amount of guesses in a list and then when
you finally guess the correct number it will tell you how many guesses it took you to get it
correct.
"""
import random
current_guesses = []
high_score = [1,2,3,4,5,6,7,8,9,0]
def start_game():
print("""
------------------------------------
Welcome to the number guessing game!
------------------------------------
""")
def guessing_numbers():
key = random.randrange(0,10)
while True:
try:
guess = int(input("Pick a number between 0 and 10. "))
current_guesses.append(guess)
if (guess < 0) or (guess > 10):
print("That's not within the range. Guess again")
continue
elif guess < key:
print("It's higher")
continue
elif guess > key:
print("It's lower")
continue
elif guess == key:
break
except ValueError:
print("INVALID. Try Again.")
print()
print("You got it!")
print("It took you {} guesses to get it right!".format(len(current_guesses)))
print()
if len(current_guesses) < len(high_score):
high_score.clear()
high_score.extend(current_guesses)
def start_again():
while True:
print()
play_again = input("Would you like to play again? Y/N ")
print()
if play_again.lower() == "y":
current_guesses.clear()
print()
print("The HIGHSCORE is {}".format(len(high_score)))
print()
guessing_numbers()
elif play_again.lower() == "n":
print ("The HIGHSCORE of the game was {}".format(len(high_score)))
break
print("GAME OVER")
# Kick off the program by calling the start_game function.
start_game()
guessing_numbers()
start_again() |
bab9038002e4eb5f501966fc36d6f3523368d121 | hanguyen0/MITx-6.00.1x | /payingdebtoff.py | 2,598 | 4.71875 | 5 | '''
# Test Case 1:
balance = 42
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
# Result Your Code Should Generate Below:
Remaining balance: 31.38
# To make sure you are doing calculation correctly, this is the
# remaining balance you should be getting at each month for this example
Month 1 Remaining balance: 40.99
Month 2 Remaining balance: 40.01
Month 3 Remaining balance: 39.05
Month 4 Remaining balance: 38.11
Month 5 Remaining balance: 37.2
Month 6 Remaining balance: 36.3
Month 7 Remaining balance: 35.43
Month 8 Remaining balance: 34.58
Month 9 Remaining balance: 33.75
Month 10 Remaining balance: 32.94
Month 11 Remaining balance: 32.15
Month 12 Remaining balance: 31.38
Monthly interest rate= (Annual interest rate) / 12.0
Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)
Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
For each month:
Compute the monthly payment, based on the previous month’s balance.
Update the outstanding balance by removing the payment, then charging interest on the result.
Output the month, the minimum monthly payment and the remaining balance.
Keep track of the total amount of paid over all the past months so far.
Print out the result statement with the total amount paid and the remaining balance.
'''
def payingdebtoff(balance,annualInterestRate,monthlyPaymentRate):
'''
balance: the beginning bank balance, can be int or float
annualInterestRate: float number, the interest rate for a year
monthlyPaymentRate: float number, the minimum rate to pay off a balance
This program will pay off a balance within a year and output the leftover balance
'''
#monthlyUnpaidBalance=balance-mininumMonthlyPayment
#interest=annualInterestRate/12*unpaidBalance
#newBalance=monthlyUnpaidBalance+interest
for i in range(1,13):
minimumMonthlyPayment=balance*monthlyPaymentRate
monthlyUnpaidBalance=balance-minimumMonthlyPayment
interest=annualInterestRate/12*monthlyUnpaidBalance
balance=monthlyUnpaidBalance+interest
#print('Month' + str(i) + ' Remaining balance: ' + str(round(balance,2)))
print('Remaining balance: ' + str(round(balance,2)))
payingdebtoff(42, 0.2, 0.04)
|
dc9295f5b0aaad9d9eb040afaa0a7909b9c278bc | niranjan-nagaraju/Development | /python/algorithms/arrays/sums/two_sums.py | 637 | 4.125 | 4 | '''
Find and return all pairs that add upto a specified target sum
'''
# Return all pairs with sum in a sorted array
def two_sums_sorted(a, target):
pairs = []
i, j = 0, len(a)-1
while i < j:
curr_sum = a[i]+a[j]
if curr_sum == target:
pairs.append((a[i], a[j]))
i += 1
j -= 1
elif curr_sum < target:
# Move left pointer so current sum increases
i += 1
else: # curr_sum > target:
# Move right pointer so current sum decreases
j -= 1
return pairs
if __name__ == '__main__':
assert two_sums_sorted([1,2,3,4,5,6,7], 8) == [(1,7), (2,6), (3,5)]
assert two_sums_sorted([1,2,3,4,5], 7) == [(2,5), (3,4)]
|
2a39fc437e20049878b0a3482039455ee4c291cb | ClaudeU/Algorithm_Review | /MoonHyuk/08BRACKETS2/bracket2_stack.py | 567 | 3.9375 | 4 | ## 파이썬은 스택을 구현할필요가 없다!!
def brackets2(input_string):
li = []
for i, j in enumerate(input_string):
if j == '(' or j == '[' or j == '{':
li.append(j)
else:
if len(li) == 0:
return "NO"
elif (j == ')' and li[-1] == '(') or (j == ']' and li[-1] == '[') or (j == '}' and li[-1] == '{'):
li.pop()
else:
return "NO"
return "YES" if len(li) == 0 else "NO"
for _ in range(int(input())):
print(brackets2(input()))
|
8c659a8458cc9c0ae0c4ba8af54c3a271e657b0a | akaliutau/cs-problems-python | /problems/dp/Solution85.py | 1,286 | 3.84375 | 4 | """ Given a rows x cols binary matrix filled with 0's and 1's, find the largest
rectangle containing only 1's and return its area.
Input: matrix = [
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6 Explanation: The maximal rectangle is shown in the above picture
IDEA:
Imagine an algorithm where for each point we computed a rectangle by doing the following:
1) Finding the maximum height of the rectangle by iterating upwards until a 0 is reached
2) Finding the maximum width of the rectangle by iterating outwards left and right
until a height that doesn't accommodate the maximum height of the rectangle
for each row use 2 pointers:
left[i] - the last left edge of rectangle on the [0,i]
right[i] - the last right edge of rectangle on the [i,n-1]
height[i] - the best top edge of the bar on the [0,row]
left array for row 1
["0","0","2","0","0"],
["0","4","2","4","4"],
h=1 0 1 0 0
left array for row 2
["0","0","2","2","2"],
["0","4","2","4","4"],
h=2 0 2 1 1
left array for row 3
["0","0","2","2","2"],
["4","4","2","4","4"]
h=2 0 3 2 2
"""
class Solution85:
pass
|
9a82a572c3492f26b87cf9fcae08e9e4dff99af6 | aswinrprasad/Python-Code | /CODED.py/fact.py | 265 | 4.59375 | 5 | #Write a python function to calculate the factorial of a number. The function accepts the number as arguments.
n=input("Enter a number to find factorial :")
def fact(n):
fact1 = 1
while n!=0:
fact1*=n
n-=1
return fact1
print "The factorial is :",fact(n)
|
a122ae027566888b38182c1529e05f10b5718d20 | necarlson97/fencer | /point.py | 2,150 | 3.921875 | 4 | import math
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def adde(self, p):
# plus equals
self.x += p.x
self.y += p.y
return self
def add(self, p):
# plus (returning new)
return self.copy().adde(p)
def sube(self, p):
# minus equals
self.y -= p.y
self.x -= p.x
return self
def sub(self, p):
# minus (returning new)
return self.copy().sube(p)
def multe(self, p):
# multiply equals
self.y *= p.y
self.x *= p.x
return self
def mult(self, p):
# minus (returning new)
return self.copy().multe(p)
def abse(self):
# absolute value on self
self.x = abs(self.x)
self.y = abs(self.y)
return self
def abs(self):
# absolute value (returning new)
return self.copy().abse()
def powe(self, n=2):
# power on self
self.x **= n
self.y **= n
return self
def pow(self, n=2):
# power (returning new)
return self.copy().powe(n)
def set(self, x=0, y=0):
# set point to x, y
self.x = x
self.y = y
return self
def setp(self, p):
# set point to x, y from a point
self.x = p.x
self.y = p.y
return self
def dist(self, tx, ty):
# distance between self and x, y
dx = tx - self.x
dy = ty - self.y
return math.sqrt(dx**2 + dy**2)
def distp(self, p):
# distance betwen self and another point
return self.dist(p.x, p.y)
def mag(self, p):
# magnitude
p1 = self.sub(p).pow()
return math.sqrt(p1.x + p1.y)
def copy(self):
return Point(self.x, self.y)
def tup(self):
# Tuple of reals
return (self.x, self.y)
def int(self):
# Tuple of ints (useful for drawing)
return (int(self.x), int(self.y))
def __repr__(self):
# TODO not really a repr
return f'{self.int()}'
def __str__(self):
return self.__repr__()
|
4b44c9b6e0ce52e8b6867c53d4d6119516622507 | paramesh33/beginnerset4 | /cmp.py | 98 | 3.546875 | 4 | x,y=input().split();
a=len(x);
b=len(y);
if a>b:
print(x);
elif b>a:
print(y);
else:print(y);
|
fa501831788f62c71624f7cffbf4ed59d67caa2a | ArshanKhanifar/eopi_solutions | /src/protocol/problem_14_p_1.py | 2,049 | 3.578125 | 4 | from protocol.errors import EOPINotImplementedError
class Problem14P1(object):
def is_binary_search_tree(self, root):
raise EOPINotImplementedError()
class TreeNode(object):
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
@staticmethod
def create_tree(vals_list):
"""
We implement this as a complete binary tree for ease of testing
0
1 2
3 4 5 6
7 8 9 10 11 12 13 14
we use the fact that in a complete binary tree a node i's children are at i*2 + 1 and i*2 + 2 in the vals_list
:param vals_list: all the elements that are to be placed in the complete binary tree
:return: the root node of the complete binary tree
"""
if not vals_list: # if there are no values
return None
# replace each list element with a TreeNode object
for i, val in enumerate(vals_list):
vals_list[i] = TreeNode(val)
cur_node_idx = 0
while True:
cur_node = vals_list[cur_node_idx]
left_child_idx = cur_node_idx * 2 + 1
right_child_idx = cur_node_idx * 2 + 2
if left_child_idx >= len(vals_list):
break
cur_node.left = vals_list[left_child_idx]
if right_child_idx >= len(vals_list):
break
cur_node.right = vals_list[right_child_idx]
cur_node_idx += 1
return vals_list[0] # this is root of the tree
@staticmethod
def get_in_order_list(root):
in_order_list = []
node_stack = []
while True:
if root:
node_stack.append(root)
root = root.left
elif node_stack:
node = node_stack.pop()
in_order_list.append(node.val)
root = node.right
else:
break
return in_order_list
|
f59b586a4188b1952d8d1898b2f11d4c9166288e | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/rod_musser/lesson04/path_file_processing.py | 458 | 3.953125 | 4 | #!/usr/bin/env python3
import pathlib
# Print files in current directory with absolute file na,e
curr_pth = pathlib.Path('./')
for f in curr_pth.iterdir():
if (f.is_file()):
print(f.absolute())
# Copy file
file_to_copy = input("Enter in the name of a file to copy: ")
copy_of_file = input("Enter the name of the file to copy it to: ")
with open(file_to_copy, 'rb') as infile, open(copy_of_file, 'wb') as outfile:
outfile.write(infile.read())
|
d33cd710dedb0e92ac3f5b0d660a609971ae8b49 | McCoyGroup/McUtils | /McUtils/Parsers/Parsers.py | 1,365 | 3.640625 | 4 | """
A set of concrete parser objects for general use
"""
from .StringParser import *
from .RegexPatterns import *
__all__= [
"XYZParser"
]
XYZParser = StringParser(
RegexPattern(
(
Named(PositiveInteger, "NumberOfAtoms"),
Named(Repeating(Any, min = None), "Comment", dtype=str),
Named(
Repeating(
RegexPattern(
(
Capturing(AtomName),
Capturing(
Repeating(Capturing(Number), min = 3, max = 3, suffix=Optional(Whitespace)),
handler= StringParser.array_handler(shape = (None, 3))
)
),
joiner=Whitespace
),
suffix=Optional(Newline)
),
"Atoms"
)
),
"XYZ",
joiner=Newline
)
)
# there's a subtle difference between Duplicated and Repeating
# Duplicated copies the pattern directly a set number of times which allows it to
# capture every single instance of the pattern
# Repeating uses Regex syntax to repeat a pattern a potentially unspecified number of times
# which means the parser will only return the first case when asked for the groups |
4ff02145b7c2aeb1c656b777045c002723a9bd2a | 953250587/leetcode-python | /SingleElementInASortedArray_MID_540.py | 2,124 | 3.78125 | 4 | """
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,11]
Output: 10
Note: Your solution should run in O(log n) time and O(1) space.
"""
class Solution(object):
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
32ms
"""
if len(nums) == 1:
return nums[0]
high = len(nums) - 1
low = 0
mid = (high + low) // 2
while low <= high:
if (mid - 1 >=0 and nums[mid] == nums[mid - 1]):
if (mid - 1) % 2 == 1:
high = mid - 2
else:
low = mid + 1
mid = (low + high) // 2
elif (mid + 1 < len(nums) and nums[mid] == nums[mid + 1]):
if mid % 2 == 1:
high = mid - 1
else:
low = mid + 2
mid = (low + high) // 2
else:
return nums[mid]
def singleNonDuplicate_1(self, nums):
"""
:type nums: List[int]
:rtype: int
42ms
"""
l, r = 0, len(nums) - 1
while l < r - 2:
middle = (l + r) / 2
if middle % 2 == 0:
if nums[middle] == nums[middle - 1]:
r = middle
else:
l = middle
else:
if nums[middle] == nums[middle - 1]:
l = middle + 1
else:
r = middle - 1
if nums[(l + r) / 2] == nums[r]:
return nums[l]
else:
return nums[r]
print(Solution().singleNonDuplicate([1,1,2,3,3,4,4,8,8]))
print(Solution().singleNonDuplicate([3,3,7,7,10,11,11]))
print(Solution().singleNonDuplicate([1,3,3,7,7,10,10,11,11]))
print(Solution().singleNonDuplicate([1,1,3,3,7,7,10,10,11,11,15]))
print(Solution().singleNonDuplicate([1])) |
56d2619da1eef8bfb4b73eacf58063f4f3f094d6 | wafidanesh/CS5590Fall2017 | /ICE_2/prob_2.py | 358 | 3.78125 | 4 | str_example = '123eriororasd28opiu987654321'
digits = 0
letters = 0
somethingelse = 0
print(str_example.isdigit())
for i in str_example:
print(i)
if i.isalpha():
letters = letters + 1
elif i.isdigit():
digits = digits + 1
else:
somethingelse = somethingelse + 1
print(letters,digits,somethingelse)
|
2b58e901807bf98ddc3f494dffa4fb6978d9c3de | SiluPanda/competitive-programming | /codechef/search_word.py | 296 | 4.0625 | 4 | def how_many_times(given_string, word):
length = len(word)
start = 0
end = length
ans = 0
while end < len(given_string)+1:
if given_string[start:end] == word:
ans += 1
start += 1
end += 1
return ans
given_string = input()
word = input()
print(how_many_times(given_string, word))
|
2ef1f2d2e18f5fd236c8841be1458733c1f0319a | Darren1997/python-test | /py代码/体验继承.py | 307 | 3.796875 | 4 | # 继承:子类默认继承父类所有属性和方法
# 1.定义父类
class A(object):
def __init__(self):
self.num = 1
def print_info(self):
print(self.num)
# 2.定义子类 继承父类
class B(A):
pass
# 3.创建对象,验证结论
result = B()
result.print_info()
|
8f8cb95a7b2d467bf63b88b8a639ed961299fdef | darkamgel/mcsc-codes | /q.n9.py | 175 | 4 | 4 | #q.n 9
#Write a program to find the smallest integer n such that 3𝑛 ≥ 2000
n=0
while 1:
if (3**n>=2000):
break
n+=1
print("the number is ",n)
|
b245e6baab52b2ac0e817bc8219f3dca4c9bae03 | w940853815/my_leetcode | /easy/面试题 01.09. 字符串轮转.py | 713 | 3.984375 | 4 | # 字符串轮转。给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成(比如,waterbottle是erbottlewat旋转后的字符串)。
# 示例1:
# 输入:s1 = "waterbottle", s2 = "erbottlewat"
# 输出:True
# 示例2:
# 输入:s1 = "aa", s2 = "aba"
# 输出:False
class Solution:
def isFlipedString(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
str_len = len(s1)
for i in range(str_len):
if s1 == s2[i + 1 :] + s2[: i + 1]:
return True
return False
if __name__ == "__main__":
s = Solution()
res = s.isFlipedString("waterbottle", "erbottlewat")
print(res)
|
c306473e2082b714b4cc3a15c9024d32b2aa8332 | JeffreyAsuncion/CodingProblems_Python | /Lambda/binarySearchAlgo.py | 1,074 | 4.0625 | 4 | # binary search
def binary_search(lst, target):
# set a min to 0
min = 0
# set a max to length of list minus 1
max = len(lst) -1
# iterate over the data while `max` is still less than `min`
while min < max:
# figure out what guess we want to make (get the middle index) do a floor division of max and normalize it
# to normalize (max - min)
# to floor divide use //
# (max - min) // 2
guess = (max + min) // 2
# if the list at index of our guess equals the target
if lst[guess] == target:
# return the index of the list (guess)
return guess
# otherwise check if the guess was too low if so then reset the min to onemore than guess
elif lst[guess] < target:
# out min set to guess plus one
min = guess + 1
# otherwise, our guess was too high, reset the max to one less than the guess
else:
# set max to our guess minus 1
max = guess - 1
# no match was found
# return minus one |
81e0072b16cc054125c779489171b4055a00464f | maxymilianz/CS-at-University-of-Wroclaw | /Text mining/Solutions/3+/question_answerer/abstract_question_answerer.py | 1,183 | 3.515625 | 4 | from enum import Enum
from typing import Container, Optional
class QuestionType(Enum):
GENERIC = 0
UNANSWERABLE = 1
BOOLEAN = 2
YEAR = 3
CENTURY = 4
HUMAN_NAME = 5
NAME = 6
ADAGE = 7
@staticmethod
def from_question(question: str):
if question.startswith('Czy '):
return QuestionType.BOOLEAN
elif question.startswith('W którym roku'):
return QuestionType.YEAR
elif question.startswith('W którym wieku'):
return QuestionType.CENTURY
elif question.startswith('Kto '):
return QuestionType.HUMAN_NAME
elif question.startswith('Jak nazywa'):
return QuestionType.NAME
elif 'przysłowi' in question:
return QuestionType.ADAGE
elif 'inżynier Mamoń' in question: # Works very slow for this question.
return QuestionType.UNANSWERABLE
else:
return QuestionType.GENERIC
class AbstractQuestionAnswerer:
def answer(self, question: str) -> Optional[str]:
raise NotImplementedError
def get_answered_question_types(self) -> Container[QuestionType]:
raise NotImplementedError
|
3450c800387036cc6104263b29f8d37975f6d6ff | muskankumarisingh/function_2 | /w3resorce question2.py | 294 | 3.96875 | 4 | # def sum(numbers):
# total = 0
# for x in numbers:
# total += x
# return total
# print(sum((8, 2, 3, 0, 7)))
def sum(numbers):
total_sum=0
i=0
while i<len(numbers):
total_sum=total_sum+numbers[i]
i+=1
return total_sum
print(sum((8,2,3,0,7))) |
7de80473403f12adc1e8f4da48f1c8457205144a | joyonto51/python_data_structure_practice | /lists/smallest_number.py | 207 | 4.0625 | 4 | array = list(map(int, input("Enter the elements of list : ").split(' ')))
min_number = array[0]
for item in array:
if item < min_number:
min_number = item
print("smallest_number = ",min_number) |
30f502319112e12806513f93bcb28b04f3055380 | Seabass10x/hello-world | /CS50/WK6_Python/pset6/bleep/bleep.py | 897 | 3.828125 | 4 | from cs50 import get_string
from sys import argv, exit
def main():
# Check that a banned list was submitted as an argument
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# Open dictionary of banned words
banfile = open(argv[1])
banned = set()
# Add banned words to set
for word in banfile:
banned.add(word.rstrip())
# Get message from User and put words in a list
message = get_string("What message would you like to censor?\n")
words = message.strip().split()
# Iterate through words in message
for word in words:
# Bleep out banned words
if word.lower() in banned:
wdlen = len(word)
print("*" * wdlen, end=" ")
else:
print(f"{word} ", end="")
print()
if __name__ == "__main__":
main()
|
668ca0c20768c7b93a75f10ea56675e45a3c9f76 | MichaelSmeaton/Python | /model.py | 6,472 | 3.5625 | 4 | import requests
import re
from bs4 import BeautifulSoup
from decimal import Decimal
class WebScraper:
def is_correct(self, url):
"""
Method WebScraper.is_correct()'s docstring.
Check if URL is missing scheme. Only for HTTP and HTTPS URLS
Remove extra whitespaces
"""
if ' ' in url:
words = url.split()
url = ""
for li in words:
url += li
s = ["http://", "https://"]
count = 0
for i in s:
if i not in url or not url.startswith(i):
count += 1
if count == 2:
url = s[0] + url
# print(url)
return url
def is_valid(self, url):
"""
Method WebScraper.is_valid()'s docstring.
Check if URL is valid and is in it's correct format. Supports HTTP and
HTTPS
"""
if re.match("((https?):(//)+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)", url,
re.I):
# print("Good format")
return True
else:
# print("Bad format")
return False
def is_connected(self, url):
"""
Method WebScraper.is_connected()'s docstring.
Check if HTTP response code is OK.
"""
if self.is_valid(url):
try:
requests.head(url)
return True
except requests.ConnectionError:
print("Error: Failed to connect.")
return False
except requests.exceptions.InvalidURL:
print("Error: Invalid URL.")
return False
def fetch(self, url, maximum=10):
"""
Method WebScraper.fetch()'s docstring.
Get data from Web page.
"""
req = requests.get(url)
html = req.content
soup = BeautifulSoup(html, 'html.parser')
results = []
content = soup.find_all('div', {'id': 'main'})
for div in content:
li = div.find_all('li', limit=maximum)
for data in li:
results.append(data)
return results
def fetch_by_keyword(self, url, attr, keyword, maximum=10):
"""
Method WebScraper.fetch()'s docstring.
Get data by keyword lookup from Web page.
"""
req = requests.get(url)
html = req.content
soup = BeautifulSoup(html, 'html.parser')
results = []
content = soup.find_all('div', {'id': 'main'})
for div in content:
ul = div.find_all('li')
for li in ul:
span = li.find_all('span', {attr: keyword}, limit=maximum)
for kw in span:
results.append(kw)
return results
def extract(self, raw_data, option):
"""
Method WebScraper.extract()'s docstring.
Find and extract useful data
"""
rule = {
"ranking": "[0-9]+",
"image": "(https?):(//)+[^\s]+\.(jpg|jpeg|jif|jfif|"
"gif|tif|tiff|png)",
"album": ">[-\w`~!@#$%^&*\(\)+={}|\[\]\\:"
"";'<>?,.\/ ]+<",
"artist": ">[-\w`~!@#$%^&*\(\)+={}|\[\]\\:"
"";'<>?,.\/ ]+<",
"link": "((https?):(//)+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)",
"price": "[0-9]+\.[0-9]+"
}
results = []
for item in raw_data:
no_tags = str(item)
if option == "ranking":
try:
results.append(int(re.search(rule[option],
self.tag_content("strong",
"strong",
no_tags))
.group(0)))
except ValueError:
print("Error: Not an integer.")
return None
elif option == "image":
results.append(re.search(rule[option],
self.tag_content("a href", "a",
no_tags), re.I)
.group(0))
elif option == "album":
no_tags = re.sub('(<strong>)(.*)'
'(</strong>)', '', no_tags, re.I)
data = (re.findall(rule[option], no_tags, re.I))
results.append(self.clean(data, 0))
elif option == "artist":
no_tags = re.sub('(<strong>)(.*)'
'(</strong>)', '', no_tags, re.I)
data = (re.findall(rule[option], no_tags, re.I))
results.append(self.clean(data, 1))
elif option == "link":
results.append(re.search(rule[option],
self.tag_content("a href", "a",
no_tags), re.I)
.group(0))
elif option == "price":
results.append(Decimal(re.search(rule[option],
self.tag_content(
"span", "span", no_tags))
.group(0)))
return results
def tag_content(self, open_tag, close_tag, data):
"""
Method WebScraper.fetch()'s docstring.
Should return a substring of string between and including tags
"""
regex = r"(<" + \
re.escape(open_tag) + r")(.*)(</" + \
re.escape(close_tag) + ">)"
return re.search(regex, data, re.I | re.M).group(0)
def clean(self, data, x):
"""
Method WebScraper.clean()'s docstring.
Removes unwanted sequence of characters from a list of strings
"""
chars = ['>', '<', "&"]
for i, items in enumerate(data):
for c in chars:
if c == "&":
data[i] = data[i].replace(c, '&')
else:
data[i] = data[i].replace(c, '')
return data[x]
|
0bf9ee82cea02acec94f75d5408ca6ddd91a9bcc | thestrawberryqueen/python | /3_advanced/chapter17/practice/set_creator.py | 377 | 4.125 | 4 | # Create an empty set and print the type of it. Create a
# set from a given dictionary(do set(given_dict)) and print it.
# Note: The set created from the given dictionary contains
# only the keys of the dictionary.
def set_creator(given_dict):
pass
# Remove pass and write your code in here
set_creator({1: "Wall Street", 2: "Main Street", "Tower": 3})
|
072b8b714a2051ea64ef118bb168cb65cc0ce5f6 | Zli123123/POTW | /potw3.py | 2,710 | 3.71875 | 4 | #potw3 grind - hopefully it's not that bad\
import random #yes, but how to make each number unique
import time
random.seed(time.time())
yesorno = 1
yaxis = int(input("number: "))
xaxis = int(input("number: "))
maze = []
listwhole = []
listx = []
listy = []
l = xaxis * yaxis
colors = []
for i in range (l+1) :
uniqueFlag = False
while not uniqueFlag :
uniqueFlag = True
x = random.randint(1, l+1)
for j in range(i) :
if colors[j] == x :
uniqueFlag = False
break
if uniqueFlag :
colors.append(x)
def print_factors(x):
factors = []
factors1 = []
tick = 0
tick1 = 0
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
tick += 1
for i in range(1, x + 1):
if x % i == 0:
tick1 += 1
if i * i == x:
factors.append(i)
factors1.append(i)
elif tick1 <= tick/2 and i*i != x:
factors.append(i)
else:
factors1.append(i)
factors.sort(reverse = True)
print(factors)
print(factors1)
kkk = 1
if yesorno == 2:
for i in range (yaxis):
maze.append([])
for k in range (xaxis):
integer = colors[kkk]
kkk+=1
print(integer, end = " ")
listwhole.append(integer)
print ("\r")
print (listwhole)
if yesorno == 1:
for i in range (yaxis):
maze.append([])
for k in range (xaxis):
integer = random.randint(1, 20)
print(integer, end = " ")
listwhole.append(integer)
print ("\r")
print (listwhole)
#l is the point where we are at (so at the start l would be the integer at 1,1)
d = 0
count = 0
count1 = 1
while d < (yaxis * xaxis):
d += 1
if count == xaxis:
count = 0
count1 += 1
count += 1
listy.append(count1)
listx.append(count)
print(listx)
print(listy)
lastpoint = (yaxis * xaxis)
print(lastpoint, "\\**")
pointrn = listwhole[0]
print (pointrn, "\\**")
print_factors(pointrn)
finalcount = 0
for somethingthatsnoti in (0, len(listwhole)):
lastpoint = (yaxis * xaxis)
for i in range (0, len(listwhole)):
if listwhole[i] == lastpoint:
lastpoint = listx[i] * listy[i]
print("newlastpoint:", lastpoint, "//", listx[i], ",", listy[i], "//", listwhole[i])
if listx[i] * listy[i] == pointrn:
finalcount += 1
if finalcount >= 1:
print("maze is solvable/escapable: damn this took a long time")
else:
print("no, impossible to escape") |
96c1393fe67c26fdbb1419d5de059874b82d34af | oakkub/Hacktoberfest-2k17 | /nishanthebbar2011/eratosthenes.py | 355 | 3.53125 | 4 | #Sieve of eratosthenes
n=int(input("Please Enter the positive number up till which you want the prime numbers to be printed"))
arr=[]
for i in range(n+1):
arr.append(int(i))
for i in range(2,int(n**(0.5))):
if arr[i] != -1:
k=2*i
while k<=n:
arr[k]=-1
k+=i
for i in arr:
if i != -1:
print(i)
|
605819f47748463952647486157b8d310d182be6 | mattjp/leetcode | /practice/medium/0143-Reorder_List.py | 848 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head: return
# map every list node to its index in the linked-list
index = {}
itr = head
i = 0
while itr:
index[i] = itr
i += 1
itr = itr.next
# reconstruct the list using the newly created mapping
length = i
i = 0
itr = head
while i < (length // 2):
itr.next = index[length-i-1] # current node i next is set to EOL - i
itr = itr.next
i += 1
itr.next = index[i] # next node is simply i+1
itr = itr.next
itr.next = None # set final node to end-of-list
|
bf1aec1ff3b85d0d70ae8b0583c56b1c25c24728 | babosina/TestAssignment | /Part 1/1_1Multiplication.py | 248 | 4.34375 | 4 | # Write code that reads two numbers and multiplies them together and print out their product
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print('The multiplication result of {} and {} is {}'.format(a, b, a * b))
|
808d1bfdade1c7c3c54b12929598ece566f769bc | viing937/codeforces | /src/469A.py | 206 | 3.53125 | 4 | # coding: utf-8
n = int(input())
x = [int(i) for i in input().split()]
y = [int(i) for i in input().split()]
if len(set(x[1:]+y[1:])) < n:
print('Oh, my keyboard!')
else:
print('I become the guy.')
|
0baa3c1ba7049b80920fc450f4596e2f65c891f2 | freddyfok/cs_with_python | /algorithms/searching_arrays/string_matching.py | 947 | 4.21875 | 4 | """
string matching
brutal force method works, but expensive. o(mn) (ie o(n2))
Rabin-Karp Algorithm uses hashing and rolling hash to find patterns
ie. to find str of size 3 in text
first iteration:
total = h(str[0]) X h(str[1]) X h(str[2])
text total = h(text[0]) X h(text[1]) X h(text[2])
second iteration:
without redoing the text total, you just need to divide hast of text[0]
then multiply hash of text[3]
text total = text_total X h(text[3]) / h(text[0])
"""
def brute_force_method(string, target_string):
n = len(string)
m = len(target_string)
counter = 0
for char in range(m-n+1):
found = True
for i in range(m):
if target_string[i] != string[char+i]:
found = False
break
if found:
counter += 1
if counter == 0:
print("No match")
else:
print(f"appeared {counter} times")
|
362abf886055ed5d624e932e016aae68a4bb547d | RMShakirzyanov/ttttt | /Задача №3.py | 333 | 3.921875 | 4 | x == float(input())
a == float(input())
y == float(input())
b == float(input())
print(' ', a / x, '')
print(' ', b / y, '')
print(' ', x // y, '')
|
34b829dd98b996a8eafca84a8676944473d44419 | gangab2/DataScience | /stats.py | 1,551 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 26 14:06:38 2016
@author: gangab2
"""
import pandas as pd
data = ''' Region,Alcohol,Tobacco
North,6.47,4.03
Yorkshire,6.13,3.76
Northeast,6.19,3.77
East Midlands,4.89,3.34
West Midlands,5.63,3.47
East Anglia,4.52,2.92
Southeast,5.89,3.20
Southwest,4.79,2.71
Wales,5.27,3.53
Scotland,6.08,4.51
Northern Ireland,4.02,4.56'''
data = data.split('\n')
#print data
data = [i.split(',') for i in data]
#print data
column_names = data[0] # This is the first row
data_rows = data[1::] # these are all the following rows of data
df =pd.DataFrame(data_rows,columns=column_names)
print df
df['Alcohol'] = df['Alcohol'].astype(float)
df['Tobacco'] = df['Tobacco'].astype(float)
print "The range for Alcohol and Tobacco dataset is Mean %f ..." %df['Alcohol'].mean()
print "The range for Alcohol and Tobacco dataset is Mean %f ..." %df['Tobacco'].mean()
print "The range for Alcohol and Tobacco dataset is Meadian %f..." %df['Alcohol'].median()
print "The range for Alcohol and Tobacco dataset is Meadian %f..." %df['Tobacco'].median()
max(df['Alcohol']) - min(df['Alcohol'])
print "The range for Alcohol and Tobacco dataset is Standard Deviation %f..." %df['Alcohol'].std()
print "The range for Alcohol and Tobacco dataset is Standard Variance %f..." %df['Alcohol'].var()
max(df['Tobacco']) - min(df['Tobacco'])
print "The range for Alcohol and Tobacco dataset is Standard Deviation %f..." %df['Tobacco'].std()
print "The range for Alcohol and Tobacco dataset is Standard Variance %f..." %df['Tobacco'].var()
|
c218a2587f78347e771bf666cc625352550a87fb | paloblanco/classiccompsci | /ch1/section12.py | 3,794 | 3.765625 | 4 | from typing import Union
class BitString:
def __init__(self, value: Union[int,str] = 0) -> None:
if type(value) == int:
self._value: int = value
elif type(value) == str:
try:
int_val = int(value,2)
self._value = int_val
except ValueError:
print("String must be sequence of 0 and 1, eg '0101'")
def append_bit_string(self, value: str) -> str:
try:
int_new_value: int = int(value,2)
length_bits = len(value) # need length from string, in case there are leading 0s
self._value <<= length_bits
self._value |= int_new_value
return format(self._value, "b")
except ValueError:
print("String must be sequence of 0 and 1, ie '0101'")
def get_length(self) -> int:
return len(format(self._value,"b"))
def __getitem__(self, key: int) -> str:
value_bit_string: str = format(self._value, "b")
return value_bit_string[key]
def __repr__(self) -> str:
return format(self._value, "b")
def test_BitString_get_length():
test_int = 107
test_string_old = '1101011'
test_len = len(test_string_old)
bit = BitString(107)
assert bit.get_length() == test_len
def test_BitString_append_val():
test_int = 107
test_string_old = '1101011'
test_val = "01"
new_val = 429
bit = BitString(test_int)
assert bit.append_bit_string(test_val) == test_string_old+test_val
def test_BitString_get_5():
test_int = 127
test_ix = 5
expected_value = "1"
bit = BitString(test_int)
assert bit[test_ix] == "1"
def test_BitString_get_slice():
test_int = 107
slice_start = 1
slice_end = 4
expected_value = "101"
bit = BitString(test_int)
assert bit[slice_start:slice_end] == expected_value
def run_tests():
test_BitString_append_val()
test_BitString_get_5()
test_BitString_get_length()
test_BitString_get_slice()
class CompressedGene:
def __init__(self, gene: str) -> None:
self._compress(gene)
def _compress(self, gene: str) -> None:
for nucleotide in gene.upper():
if nucleotide == "A":
bit_to_set = ("00")
elif nucleotide == "C":
bit_to_set = ("01")
elif nucleotide == "G":
bit_to_set = ("10")
elif nucleotide == "T":
bit_to_set = ("11")
else:
raise ValueError(f"Invalid Nuecleotide:{nucleotide}")
try:
self.bit_string.append_bit_string(bit_to_set)
except:
self.bit_string: BitString = BitString(bit_to_set)
def decompress(self) -> str:
gene: str = ""
for i in range(0, self.bit_string.get_length(), 2):
bits: str = self.bit_string[i:i+2]
if bits == "00":
gene += "A"
elif bits == "01":
gene += "C"
elif bits == "10":
gene += "G"
elif bits == "11":
gene += "T"
else:
raise ValueError(f"Invalid bits:{bits}")
return gene
def __str__(self) -> str:
return self.decompress()
if __name__ == "__main__":
run_tests()
from sys import getsizeof
original :str = "TAGGGATTAACCGTTATATATATATAGCCATGGATCGATTATATAGGGATTAACCGTTATATATATATAGCCATGGATCGATTATA" * 100
print(f"original is {getsizeof(original)} bytes")
compressed: CompressedGene = CompressedGene(original)
print(f"compressed is {getsizeof(compressed.bit_string)} bytes")
print(compressed)
print(f"original and decompressed are the same {original == compressed.decompress()}")
|
41a3b1b67e1dfcb2003c32c9be0bb25b85440a86 | brenoso/graph-theory-exercises | /Atividade 1/Problema 1/source/Aresta.py | 693 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Aresta (object):
'''
Construtor da classe
'''
def __init__(self, u, v, peso = 1):
self.__u = str(u)
self.__v = str(v)
self.__peso = peso
'''
Imprime a aresta
'''
def __str__(self):
return " (" + str(self.__u) + ", " + str(self.__v) + ")(" + str(self.__peso) + ") "
'''
Retorna uma lista com o par ordenado de vértices que compõem a aresta
'''
def _obtemAresta(self):
return [self.__u, self.__v]
def _obtemVerticeU(self):
return self.__u
def _obtemVerticeV(self):
return self.__v
def _obtemPeso(self):
return self.__peso |
d8cf21aac77e12e6266b1c399ae55839dc0a5e5b | jh-lau/leetcode_in_python | /data_structure/stack/栈.py | 1,990 | 3.921875 | 4 | """
Created by PyCharm.
User: Liujianhan
Date: 2019/5/31
Time: 9:44
"""
__author__ = 'liujianhan'
class Stack:
# 列表最后元素作为栈顶元素
def __init__(self):
self.items = []
def push(self, elem):
self.items.append(elem)
def pop(self):
return self.items.pop()
def top(self):
return self.items[-1]
def is_empty(self):
return 0 == len(self.items)
def size(self):
return len(self.items)
def parentheses_check(checking_string):
stack = Stack()
for checking_char in checking_string:
if checking_char == '(':
stack.push(checking_char)
else:
if stack.is_empty():
return False
else:
stack.pop()
return True if stack.is_empty() else False
def multi_parentheses_check(checking_string, left_list, right_list):
stack = Stack()
for checking_char in checking_string:
if checking_char in left_list:
stack.push(checking_char)
else:
if stack.is_empty():
return False
else:
need_match = stack.pop()
if left_list.index(need_match) != right_list.index(checking_char):
return False
return True if stack.is_empty() else False
def main_1():
string_list = ['(()()()())', '(((())))', '(()((())()))', '((((((())', '()))', '(()()(()']
for checking_string in string_list:
print(f"{parentheses_check(checking_string)} ----- {checking_string}")
print('*****************')
def main():
left_list = ['(', '[', '{']
right_list = [')', ']', '}']
string_list = ['{{([][])}()}','[[{{(())}}]]','[][][](){}','([)]','((()]))','[{()]']
for checking_string in string_list:
print(f"{multi_parentheses_check(checking_string, left_list, right_list)} ---- {checking_string}")
print('***********')
if __name__ == '__main__':
main()
|
9f1364301f6c206b8c9d190a919280cdc555a4d7 | PacktPublishing/fastText-Quick-Start-Guide | /chapter2/remove_stop_words.py | 930 | 3.75 | 4 | """
Small script so that it is easy to work with the pipe operator and can be
plugged in easily with other bash commands.
Please ensure that the nltk english package is already downloaded before this.
>>> import nltk
>>> nltk.download('stopwords')
Usage: cat raw_data.txt | python remove_stop_words.py > no_stop_words.txt
"""
import io
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import sys
def get_lines():
"""Process lines from standard input.
:yields: str: each line.
"""
lines = sys.stdin.readlines()
for line in lines:
yield line
def main():
"""Split the line, remove the stop words, join and serve."""
stop_words = set(stopwords.words('english'))
for line in get_lines():
words = line.lower().split()
newwords = [w for w in words if w not in stop_words]
print(' '.join(newwords))
if __name__ == "__main__":
main()
|
44ad0eda2239699794fb388a6f9f4f7cf6f455cb | Python-Repository-Hub/Learn-Online-Learning | /Python-for-everyone/02_Data_Structure/10_Tuple/08_sort_by_value.py | 549 | 3.765625 | 4 | #increase-order
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )
print(tmp) # [(10, 'a'), (1, 'b'), (22, 'c')]
tmp = sorted(tmp)
print(tmp) # [(1, 'b'), (10, 'a'), (22, 'c')]
#decrease-order
c = {'a':10, 'b':1, 'c':22}
tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )
print(tmp) # [(10, 'a'), (1, 'b'), (22, 'c')]
tmp = sorted(tmp, reverse=True)
print(tmp) # [(22, 'c'), (10, 'a'), (1, 'b')]
|
00629e1d1903e0021548b70c3526fb3b9a3263d1 | liuiuge/LeetCodeSummary | /125.ValidPalindrome.py | 582 | 3.921875 | 4 | # -*- coding: utf8 -*-
class Solution:
def isPalindrome(self, s: str) -> bool:
if not s:
return True
l, r = 0, len(s) - 1
while l < r:
while not s[l].isalnum() and l < r:
l += 1
while not s[r].isalnum() and l < r:
r -= 1
if s[l].upper() != s[r].upper():
return False
l += 1
r -= 1
return True
if __name__ == "__main__":
sol = Solution()
print(sol.isPalindrome("A man, a plan, a canal: Panama"))
|
00df019190e6997d4e5efe02b9706a23c99ac60d | jsanon01/python | /python-folder/slice.py | 387 | 4.03125 | 4 | """
"""
print("\nthe slice constructor returns the following syntaxes: ".title())
#print('\n- slice(stop)\n- slice(start, stop, step)')
print('\n----------------- Syntax: slice(stop) ----------------------')
print("\nstring = 'astring'")
print('\n- s1 = slice(3) => it means to stop at 3')
string = 'astring'
s1 = slice(3)
print('\nresult is: '.title(), string[s1])
print()
|
789d71e5924fdd2bb85b60d87618fff71195bcc2 | Qunfong/CodeWars | /getSumBetweenTwoValues.py | 469 | 3.796875 | 4 |
def check_equal(a, b):
value = None
if a == b:
value = a
return value
def get_sum(a, b):
equal = check_equal(a, b)
if(check_equal(a, b) is not None):
return equal
largest = max(a, b) + 1
smallest = min(a, b)
sum = 0
for x in range(smallest, largest):
sum += x
return sum
print(get_sum(1, 0))
print(get_sum(1, 2))
print(get_sum(0, 1))
print(get_sum(1, 1))
print(get_sum(-1, 0))
print(get_sum(-1, 2))
|
05aa91e9685090e452badc3be9a85c65d4210c16 | Shashankhs17/Hackereath-problems_python | /Implementation/led.py | 1,763 | 4.09375 | 4 | '''
Its Diwali time and there are LED series lights everywhere.
Little Roy got curious about how LED lights work.
He noticed that in one single LED Bulb
there are 3 LED lights, namely Red, Green and Blue.
State of the bulb at any moment is
the sum of Red, Green and Blue LED light.
Bulb works as follows:
R = R
G = G
B = B
R + G + B = WHITE
--------- = BLACK
R + G + - = YELLOW
R + - + B = MAGENTA
- + G + B = CYAN
Roy took out all the LEDs and found that
Red LED stays ON for R seconds,
Green LED stays ON for G seconds and
Blue LED stays ON for B seconds.
Similarly they stay OFF for same respective R, G, B number of seconds.
(Initially all the LEDs are OFF)
Roy has one query for you, given the total number of seconds T,
find the number of seconds Red, Green, Blue, Yellow, Cyan, Magenta, White, Black(no light) lights are visible.
'''
t, r, g, b = map(int, input("Enter value of T, R, G & B respectively: ").split())
r_ = g_ = b_ = y_ = c_ = m_ = w_ = b__ = 0
k = l = m = 1
x = y = z = 0
for i in range(1, t+1):
if i <= k*r:
x = 0
elif i>k*r and i<(k+1)*r:
x = 1
else:
x = 1
k += 2
if i <= l*g:
y = 0
elif i>l*g and i<(l+1)*g:
y = 1
else:
y = 1
l += 2
if i <= m*b:
z = 0
elif i>m*b and i<(m+1)*b:
z = 1
else:
z = 1
m += 2
if x and y and z:
w_ += 1
elif x and y and not z:
y_ += 1
elif x and not y and z:
m_ += 1
elif not x and y and z:
c_ += 1
elif x and not y and not z:
r_ += 1
elif not x and y and not z:
g_ += 1
elif not x and not y and z:
b_ += 1
else:
b__ += 1
print(r_, g_, b_, y_, c_, m_, w_, b__) |
c57ff37251349a9260593496870ed0d8aff96c64 | apu1995/appucodes | /amt.py | 241 | 3.90625 | 4 | amt=float(input("Enter the amount?\n"))
rate=float(input("Enter the rate?\n"))
time=int(input("Enter the time?\n"))
val=0
year=1
while year<=time :
val=amt+(amt*rate)
print("Value for year %d is %.2f" % (year,val))
amt=val
year=year+1
|
237782f2bc42526762024522b54a9c12a97af630 | ZeroStack/hackerrank | /algorithms/implementation/1_gradingstudents.py | 407 | 3.578125 | 4 | #!/bin/python3
import sys
def solve(grades):
grades = [ grade if round(grade/5+0.5)*5 < 40 else round(grade/5+0.5)*5 if round(grade/5+0.5)*5 - grade < 3 else grade for grade in grades]
for grade in grades:
print(grade)
n = int(input().strip())
grades = []
grades_i = 0
for grades_i in range(n):
grades_t = int(input().strip())
grades.append(grades_t)
solve(grades)
|
e8fd5cc58c197c029e5534504b5fe2fd84832fa1 | danny-hunt/Problems | /bst_inorder_successor/bst_i_s.py | 979 | 4 | 4 | """
Given a node in a binary search tree, return the next bigger element, also known as the inorder successor.
For example, the inorder successor of 22 is 30.
21
/ \
5 30
/ \
22 35
\
27
\
28
You can assume each node has a parent pointer.
"""
# Given a node we need to check the smallest node in its right subtree
# If that doesn't exist then go through ancestors - the first ancestor that is a right-parent of the path is the IS
# Otherwise one doesn't exist
def inorder_successor(node):
current_node = node
if node.right_child:
current_node = node.right_child
while current_node.left_child:
current_node = current_node.left_child
return current_node.value
else:
while current_node.parent:
if current_node.value < current_node.parent.value:
return current_node.parent.value
current_node = node.parent
return node.value
|
5b1bc57221a4f64bd5a1cbea7e08433c42429f44 | gmergola/python-oo | /wordfinder.py | 1,363 | 4.1875 | 4 | """Word Finder: finds random words from a dictionary."""
import random
class WordFinder:
"""reads a file and makes an attribute equal
to a list of words in file
>>> wf = WordFinder("/Users/gennamergola/Desktop/test.txt")
3 words read
>>> wf.random()
'cat'
>>> wf.random()
'cat'
>>> wf.random()
'porcupine'
>>> wf.random()
'dog'
"""
def __init__(self, file_path):
"""reading file, printing out words within file"""
self.file_str = open(file_path).read()
self.list_words = self.make_list()
print(f"{len(self.list_words)} words read")
def make_list(self):
""" making list of words read from file"""
return self.file_str.split('\n')
def random(self):
""" prints out a random word from list_words"""
return random.choice(self.list_words)
class SpecialWordFinder(WordFinder):
""" Special word finder that gets rid of blank lines and comments.
"""
def __init__(self,file_path):
"""get parent class """
super().__init__(file_path)
def make_list(self):
"creating a list of words without blank lines and #mark"
words = super().make_list()
return [word for word in words if not word.startswith("#") and not word == ""]
|
56b4b4b2b4ea586a212e2867050e7c1929c895f0 | fastso/learning-python | /atcoder/contest/solved/abc036_b.py | 176 | 3.515625 | 4 | n = int(input())
a = [list(input()) for i in range(n)]
for i in range(n):
line = []
for j in reversed(range(n)):
line.append(a[j][i])
print(''.join(line))
|
36a8bd1185dc7e28e3ecbe72d6368af8c3874235 | kgm7334/Python-Challenge | /PythonChallenge4/main.py | 2,142 | 3.796875 | 4 | import os
import requests
while True:
print("Welcome to IsitDown.py")
print("Please Write URL Or URLs You Want To Check. (Seperated comma)")
User_Input_URL = input("").replace(" ", "").lower()
if(User_Input_URL == ""):
continue
else:
if((".com" in User_Input_URL) and ("," in User_Input_URL)):
URLs = User_Input_URL.split(",")
for URL in URLs:
if(".com" in URL):
if("http" in URL):
try:
r = requests.get(URL)
if(r.status_code == requests.codes.ok):
print(URL+" is up!")
if(r.status_code == 404):
print(URL+" is down!")
except:
print(URL+" is down!")
continue
else:
try:
r = requests.get("http://"+URL)
if(r.status_code == requests.codes.ok):
print("http://"+URL+" is up!")
if(r.status_code == 404):
print("http://"+URL+" is down!")
except:
print("http://"+URL+" is down!")
continue
while True:
Excute = input(
"Do You Want to start over? y/n: ").strip().lower()
if(Excute == "y" or Excute == "n"):
break
else:
print("Thats Not avalid answer")
continue
else:
print(User_Input_URL+" is not a valid URL")
while True:
Excute = input(
"Do You Want to start over? y/n: ").strip().lower()
if(Excute == "y" or Excute == "n"):
break
else:
print("Thats Not avalid answer")
continue
if(Excute == "n"):
break
|
a71b0fd8553a2969cc59d1f32dcf39f25b5bd7b4 | tmvinoth3/Python | /SortandReverse.py | 383 | 4.0625 | 4 | #code
l = [2,1,5,4,3]
m = l.copy()
str = 'this is string'
strlist = str.split() #string to list
m.sort()#sort
print(l)
m.reverse() #reverse
print("m : ",m)
l.sort(reverse=True)
print("l : ",l)#reverse
strlist.sort(key=len) #sort list
print(strlist);
print('*'.join(strlist)) #convert to string
n = sorted(l) #not change the l
print(n)
r = reversed(n) #not reverse the n
print(r) |
c7e09a585862f480a0d54a31fbb8ac7c5231e590 | Walaga/weekday-of-birth | /weekday of birth.py | 1,351 | 4.15625 | 4 |
#NAME WALAGA PRISCILLA N. EDITH
#REGISTRATION NUMBER 16/U/12253/PS
import calendar #importing inbuilt calendar module
a=input("What is your year of birth?\n")
b=input("Enter your month of birth (enter number e.g for december enter 12\n")
c=input("Enter the date on which you were born(1-30)\n")
x=calendar.weekday(year=int(a), month=int(b), day=int(c)) #module gives the index of the day from the list ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
#Applying a conditional function to assign each date a corresponding prefix
if int(c) == 1:
d = c +"st"
elif int(c)==2:
d = c +"nd"
elif int(c)==3:
d = c +"rd"
elif int(c) >= 4 and int(c) <= 20:
d = c +"th"
elif int(c)==21:
d = c +"st"
elif int(c) == 22:
d = c +"nd"
elif int(c) == 23:
d = c +"rd"
elif int(c) == 31:
d = c +"st"
else:
d = c+"th"
#Applying a conditional func
#Applying a conditional function to assign the result from the module used to the respective day
if x == 0:
y = "Monday"
elif x == 1:
y = "Tuesday"
elif x == 2:
y = "Wednesday"
elif x == 3:
y = "Thursday"
elif x == 4:
y = "Friday"
elif x == 5:
y = "Saturday"
else:
y = "Sunday"
print("We you were born on "+y+" "+d)
input("Press enter")
|
531f268f34608f26ee9fc0db3802be301a65cc8d | zjw641220480/pythonfirst | /src/simple/simple_function.py | 2,210 | 3.8125 | 4 | #!/usr/bin/python3
#coding=utf-8 #必不可少的,不然容易报错
'''
Created on 2017年9月27日
用来演示python函数的相关操作
@author: lengxiaoqi
'''
#自己的第一个参数罢了
from keyword import kwlist
def myFirstFunction():
print("这个是我的第一个参数");
#有参数的python方法
def myFunctionParameter(parameter):
print("传递过来的参数为:"+parameter);
return parameter+"\tfanhuizhi"
#计算绝对值的方法,一个实例方法
def my_abs(x):
if not isinstance(x, (int,float)):
raise TypeError("bad operand type");
if x>=0:
return x;
else:
return -x;
'''
在Python中定义函数,可以用必选参数,默认参数,可变参数,关键字参数和命名关键字参数这5种
参数都可以组合使用,但是,参数定义的顺序必须是:必选参数,默认参数,可变参数,命名关键字参数和关键字参数
第一个参数为位置参数,第二个参数为默认参数,两个参数都没有进行类型校验;
*args是可变参数,args接受的是一个tuple;
**kw是关键字参数,kw接受的是一个dict;
定义命名关键字参数的时候,在没有可变参数的情况下,分隔符(*)不能省略,不然定义的就是位置变量了;
'''
def power(x,n=2):
s=1;
while n>0:
n=n-1;
s=s*x;
return s;
'''
初始的将参数处理成列表或者集合
'''
def calc(numbers):
sum=0;
for n in numbers:
sum= sum+n*n;
return sum;
'''
将参数处理成可变参数(实质上就是一个列表)
'''
def calc_pa(*numbers):
sum=0;
for n in numbers:
sum = sum + n*n;
return sum;
'''
关键字参数演示
'''
def person(name,age,**kw):
if 'city' in kw:
#有city参数
pass;
if 'job' in kw:
#有job参数
pass;
print('name:',name,'age:',age,'other:',kw);
'''
命名关键字参数的演示
'''
def person_key(name,age,*,city,job):
print('name:',name,'age:',age,'city:',city,'job:',job);
#print(myFirstFunction());#因为第一个函数无返回值,故第二行会打印None,
#print(myFunctionParameter('parameter')); |
d36552314147c6b95014eeaebe5f2e2ccf05da9b | tbartek9/Script-to-combine-files | /combine_files.py | 746 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 18:59:12 2021
@author: Bartosz Terka
"""
"""
This script combines files with the same extension.
1)put the script in the folder together with the folder containing the files
2)complete the names of folder and file in lines 13,14 and 17
"""
import os
name=open('name.txt','a') #in place of name.xx enter the name and extension of file which will be created
folders=os.listdir('folder') #in place of folder enter the name of folder that contains the files to combine
licznik=len(folders)
os.chdir('folder') #in place of folder enter the name of folder that contains the files to combine
i=0
while(i<licznik):
plik=open(folders[i],'r')
name.write(plik.read())
i+=1
|
32ee19d2bee60a004ae5e9782d4058d11fba2369 | Qocotzxin/python-course | /3 - Flows/G.py | 402 | 4.1875 | 4 | # Dadas dos listas, debes generar una tercera con todos los elementos
# que se repitan en ellas, pero no debe repetirse ningún elemento en la nueva lista:
lista_1 = ["h", 'o', 'l', 'a', ' ', 'm', 'u', 'n', 'd', 'o']
lista_2 = ["h", 'o', 'l', 'a', ' ', 'l', 'u', 'n', 'a']
lista_3 = []
for char in lista_1:
if char in lista_2 and char not in lista_3:
lista_3.append(char)
print(lista_3) |
4ae704007bd1396abe4fdef60aac94de5235da98 | ashwin-subramaniam/Guessing-Game | /guessingGame.py | 576 | 4.25 | 4 | import random;
number = random.randint(1,9)
chances = 5
guess = 0
print("Guessing Game(1-9)")
while number!=guess and chances > 0:
guess = int(input("Enter Your Guess:"))
chances = chances - 1
if(number>guess):
print("Your Guess was too low. Guess a number higher than ",str(guess))
elif(number<guess):
print("Your guess was too high. Guess a number lower than ",str(guess))
else:
print("Congratulations!You Won!!!")
if not chances < 0:
print("You lose!!! The number is", str(number))
|
7628210ce964285a17605540c9e1f41c3f95b770 | JIN-YEONG/keras_example | /keras/0725/keras13_lstm_earlyStopping.py | 2,355 | 3.921875 | 4 |
# RNN (Recurrent Neural Network) 순환 신경망
# 시배열(연속된) 데이터의 분석의 유리
# 시배열(time distributed) -> 연속된 데이터
from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 1. 데이터
x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12],[20,30,40],[30,40,50],[40,50,60]])
y = array([4,5,6,7,8,9,10,11,12,13,50,60,70])
# print('x.shape: ', x.shape)
# print('y.shape: ', y.shape) # 결과 값의 개수를 알수 있다.
x = x.reshape((x.shape[0], x.shape[1],1)) # x의 shape를 (4,3,1)로 변경(데이터의 개수는 변함 없음)
# 행은 무시하고 (3,1)이 input_shape에 들어간다.
print('x.shape: ', x.shape)
# 2. 모델 구성
model = Sequential()
model.add(LSTM(10, activation='relu', input_shape=(3,1))) # inpurt_shape=(칼럼의 수, 자를 데이터수)
# 10 -> 아웃풋 노드의 개수,Dense에서 사용
# 이미 많은 파라미터를 가지고 있어서 에포를 올리는 것이 효과적일 수 있다.
model.add(Dense(28))
model.add(Dense(30))
model.add(Dense(14))
model.add(Dense(1))
# model.summary()
#################과제###################
# LSTM의 Param의 개수가 왜 많은지 답하시오
# (인풋 3 + 바이어스 1) * ? * 아웃풋 10 = 480
# ? = 12 -> '?'가 어디서 나왔는가?
########################################
# 3.실행
model.compile(optimizer='adam', loss='mse')
from keras.callbacks import EarlyStopping # 모델의 훈련을 조기에 종료 시킬 수 있다.
early_stopping = EarlyStopping(monitor='loss', patience=100, mode='auto') # loss값을 기준으로 훈련을 멈춤
# parience => 동일한loss가 반복되는 횟수, 반복되면 종료
model.fit(x,y,epochs=10000,batch_size=1, callbacks=[early_stopping]) # callbacks 속성으로 조기 종료 조건 전달
x_input = array([25,35,45]) # (1,3,?)
# x_input = array([70,80,90])
x_input = x_input.reshape((1,3,1))
yhat = model.predict(x_input, verbose=0)
print(yhat)
|
960e19fbd5ce77021ae4e82c74bafb03c9253de4 | shres-ruby/pythonassignment | /functions/q7_f.py | 692 | 4.34375 | 4 | # 7. Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.
# Sample String : 'The quick Brow Fox'
# Expected Output :
# No. of Upper case characters : 3
# No. of Lower case Characters : 12
def func(s):
upper = 0
lower = 0
for i in s:
if i.isupper() == True:
upper += 1
elif i.islower() == True:
lower += 1
return upper, lower
# print(f"No. of Upper case characters : {upper}\nNo. of Lower case characters : {lower}")
upper,lower = func('The quick Brow Fox')
print(f"No. of Upper case characters : {upper}")
print(f"No. of Lower case characters : {lower}") |
86e74e6b83be3976ba48f90728a50334811df18a | cycho04/python-automation | /game-inventory.py | 1,879 | 4.3125 | 4 | # You are creating a fantasy video game.
# The data structure to model the player’s inventory will be a dictionary where the keys are string values
# describing the item in the inventory and the value is an integer value detailing how many of that item the player has.
# For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
# means the player has 1 rope, 6 torches, 42 gold coins, and so on.
# Write a function named displayInventory() that would take any possible “inventory” and display it like the following:
# Inventory:
# 12 arrow
# 42 gold coin
# 1 rope
# 6 torch
# 1 dagger
# Total number of items: 62
#then..
# Imagine that a vanquished dragon’s loot is represented as a list of strings like this:
# dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# Write a function named addToInventory(inventory, addedItems), where the inventory parameter
# is a dictionary representing the player’s inventory (like in the previous project)
# and the addedItems parameter is a list like dragonLoot. The addToInventory() function
# should return a dictionary that represents the updated inventory.
# Note that the addedItems list can contain multiples of the same item.
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
print('Inventory: ')
item_count = 0
for k, v in inventory.items():
item_count += int(v)
print(v, k)
print('Total number of items:', item_count)
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] += 1
else:
inventory[i] = 1
return inventory
modified = addToInventory(stuff, dragonLoot)
displayInventory(modified) |
b4008e51e84b1604c72c9dc17f03677ad70b26b3 | Zjly/Program-Python | /review/data_structure/fib.py | 411 | 3.859375 | 4 | def fib1(n):
if n == 1 or n == 2:
return 1
else:
return fib1(n - 1) + fib1(n - 2)
def fib2(n):
if n == 1 or n == 2:
return 1
else:
pre1 = 1
pre2 = 1
this = 2
for i in range(3, n + 1):
this = pre1 + pre2
pre1 = pre2
pre2 = this
return this
if __name__ == '__main__':
for i in range(1, 10):
print(fib1(i), end=" ")
print()
for i in range(1, 10):
print(fib2(i), end=" ")
|
a3e1bc36279778dc5d7054b1de2c9a1fa5b663a4 | arnabid/QA | /trees/minHeightTrees.py | 1,398 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 6 08:11:03 2017
@author: arnab
"""
"""
Minimum height trees
reference: https://leetcode.com/problems/minimum-height-trees/description/
Notes:
There can be only 1 or 2 nodes with minimum height trees.
These nodes are the critical nodes in the sense that maximum distance and total distance to
reach the a node(or all nodes) in the network will be minimum. Any sort of message propagation
will be most efficient from these node(s).
Runtime analysis:
build the degree map: O(E)
every node gets added and removed from the queue only once.
when the node is in the front of the queue, its edges are examined.
so total time: O(E)
linear time algorithm: O(E) + O(E)
"""
from collections import Counter
import Queue
def findMinHeightTrees(graph):
n = len(graph)
degree = Counter()
q = Queue.Queue()
# build the degree map and put the leaves in the queue
for node in graph:
degree[node] = len(graph(node))
if degree[node] == 1:
q.put(node)
while n > 2:
# prune the batch of leaves present in the queue
for i in range(q.qsize()):
v = q.get()
n -= 1
for w in graph.get(v, []):
degree[w] -= 1
if degree[w] == 1:
q.put(w)
res = []
while not q.empty():
res.append(q.get())
return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.