blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bd9a09532638a2f1c8746abb1d759af0a9770ce1 | Genghis77777/Item-Comparison | /Test.py | 1,281 | 4.0625 | 4 | product_details = []
product_name = ""
product_status = ""
best_value = []
worst_value = []
while product_name != "X":
product_name = input("\nPlease enter the name of the product: ")
if product_name == "X":
break
else:
product_weight = float(input("Please enter the weight/volume of the "
"product: "))
product_price = float(input("Please enter the price of the product: $"))
product_price = round(product_price, 2)
unit_price = product_weight/product_price
unit_price = round(unit_price, 2)
product_details.append([product_name, product_weight, product_price,
unit_price, product_status])
for item in product_details:
print(f"\n{item[4]}"
f"\nItem Name: {item[0]}"
f"\nItem Weight/Volume: {item[1]}kg"
f"\nItem Price: ${item[2]}"
f"\nUnit Price: ${item[3]}")
if len(best_value) == 0:
best_value = item
elif item[3] < best_value[3]:
best_value = item
if len(worst_value) == 0:
worst_value = item
if item[3] > worst_value[3]:
worst_value = item
print(f"\nThe best value item is {best_value}")
print(f"The worst value item is {worst_value}")
|
43b36d5346f4c2028460d512fd558b6d718e1c8c | eliaskousk/example-code-2e | /17-it-generator/coroaverager.py | 888 | 3.515625 | 4 | """
A coroutine to compute a running average
# tag::CORO_AVERAGER_TEST[]
>>> coro_avg = averager() # <1>
>>> next(coro_avg) # <2>
0.0
>>> coro_avg.send(10) # <3>
10.0
>>> coro_avg.send(30)
20.0
>>> coro_avg.send(5)
15.0
# end::CORO_AVERAGER_TEST[]
# tag::CORO_AVERAGER_TEST_CONT[]
>>> coro_avg.send(20) # <1>
16.25
>>> coro_avg.close() # <2>
>>> coro_avg.close() # <3>
>>> coro_avg.send(5) # <4>
Traceback (most recent call last):
...
StopIteration
# end::CORO_AVERAGER_TEST_CONT[]
"""
# tag::CORO_AVERAGER[]
from collections.abc import Generator
def averager() -> Generator[float, float, None]: # <1>
total = 0.0
count = 0
average = 0.0
while True: # <2>
term = yield average # <3>
total += term
count += 1
average = total/count
# end::CORO_AVERAGER[]
|
23d1af69bd1560673e3ad498ab3ef57b8e837a16 | sunanqi/algorithms | /dfs.py | 1,317 | 3.71875 | 4 | """
- Problem:
traverse nodes in a graph
- Algorithm:
DFS
- time complexity:
O(V+E)
optimization: before dfs, convert adjacency list to iterator
- input:
graph represented as adjacency list
- output:
reachable nodes
"""
import collections
import datetime
def dfs(G, s):
for k in G:
G[k] = iter(G[k])
explored = set([s])
stack = []
stack.append(G[s])
while stack:
try:
v = next(stack[-1])
if v not in explored:
explored.add(v)
stack.append(G[v])
except:
stack.pop()
return explored
if __name__ == '__main__':
start_read_file = datetime.datetime.now()
G = collections.defaultdict(list)
with open('SCC.txt') as f:
lines = f.read().split('\n')
for line in lines:
if line:
tmp = [int(i) for i in line.split()]
G[tmp[0]].append(tmp[1])
finish_read_file = datetime.datetime.now()
print('read file uses ', finish_read_file-start_read_file, 'seconds')
print('total number of nodes:', len(G))
print('total number of edges:', sum(len(G[k]) for k in G))
print('number of reachable nodes:', len(dfs(G,1)))
finish_dfs = datetime.datetime.now()
print('dfs uses ', finish_dfs - finish_read_file, 'seconds')
|
bd39c0259a611da6809fb047f9eabc8f0230cbca | xaviruvpadhiyar98/Python-Assignments | /missingElement().py | 304 | 3.671875 | 4 | # finds the msiing elemnt from first to second arr
def MissingElement(a,b):
for x in a:
if x in b:
b.remove(x)
a.remove(x)
for x in a:
if x not in b:
print(x)
a=[1,2,3,4,5,6,7]
b=[3,7,2,1,4,6]
MissingElement(a,b) |
069d037b0914392b786ee77f7c37e4f248f8b506 | zhouyanasd/SNN_framework | /src/data/__init__.py | 525 | 3.5 | 4 | '''
The type of data is N groups in a python list,
and each group is a numpy array which form is [feature, number].
Example: python-list[np.array[feature, number],...]
[array([[0, 0, 1, ..., 0, 0, 0],
[2, 2, 0, ..., 1, 0, 4],
[1, 0, 2, ..., 3, 0, 1],
[1, 1, 0, ..., 1, 0, 1],
[1, 1, 3, ..., 0, 5, 0]]), array([[3, 2, 1, ..., 2, 3, 1],
[1, 3, 0, ..., 1, 2, 0],
[2, 1, 1, ..., 3, 2, 2],
[3, 0, 0, ..., 1, 0, 1],
[3, 1, 3, ..., 2, 0, 7]])
'''
from .simple import Simple |
3d06021a04644cddeb73d5ccc6ef51129b715647 | ShriyaChandran/C97Homework | /Homework97.py | 652 | 4.1875 | 4 | import random
print("The number guessing game")
guessCount=0
number=random.randint(1,9)
introString=int(input("Enter a number from 1 to 9"))
while(guessCount<6):
if(introString>number):
print("The number is lesser than")
print(introString)
introString=int(input("Enter a number from 1 to 9"))
elif(introString<number):
print("The correct number is greater than ")
print(introString)
introString=int(input("Enter a number from 1 to 9"))
else:
print("Congratulations!! You guessed it man")
guessCount=guessCount+1
if(guessCount==6):
print("You lose. sad.")
|
8eb47fd7811e5b2de75a1f75d21210e64c99e540 | seanbrede/Leetcode | /0055_Jump_Game.py | 577 | 3.546875 | 4 | class Solution:
def canJump(self, nums: List[int]) -> bool:
last_pos = len(nums) - 1
steps_left = 0
i = 0
# while we are within the array and still have steps left
while i < last_pos:
# update the number of steps left, if none then quit
steps_left = max(nums[i], steps_left)
if steps_left == 0: return False
# update our position and reduce the number of steps left
steps_left -= 1
i += 1
# we only get here if we reached the end
return True
|
b8db204d634ce6b6ea3ad868dd02b0747e289348 | Saransh-kalra/Python-Labs | /Python/grading_system.py | 286 | 3.984375 | 4 | print("welcome to the grading system")
marks=float(input("enter your marks: "))
if(marks>=90.0):
print("you got an A")
elif(marks>=80.0):
print("you got a B")
elif(marks>=70.0):
print("you got a C")
elif(marks>=60.0):
print("you got a D")
else:
print("you got a F")
|
32b4bac7d801b62e129244f09eed2a1eb8d1ac96 | varughese/CS8-Spring19-Recitation | /week4/SOL03a.py | 308 | 4.03125 | 4 | # Python program that play guess game with a user
from random import randint
#This allows to the user to input his first number
user_number=int(input("Guess the number:"))
number = randint(1, 10)
while number!= user_number:
user_number=int(input("Guess the number:"))
print("Yay :), you found it!") |
1c53736b4f25a908d89099ee6cfd1beaf4be90fb | beardnick/LeetCode | /src/practice/travel.py | 160 | 3.515625 | 4 | # -*- coding: utf-8 -*-
n = int(input())
nums = []
for i in range(n):
nums.append(list(map(int,input().split())))
print("n =" , n)
print("nums = " , nums) |
8b9f0f2a61abfbb34fd1788996c31135343cbf16 | iagotito/hacktoberfest | /python/topological_sort.py | 774 | 3.671875 | 4 | clothes = {
0: 'underwear',
1: 'pants',
2: 'belt',
3: 'suit',
4: 'shoe',
5: 'socks',
6: 'shirt',
7: 'tie',
8: 'clock'
}
graph = [
[1, 4],
[2, 4],
[3],
[],
[],
[4],
[2, 7],
[3],
[]
]
visited = [0 for x in range(len(graph))]
stack = []
def print_stack(stack, clothes):
order = 1
while stack:
cur_clothe = stack.pop()
print(order, clothes[cur_clothe])
order += 1
def dfs(u):
global visited, graph
visited[u] = 1
for v in graph[u]:
if not visited[v]:
dfs(v)
stack.append(u)
def top_sort(graph):
for v in range(len(graph)):
if not visited[v]:
dfs(v)
top_sort(graph)
print(stack)
print_stack(stack, clothes) |
9ebba8140c0240ee2a3a946226b30bf3b03a5e64 | doPggy/py-try | /12-list-comprehension.py | 611 | 4.1875 | 4 | # 产生式表达式
## 循环生成 list
values = [10, 21, 3, 44, 5]
squares = []
for x in values:
squares.append(x ** 2)
print(squares)
## 列表生成式生成 list
values = [10, 21, 3, 44, 5]
squares = [x ** 2 for x in values]
print(squares)
'''还可以带判断语句'''
squares = [ x ** 2 for x in values if x >= 10 ]
print(squares)
## 生成集合字典
values = [10, 21, 3, 44, 5]
squares = { x ** 2 for x in values }
print(squares)
squares = { x:x ** 2 for x in values }
print(squares)
## 一个应用
'''这样不会一次性把列表生成'''
total = sum(x ** 2 for x in values)
print(total)
|
2efd25d52393850c991ba24cd1b1fcb6545f001a | glendaascencio/Python-Tutorials | /scalene_isosolis_equilateral_triangle.py | 692 | 4.4375 | 4 | # Python-Tutorial
Tutorial for learning how to Program with python
''' We'll pront the user to enter the size of a triangle and
we'll determine if it is an scalene, isosolis, or equilateral triangle
* Scalene triangle= is when the sizes has different lenghts
* Isosceles triangle = has two equal lenghts
* Equilateral triangle = has three equal lengths
'''
a = int(raw_input("Enter the length of a = "))
b = int(raw_input("Enter the lenght of b = "))
c = int(raw_input("Enter the lenght of c = "))
if a != b and a != c and c != a:
print("This is a scalene triangle")
elif a == b and b == c:
print("This is a equilateral triangle")
else:
print("This is an isosceles triangle")
|
1be23e11c00d86c31357bb3f6519cc2a9272801e | Vinod096/learn-python | /lesson_02/personal/chapter_5/01_km_convertor.py | 350 | 4.5 | 4 | #Write a program that asks the user to enter a distance in kilometers, and then converts that
#distance to miles. The conversion formula is as follows:
#Miles = Kilometers * 0.6214
def miles():
kilometers = float(input("enter kilometers :"))
miles = kilometers * 0.6214
print("distance travelled in miles :{0:2f}".format(miles))
miles()
|
7a314ba94d77439e3a5755032c853fbcf7177490 | forrestjan/Labos-MCT-19-20 | /2019-prog-labooefeningen-forrestjan/week4/oefening7.py | 348 | 3.609375 | 4 | def print_list(soort, lijst):
print(f"verzameling: {soort} ")
for item in lijst:
print(f"{item} staat op positie {lijst.index(item)}")
lijst = [12, 45, -9, -15]
print_list = ("gehele getallen", lijst)
lijst = ["maandag", "moet", "ik", "s'avonds",
"ook", "iets", "doen", "voor", "school"]
print(f"DRINGEND TO DO", lijst)
|
ffb8f3bd438cb358141d443394258d60a14e3e43 | shaikbabafakruddin/babafakruddin-python-and-network-security | /project1.py | 313 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 4 16:58:29 2021
@author: Shinjon Mukherjee
"""
# Project 1 = Program to generate md5 hash of the given data
import hashlib
word=input("Enter the word You want to encode = ")
enc=word.encode("utf-8")
digest=hashlib.md5(enc.strip()).hexdigest()
print(digest)
|
57aa091a308335dfd8e0e4d711850c78d71c4691 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2776/58586/271275.py | 605 | 3.546875 | 4 | words=eval(input())
ans=[]
def dfs(words,temp,depth):
if len(temp)==0:
if depth>=2:
return True
else:
return False
for i in range(0,len(words)):
if len(words[i])>len(temp):
continue
else:
if temp.find(words[i])!=-1:
t=temp
temp=temp.replace(words[i],"")
if dfs(words,temp,depth+1):
return True
temp=t
return False
# dfs(words,"",0)
for i in range(len(words)):
if dfs(words,words[i],0):
ans.append(words[i])
print(ans) |
1aca501a366d2e63b4339e090506b91cee599d92 | VipulGirishKumar/Cinema-Hall-Booking-System | /Project- Cinema Seat Booking.py | 6,598 | 3.765625 | 4 | #Cinema Hall - Seat Booking Booking System
print("Cinema Hall - Seat Booking Booking System")
seats = []
seats.append([0,0,1,0,1,1,0,1])
seats.append([0,1,1,0,0,1,0,1])
seats.append([1,0,0,1,1,1,0,0])
seats.append([0,1,0,1,1,0,0,1])
seats.append([0,0,1,1,0,1,0,0])
seats.append([1,0,0,1,0,1,1,0])
#Password
def password():
if passwd=='python':
print("System Online")
print("")
else:
print("Access Denied")
sys.exit()
#Menu
print("")
print("\tMENU")
print(" 0. Display Menu \n 1. Display Bookings \n 2. Check Seat Availability \n 3. Book Seat \n 4. Book Seat at the front \n 5. Book Seat at the back \n 6. Cancel Booking \n 7. Cancel All Booking \n 8. Load Booking from file \n 9. Save bookings in a file \n 10. Exit " )
print("")
#Displays MENU
def displayMenu():
print("")
print("\tMENU")
print(" 0. Display Menu \n 1. Display Bookings \n 2. Check Seat Availability \n 3. Book Seat \n 4. Book Seat at the front \n 5. Book Seat at the back \n 6. Cancel Booking \n 7. Cancel All Booking \n 8. Load Booking from file \n 9. Save bookings in a file \n 10. Exit" )
print("")
#Displays all Seats
def displayBookings():
print("===========================================")
print(" SCREEN ")
print("")
for row in seats:
print("\t",row)
print("")
print("1 = Seat is Booked.")
print("0 = Seat is Available")
print("")
print("===========================================")
print("")
#Load Bookings from File
def loadBookings():
file = open("seats.txt","r")
row = 0
for line in file:
data = line.split(",")
if len(data)==8: #Only process lines which contain 8 values
for column in range (0,8):
seats[row][column] = int(data[column])
row = row + 1
file.close()
print("Bookings Loaded")
#Seat availability checking
def checkSeat():
row = int(input("Enter a row number (between 0 and 5)"))
column = int(input("Enter a column number (between 0 and 7)"))
if seats[row][column]==1:
print("This seat is already booked.")
else:
print("This seat is empty.")
#Booking Seat
import random
def bookSeat():
booked = False
F=open("BookingDetails.txt",'a')
while booked == False:
row = int(input("Enter a row number (between 0 and 5)"))
column = int(input("Enter a column number (between 0 and 7)"))
if seats[row][column]==1:
print("This seat is already booked.")
else:
print("This seat is empty.")
#Details
Name=input("Enter Customer Name :")
BookingIDD=random.randint(47136834,6753845683)
BookingID=str(BookingIDD)
F.write("\n")
F.write(BookingID+' ')
F.write(Name+' ')
F.write(str(row)+','+str(column))
print("Booking seat...")
seats[row][column]=1
print("We have now booked this seat for you.")
print("Your Booking ID is",BookingID)
booked=True
F.close()
#Booking Seat at the front
def bookSeatAtFront():
print("Booking seat at the front")
F=open("BookingDetails.txt",'a')
for row in range(0,6):
for column in range(0,8):
if seats[row][column]==0:
Name=input("Enter Customer Name :")
BookingIDD=random.randint(47136834,6753845683)
BookingID=str(BookingIDD)
F.write("\n")
F.write(BookingID+' ')
F.write(Name+' ')
F.write(str(row)+','+str(column))
print("Booking seat...")
print("Row: ", str(row))
print("Column: ", str(column))
seats[row][column]=1
print("We have now booked this seat for you.")
F.close()
return True
print("Sorry the theatre is full - Cannot make a booking")
return False
#Booking Seat at the Back
def bookSeatAtBack():
print("Booking seat at the back")
F=open("BookingDetails.txt",'a')
for row in range(5,-1,-1):
for column in range(7,-1,-1):
if seats[row][column]==0:
Name=input("Enter Customer Name :")
BookingIDD=random.randint(47136834,6753845683)
BookingID=str(BookingIDD)
F.write("\n")
F.write(BookingID+' ')
F.write(Name+' ')
F.write(str(row)+','+str(column))
print("Booking seat...")
print("Row: ", str(row))
print("Column: ", str(column))
seats[row][column]=1
print("We have now booked this seat for you.")
F.close()
return True
print("Sorry the theatre is full - Cannot make a booking")
return False
#Cancelling Seat Booking
def CancelBooking():
booked = False
while booked == False:
row = int(input("Enter a row number (between 0 and 5)"))
column = int(input("Enter a column number (between 0 and 7)"))
if seats[row][column]==1:
seats[row][column]=0
print("Booking Cancelled")
return True
else:
print("Seat is not booked")
return True
#Cancelling All Booking
def CancelAllBooking():
for row in range(0,6):
for column in range(0,8):
seats[row][column]=0
print("All Booking Cancelled")
#Save Booking in file
def saveBookings():
file = open("seats.txt","w")
for row in range(0,6):
line=""
for column in range(0,8):
line = line + str(seats[row][column]) + ","
line = line[:-1] + ("\n") #Remove last comma and add a new line
file.write(line)
file.close()
print("Booking saved in seats.txt")
#Main Program
import sys
passwd= input("Enter the password to access the booking system:")
while True:
password()
break
F1=open("BookingDetails.txt",'w')
F1.write("Booking ID"+' ')
F1.write("Name of Customer"+' ')
F1.write("Seat Number"+' ')
F1.close()
while True:
choice= int(input("Enter your choice:"))
print("")
if choice==0:
displayMenu()
elif choice==1:
displayBookings()
elif choice==2:
checkSeat()
elif choice==3:
bookSeat()
elif choice==4:
bookSeatAtFront()
elif choice==5:
bookSeatAtBack()
elif choice==6:
CancelBooking()
elif choice==7:
CancelAllBooking()
elif choice==8:
loadBookings()
elif choice==9:
saveBookings()
else:
print("Exiting...")
sys.exit()
print("")
#End of Program
|
926b0b00b37df4fa12cf3b2b2214f3cc7ceddcde | christina57/lc-python | /lc-python/src/lock/314. Binary Tree Vertical Order Traversal.py | 2,335 | 4.0625 | 4 | """
314. Binary Tree Vertical Order Traversal
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
Given binary tree [3,9,20,null,null,15,7],
3
/\
/ \
9 20
/\
/ \
15 7
return its vertical order traversal as:
[
[9],
[3,15],
[20],
[7]
]
Given binary tree [3,9,8,4,0,1,7],
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
return its vertical order traversal as:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
return its vertical order traversal as:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
Q = []
Q.append((root,0))
res = [[root.val]]
while len(Q) > 0:
size = len(Q)
offset = 0
for i in range(size):
item = Q.pop(0)
cur = item[0]
idx = item[1]
if cur.left is not None:
if idx == 0:
res.insert(0, [cur.left.val])
offset = 1
else:
res[idx+offset-1].append(cur.left.val)
Q.append((cur.left, idx+offset-1))
if cur.right is not None:
if idx+offset == len(res)-1:
res.append([cur.right.val])
else:
res[idx+offset+1].append(cur.right.val)
Q.append((cur.right, idx+offset+1))
return res |
af7e780c79b07dedfece45cdf33c046d4edf7667 | slickFix/Python_algos | /DS_ALGO/GFG_practise/BST_pred_succ.py | 2,093 | 3.96875 | 4 | class Node:
def __init__(self,data):
self.key = data
self.left = self.right = None
def find_pre(root):
curr = root
while curr.right is not None:
curr = curr.right
return curr
def find_suc(root):
curr = root
while curr.left is not None:
curr = curr.left
return curr
def findPreSuc(root,key):
if root is None:
return
if root.key == key:
if root.left is not None and root.right is not None:
findPreSuc.pre = find_pre(root.left).key
findPreSuc.suc = find_suc(root.right).key
elif root.right is None and root.left is None:
return
elif root.right is None:
findPreSuc.pre = find_pre(root.left).key
else:
findPreSuc.suc = find_suc(root.right).key
else:
if key > root.key:
findPreSuc.pre = root.key
findPreSuc(root.right,key)
else :
findPreSuc.suc = root.key
findPreSuc(root.left,key)
def insert(root,data):
if root is None:
return Node(data)
if data > root.key:
root.right = insert(root.right,data)
elif data < root.key:
root.left = insert(root.left,data)
else:
return root
return root
if __name__ == '__main__':
key = 65 # Key to be searched in BST
""" Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80
"""
root = None
root = insert(root, 50)
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
# Static variables of the function findPreSuc
findPreSuc.pre = None
findPreSuc.suc = None
findPreSuc(root, key)
if findPreSuc.pre is not None:
print("Predecessor is", findPreSuc.pre)
else:
print("No Predecessor")
if findPreSuc.suc is not None:
print("Successor is", findPreSuc.suc)
else:
print("No Successor")
|
103dba9895515b9c9ecd70d661d1e458ce578ac2 | darthHelmet/MadLibs | /MadLibs.py | 1,254 | 3.578125 | 4 | def madlib():
print "Welcome to Madlibs"
NOUN_PLURAL_1 = raw_input("Enter a Plural Noun: ")
PLACE = raw_input("Enter a Place: ")
NOUN_1 = raw_input("Enter a Noun: ")
NOUN_PLURAL_2 = raw_input("Enter a Plural Noun: ")
NOUN_2 = raw_input("Enter a Noun: ")
ADJECTIVE_1 = raw_input("Enter an Adjective: ")
VERB_1 = raw_input("Enter a Verb: ")
NUMBER = raw_input("Enter a Number: ")
ADJECTIVE_2 = raw_input("Enter an Adjective: ")
BODY_PART = raw_input("Enter a Body Part: ")
VERB_2 = raw_input("Enter a Body Verb: ")
print "Two" , NOUN_PLURAL_1, "both alike in dignity, In fair " , PLACE, ", where we lay our scene,From ancient" , NOUN_1, "break to new mutiny, Where civil blood makes civil hands unclean.From forth the fatal loins of these two foesA pair of star-cross`d" , NOUN_PLURAL_2, "take their life; Whole misadventured piteous overthrowsDo with their " , NOUN_2, "bury their parents` strife. The fearful passage of their" ,ADJECTIVE_1, "love,And the continuance of their parents` rage, Which, but their children`s end, nought could" , VERB_1, ",Is now the" , NUMBER, "hours` traffic of our stage; The which if you with " , ADJECTIVE_2, "" , BODY_PART, "attend,What here shall" , VERB_2, ", our toil shall strive to mend."
madlib() |
c585aea808a15886dbb4b531db0d43c0da54b3e9 | museHD/NCSS-Int-2020 | /Raise the Roof/raise_the_roof.py | 433 | 4.0625 | 4 | breads = {}
while len(breads) < 5:
name = input("Name: ")
bread = input("What kind of bread are you bringing? ")
if breads.get(bread,0) == 0:
breads[bread]=name
print(f"{name} is bringing a {bread}!")
elif breads.get(bread,0) != 0:
print("Someone else is bringing that already.")
print("The party is organised! Here's what's on the menu:")
for thisbread, thisname in breads.items():
print(f"{thisbread}: {thisname}") |
d1ee7b87bb3429afe702688330432ee6db4c41fa | dgjung0220/codingtest | /dfs_stack.py | 493 | 3.609375 | 4 | import collections
def iterative_dfs(start_v):
discovered = []
stack = [start_v]
while stack:
v = stack.pop()
if not v in discovered:
discovered.append(v)
for w in graph[v]:
stack.append(w)
return discovered
if __name__ == "__main__":
graph = {
1 : [2, 3 ,4],
2 : [5],
3 : [5],
4 : [],
5 : [6, 7],
6 : [],
7 : [3]
}
print(iterative_dfs(1)) |
25fb8391021e590426d416b8e4180375fcb95156 | pactonal/cse231 | /proj05.py | 2,298 | 3.875 | 4 | #!/usr/bin/python3
'''Put overall header comments here.'''
import string
def open_file():
'''Insert function DocString here.'''
opened = 0
while opened != 1:
try:
filename = input("Enter a file name: \n")
f = open(filename, "r")
opened = 1
except IOError:
print("Error. Please try again.")
opened = 0
return f
def print_headers():
'''Insert function DocString here.'''
print('{:^49s}'.format("Maximum Population Change by Continent\n"))
print("{:<26s}{:>9s}{:>10s}".format("Continent", "Years", "Delta"))
def calc_delta(line, col):
'''Insert function DocString here.'''
change = 0
old = line[(17+6*(col - 1)):(22+6*(col - 1))]
new = line[(17+6*(col)):(22+6*(col))]
for i in " ":
old = old.replace(i, "")
new = new.replace(i, "")
for i in string.punctuation:
old = old.replace(i, "")
new = new.replace(i, "")
old = int(old)
new = int(new)
change = ((new - old) / old)
return change
def format_display_line(continent, year, delta):
'''Insert function DocString here.'''
yearstring = (str(year - 50) + "-" + str(year))
delta *= 100
delta = round(delta)
displayline = "{:<26s}{:>9s}{:>9d}%".format(continent, yearstring, delta)
return displayline
def main():
'''Insert function DocString here.'''
with open_file() as data:
print_headers()
next(data)
next(data)
maxofall = 0
for line in data:
maxdelta = 0
maxyear = 0
continent = line[0:15].strip()
for column in range(6):
delta = calc_delta(line, column - 1)
if delta > maxofall:
maxcontinent = continent
maxofall = delta
maxofallyear = (1750 + 50 * (column + 1))
if delta > maxdelta:
maxdelta = delta
maxyear = (1750 + 50 * (column + 1))
print(format_display_line(continent, maxyear, maxdelta))
print("Maximum of all continents:")
print(format_display_line(maxcontinent, maxofallyear, maxofall))
return 0
if __name__ == "__main__":
main()
|
057495adcdf3173d3eeab5129ea0cd60a0a4f6fb | zixing23/wpm | /test/5.py | 1,733 | 3.53125 | 4 | import pickle
class AthleteList(list):
def __init__(self,a_name,a_dob=None,a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
def top3(self):
return(sorted(set([sanitize(t) for t in self]))[0:3])
def sanitize(time_string):
# 如果'-'在time_string中,则splitter赋予'-'
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return (time_string)
(mins, secs) = time_string.split(splitter)
return (mins + '.' + secs)
def get_data(filename):
try:
with open(filename) as f:
data = f.readline()
templ = data.strip().split(',')
return(AthleteList(templ.pop(0),templ.pop(0),templ))
except IOError as ioerr:
print("File Error: " + str(ioerr))
return (None)
def put_to_store(files_list):
all_athletes={}
for each_file in files_list:
ath = get_data(each_file)
all_athletes[ath.name] = ath
try:
with open("athletes.pickle","wb") as athf:
pickle.dump(all_athletes,athf)
except IOError as ioerr:
print("File Error(put_and_store):" +str(ioerr))
return(all_athletes)
def get_from_store():
all_athletes = {}
try:
with open("athletes.pickle","rb") as athf:
all_athletes = pickle.load(athf)
except IOError as ioerr:
print("File Error(get_from_store):" +str(ioerr))
return(all_athletes)
the_files = ['resource/james2.txt','resource/julie2.txt','resource/mikey2.txt','resource/sarah2.txt']
data = put_to_store(the_files)
for each_athlete in data:
print(data[each_athlete].name + '' + data[each_athlete].dob)
|
a51c13c8d18ce0253ed476a19b91c23852524a38 | andynines/3tmaster | /tictactoe.py | 1,821 | 3.78125 | 4 | """
tictactoe.py
Tic-tac-toe game engine
"""
import collections
class BoardStr(str):
def __str__(self):
# render board as 3x3 grid for terminal output
return '\n'.join([self[:3], self[3:6], self[6:9]])
class Game:
default_space = '-'
player_syms = ('X', 'O')
gamestate = collections.namedtuple("GameState", ["board", "options"]) # passed to players for decision making
def __init__(self, player1, player2):
self.players = (player1, player2)
def reset(self):
self.pn = 0
self.board = BoardStr(Game.default_space * 9)
def get_availpos(self):
# return list of string indexes of all empty spaces
avail = []
for i, c in enumerate(self.board):
if c == Game.default_space:
avail.append(i)
return avail
def has_winner(self, mvpos, psym):
# check for wins based on most recent spot a symbol was placed
return (
all([self.board[i]==psym for i in range(mvpos//3*3, 3*(mvpos//3 + 1))]) or # check relevant row
all([self.board[i]==psym for i in range(mvpos%3, (mvpos%3)+9, 3)]) or # check relevant column
all([self.board[i]==psym for i in [0, 4, 8]]) or # check diagonal
all([self.board[i]==psym for i in [2, 4, 6]]) # check anti-diagonal
)
def play(self):
self.reset()
mvpos = 0
while True:
gs = Game.gamestate(self.board, self.get_availpos())
if self.has_winner(mvpos, Game.player_syms[not self.pn]): # win check
self.players[not self.pn].on_win(gs)
self.players[self.pn].on_lose(gs)
break
elif len(gs.options) == 0: # draw check
self.players[0].on_draw(gs)
self.players[1].on_draw(gs)
break
mvpos = self.players[self.pn].get_mvpos(gs)
self.board = BoardStr( # modify board string with new move
self.board[:mvpos] + Game.player_syms[self.pn] + (self.board[mvpos+1:] if mvpos < 8 else "")
)
self.pn = not self.pn
|
b9dfb6c28943fdf4336694b8d880b2e28ad861a2 | abcrohit/codeforces_rohit | /1521A.py | 189 | 3.53125 | 4 | T=int(input())
for i in range(T):
a,b=(input().split(" "))
a=int(a)
b=int(b)
if(b==1):
print("NO")
else:
print("YES")
print(f"{a} {a*b} {a*b+a}") |
ef1149db5fa83151b2c2aea6af830238942c83cf | jc451073/workshops | /CP5632_assignment1.py | 4,809 | 3.875 | 4 | __author__ = 'jc451073'
# Initialize the constants
FILE = "books.csv"
MENU = "Menu: \nR - List required books\nC - List completed books\nA - Add new book\nM - Mark a book as completed\nQ - Quit"
def main():
print("Reading List 1.0 - by Moolayil Josmi")
booklist = []
load_books(booklist)
print(booklist)
display()
choice = input(">>>")
while choice.lower() != 'q':
if choice.lower() == 'r':
required(booklist)
elif choice.lower() == 'c':
completed(booklist)
elif choice.lower() == 'a':
booklist = add()
elif choice.lower() == 'm':
complete_a_book(booklist)
display()
choice = input(">>>")
print("{} books has been saved to {}".format(len(booklist), FILE))
print("Have a nice day :)")
def display():
"""
"""
print(MENU)
def load_books(booklist):
"""
if file exists(path_to_file) then :
open (path_to_file)
for each line in file :
print the line of the file
split and strip the content of the file
store the content into list
"""
book_file = open(FILE, 'r')
for line in book_file:
booklist.append(line.strip().split(','))
book_file.close()
def complete_a_book(booklist):
"""
call list_required_books(book_list) function
try
check for last index in book
if last index match
display()
else
open file
create nested list for to identify the contents of the file
display(the content of the book which matches the previous condition)
except
value error
null value
close the file
"""
required(booklist)
print('Enter the number of book to mark as completed')
try:
numofbooks = int(input(">>>"))
if booklist[numofbooks][3] == 'c':
print("That book is already completed")
else:
booklist[numofbooks][3] = 'c'
booksfile = open(FILE, 'w')
for i in booklist:
for k in i:
if k == "r" or k == "c":
print(k, end='', file=booksfile)
else:
print(k, end=',', file=booksfile)
print(file=booksfile)
booksfile.close()
print("{} by {} is completed".format(booklist[numofbooks][0], booklist[numofbooks][1]))
except ValueError:
print("Invalid input; enter a valid number")
complete_a_book(booklist)
def required(booklist):
"""
"""
total = 0
print('required books:')
count = 0
for i in booklist:
if 'r' in booklist[count][3]:
print("{}. {:<50s} by {:<20s} {:>15s} pages".format(count, booklist[count][0], booklist[count][1],
booklist[count][2]))
total += int(booklist[count][2])
count += 1
print('Total pages for {} books: {}'.format(count - 1, total))
def completed(booklist):
"""
"""
total_pages = 0
print('required books:')
count = 0
for i in booklist:
if 'c' in booklist[count][3]:
print("{}. {:<45s} by {:<15s} {:>10s} pages".format(count, booklist[count][0], booklist[count][1],
booklist[count][2]))
total_pages += int(booklist[count][2])
count += 1
print('Total pages for {} books: {}'.format(count + 1, total_pages))
def add():
"""
"""
title = input('Title:')
while title == "":
print('Input cannot be blank')
title = input('Title:')
author = input('Author:')
while author == "":
print("Input cannot be blank")
author = input('Author:')
valueerror = 0
pages = 0
while valueerror == 0:
try:
pages = int(input('Pages: '))
while pages <= 0:
print('Number must be >= 0')
pages = int(input('Pages: '))
valueerror = 1
except ValueError:
print('Invalid input; enter a valid number')
print("{} by {}, ({} pages) added to reading list".format(title, author, pages))
infoofbook = [title, author, str(pages), 'r']
booklist = []
load_books(booklist)
booklist.append(infoofbook)
print(booklist)
bookfile = open(FILE, 'w')
for i in booklist:
for k in i:
if k == "r" or k == "c":
print(k, end='', file=bookfile)
else:
print(k, end=',', file=bookfile)
print(file=bookfile)
bookfile.close()
main() |
690b2a6c55918dc81e356dd68e760d4fd658f171 | AravindSK1/Code-Everyday | /01. Python/Day 0019.py | 902 | 4.0625 | 4 | """
1. Given an array, find which two numbers form the target?
"""
class array_problems:
def __init__(self, arr, target_sum):
self.arr = arr
self.length = len(arr)
self.target = target_sum
def get_pairs(self):
"""
1. Create a dictionary to hold the pairs
2. The key will be the value of each array elements
3. The value corresponding to each key would be the index of the array element which forms with sum
"""
# dictionary to hold the pairs
pairs = dict()
for i in range(0, self.length):
pairs[self.arr[i]] = arr.index(self.target-self.arr[i]) if (self.target-self.arr[i]) in self.arr else "Pair not present"
return pairs
if __name__ == '__main__':
arr = [2,7,11,15]
target = 9
# class object
array_p1 = array_problems(arr, target)
print(array_p1.get_pairs())
|
574fa2bd9786e2a1e18fb04d5f64d2e0355a6a72 | hansrajdas/random | /practice/trie_autocomplete.py | 2,688 | 3.53125 | 4 | ALPHABET_SIZE = 26
class TrieNode:
def __init__(self):
self.children = [None for _ in range(ALPHABET_SIZE)]
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def _char_to_index(self, c):
return ord(c) - ord('a')
def _index_to_char(self, i):
return chr(i + ord('a'))
def insert(self, string):
ptr = self.root
for c in string:
idx = self._char_to_index(c)
if ptr.children[idx] is None:
ptr.children[idx] = TrieNode()
ptr = ptr.children[idx]
ptr.is_end_of_word = True
def update_suggestions(self, root, prefix, words):
if root is None:
return None
if root.is_end_of_word:
print(prefix)
words.append(prefix)
for i in range(ALPHABET_SIZE):
self.update_suggestions(root.children[i], prefix + self._index_to_char(i), words)
def autocomplete(self, prefix):
words = []
ptr = self.root
for c in prefix:
idx = self._char_to_index(c)
if not ptr.children[idx]:
return []
ptr = ptr.children[idx]
self.update_suggestions(ptr, prefix, words)
return words
def words_in_sorted_order_util(self, root, word):
if root is None:
return None
if root.is_end_of_word:
print(word)
for i in range(ALPHABET_SIZE):
self.words_in_sorted_order_util(root.children[i], word + self._index_to_char(i))
def words_in_sorted_order(self):
self.words_in_sorted_order_util(self.root, '')
def longest_prefix_matching(self, word):
ptr = self.root
longest_matched = ''
trie_word = ''
for c in word:
idx = self._char_to_index(c)
if ptr.is_end_of_word:
trie_word = longest_matched
if not ptr.children[idx]:
return trie_word
longest_matched += c
ptr = ptr.children[idx]
if ptr.is_end_of_word:
return longest_matched
return trie_word
def main():
trie = Trie()
for string in ['a', 'abc', 'absent', 'abscond', 'absence', 'cat', 'attribute', 'aaa', 'bat', 'ballon', 'people', 'prank', 'pop']:
trie.insert(string)
print(trie.autocomplete('a'))
print('------------ SORTED ORDER -----------')
trie.words_in_sorted_order()
print('------------ LONGEST PREFIX -----------')
print(trie.longest_prefix_matching('ab'))
print(trie.longest_prefix_matching('abc'))
print(trie.longest_prefix_matching('abcdef'))
main()
|
4d6cc112ac22ce560d127b6aacc59aa0f7683302 | JackyTao/algorithm | /threesum.py | 540 | 3.78125 | 4 | # -*- coding: utf-8 -*-
def threesum(a, target):
# a is already sorted
if len(a) <= 2:
return 0, 0, 0
i = 0
while i < len(a) - 2:
j, k = i + 1, len(a) - 1
while j < k:
if a[i] + a[j] + a[k] == target:
return i, j, k
elif a[i] + a[j] + a[k] > target:
k = k - 1
else:
j = j + 1
i = i + 1
return 0, 0, 0
if __name__ == '__main__':
print threesum([1, 2, 3, 4], 8)
print threesum([1, 2, 3, 4], 4)
|
db96cf906c34d902d49e55d31a150959d66345f4 | NitishReddy26/python | /grocery.py | 1,561 | 3.6875 | 4 | while True:
budget = float(input("Enter your budget : "))
available=budget
break
d ={"name":[], "quantity":[], "price":[]}
l= list(d.values())
name = l[0]
quantity= l[1]
price = l[2]
while True:
ch = int(input("1.ADD\n2.EXIT\nEnter your choice : "))
if ch == 1 and available>0:
pn = input("Enter product name : ")
q = int(input("Enter quantity : "))
p = float(input("Enter price of the product : "))
if p>available:
print("canot by product")
continue
else:
if pn in name:
ind = na.index(pn)
price.remove(price[ind])
quantity.insert(ind, q)
price.insert(ind, p)
available = budget-sum(price)
print("\namount left", available)
else:
name.append(pn)
quantity.append(q)
price.append(p)
available= budget-sum(price)
print("\namount left", available)
elif available<= 0:
print("no amount left")
else:
break
print("\nAmount left : Rs.", available)
if available in price:
print("\nyou an buy", na[price.index(available)])
print("\n\n\nGROCERY LIST")
for i in range(len(name)):
print(name[i],quantity[i],price[i])
|
83320f3d42afbc1c9e87926a26162af392a0b11f | augustedupin123/python_practice | /p11_new.py | 1,254 | 3.828125 | 4 | '''for i in range(1,6):
for j in range(1,6):
print(j, end="")
print()'''
'''for i in range(1,6):
for j in range(1,6):
print(j, end="")'''
'''for i in range(1,6):
for j in range(1,6):
print(j)'''
'''for i in range(1,6):
print(str(i)*5)'''
'''for i in range(1,6):
print((i)*5)'''
'''for i in range(65,70):
for j in range(65,70):
print(chr(i), sep="", end="")
print()'''
'''for i in range(65,70):
for j in range(65,70):
print(chr(i), end="")
print()'''
'''j = 5
while(j>0 and j<=5):
i = 5
while(i>0 and i<=5):
print(i, end="")
i -=1
j-=1
print()'''
'''for i in range(1,6):
for j in range(0, 5-i):
print(' ', end= "")
for j in range(1, i+1):
print(j, end="")
print()'''
def sec_lar(list1):
max1 = 0
max2 = 0
list2 = []
for i in range(len(list1)):
if(max1<list1[i]):
max1 = list1[i]
for j in range(len(list1)):
if(list1[j]!=max1):
list2.append(list1[j])
for k in range(len(list2)):
if(list2[k]>max2):
max2 = list2[k]
return (max2)
a = sec_lar([23,1244,235,23,423,34,23,235,23])
print (a)
|
5778497ccf5e554d8d6a99f21f6ecc6d1733ade7 | zhangcj5131/AI_teaching | /basic/26.闭包中使用外部变量.py | 732 | 3.9375 | 4 | # 定义一个外部函数
def func_out(num1):
# 定义一个内部函数
def func_inner(num2):
# 这里本意想要修改外部num1的值,实际上是在内部函数定义了一个局部变量num1,如果想调用外面的 num1,必须使用nonlocal
nonlocal num1 # 告诉解释器,此处使用的是 外部变量a
# 修改外部变量num1
num1 = 10
# 内部函数使用了外部函数的变量(num1)
result = num1 + num2
print("结果是:", result)
print(num1)
func_inner(1)
print(num1)
# 外部函数返回了内部函数,这里返回的内部函数就是闭包
return func_inner
# 创建闭包实例
f = func_out(1)
# 执行闭包
f(2) |
8ed80228ad2b2991f0c247497fd0cd601eabe17d | fjfhfjfjgishbrk/AE401-Python | /zerojudge/a883.py | 279 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 11:58 2020
@author: fdbfvuie
"""
a, b = map(int, input().split())
c, d = map(int, input().split())
e, f = map(int, input().split())
if c >= b and e >= b and e >= d:
print("Happy")
else:
print("QQ") |
0b2ee115102da0dff844ffdbfff0f1445e2b6017 | anantkaushik/leetcode | /1329-sort-the-matrix-diagonally.py | 1,243 | 4.375 | 4 | """
Problem Link: https://leetcode.com/problems/sort-the-matrix-diagonally/
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and
going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0],
where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].
Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
"""
class Solution:
def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
diagnoals = collections.defaultdict(list)
for i, row in enumerate(mat):
for j, val in enumerate(row):
diagnoals[i-j].append(val)
for d in diagnoals.values():
d.sort(reverse=True)
for i, row in enumerate(mat):
for j, _ in enumerate(row):
mat[i][j] = diagnoals[i-j].pop()
return mat
|
f1d2bd988e26ad29e12893c175013dfd270e0327 | idebosmitha/Python-practice | /Day 6/factors.py | 108 | 3.890625 | 4 | n = int(input('Enter a number: '))
f = 2
while n != 1:
if n % f == 0:
print(f)
n /= f
else:
f += 1
|
8d8e8b8f85eb796a4528edea56a12e91678d2f17 | DrewOrtego/Order-Book-Programming-Problem | /Pricer.py | 12,767 | 3.9375 | 4 | """
Pricer.py
Andrew Ortego
12/27/2017
Description:
Solves the Order Book Programming Problem. Reads an input-file containing one command per line. Each command will run an
Add or Remove order. When the size of an order matches or exceeds the given target size, output is printed to the
console reporting the best buy or sell price available. When a Remove order is executed, output is printed if the size
of an order had previously met the target size.
Usage:
python Pricer.py <target size integer>
Pricer will look for a file called pricer.in to retrieve input commands.
"""
import os
import sqlite3
import sys
class Order:
def __init__(self, timestamp, type_literal, order_id, size, price=0.0, side="."):
"""
:param timestamp: The time when this message was generated by the market, as milliseconds since midnight.
:param type_literal: Denotes an Add or a Reduce order with an "A" or an "R".
:param order-id: The unique string that identifies the order.
:param size: The size in shares of this order, when it was initially sent to the market by some stock
trader.
:param price: The limit price of this order.
:param side: A 'B' if this is a buy order (a bid), or a 'S' if this is a sell order (an ask).
"""
self.timestamp = int(timestamp)
self.type_literal = type_literal
self.order_id = order_id
self.size = int(size)
self.price = float(price)
self.side = side
def add_order_to_book(self):
"""
Update the book by adding a new order.
"""
data = (self.timestamp, self.type_literal, self.order_id, self.size, self.price, self.side)
db.execute('INSERT INTO orders VALUES(?, ?, ?, ?, ?, ?)', data)
db_con.commit()
def reduce_order(self):
"""
Update a preexisting order with a Reduce command. Delete the
"""
db.execute('SELECT * FROM orders WHERE orderId=? ORDER BY timestamp DESC', (self.order_id,))
preexisting_order = db.fetchall()[0]
reduced_size = preexisting_order[3] - self.size
if reduced_size <= 0:
db.execute('DELETE FROM orders WHERE orderId=?', (self.order_id,))
db_con.commit()
elif reduced_size > 0:
db.execute('UPDATE orders SET size=? WHERE orderId=?', (reduced_size, self.order_id))
db_con.commit()
else:
pass # placeholder for future error checking
class Book:
def __init__(self, target_size):
"""
Creates the book which will keep track of all available shares and current buy/sell prices.
"""
self.ask_size = 0
self.bid_size = 0
self.input_data = self.get_input_data()
self.target_size = self.get_target_size(target_size)
def calculate_price(self, order):
"""
Calculate the best possible bid or ask price and print relevant information.
:param order: The order which triggered a new update to the book.
:return: Float value which represents the current buy/sell price.
"""
if order.side == 'B':
db.execute('SELECT * FROM orders WHERE side=? ORDER BY price DESC, size DESC', (order.side,))
elif order.side == 'S':
db.execute('SELECT * FROM orders WHERE side=? ORDER BY price ASC, size DESC', (order.side,))
order_data = db.fetchall()
total_shares = 0
price = 0.00
for share in order_data: # ToDo make this a recursive function
if total_shares == self.target_size:
return price
elif total_shares < self.target_size:
if total_shares + share[3] >= self.target_size:
price += (self.target_size - total_shares) * share[4]
total_shares += self.target_size - total_shares
return price
else:
total_shares += share[3]
price += share[3] * share[4]
elif total_shares > self.target_size:
print("ERROR: Number of shares exceeds target size, price is incorrect")
return price
@staticmethod
def get_input_data():
"""
Attempt to open the file and parse the input, then remove any newline characters at the end of a line.
Assume the format of the data is correct/expected and that no error/consistency checking is required.
"""
input_file_path = os.path.join(os.getcwd(), 'pricer.in')
try:
with open(input_file_path) as file_data:
input_data = file_data.readlines()
except FileNotFoundError:
print('File not found: {0}\nPut the pricer.in file in this script\'s directory.'.format(input_file_path))
sys.exit('Exiting program...')
else:
return [line.strip() for line in input_data]
@staticmethod
def get_target_size(target_size):
"""
Cast the given target_size to an integer
"""
try:
return int(target_size)
except ValueError:
print('Incorrect argument provided for target-size. Please specify an integer. (e.g. 200)')
sys.exit('Exiting program...')
def process_command(self, line):
"""
Parse the command, create a new order and add it to the book.
:param line: a single space-delineated command from the input file.
"""
commands = line.split(' ')
if self.verify_input(commands):
if len(commands) == 6: # Switch the side and size parameters before instantiating a new order
commands[3], commands[5] = commands[5], commands[3]
order = Order(*commands)
self.update_book(order)
else:
print(" Skipping current command.")
def update_book(self, order):
"""
Add an order to the book unless it's a reduce order in which case reduce the size of an existing order. Update
the current bid or ask size accordingly. If the update requires output, print the relevant message.
:param order: the order being used the calculate total bid/ask size.
"""
if order.type_literal == 'R':
db.execute('SELECT * FROM orders WHERE orderId=?', (order.order_id,))
preexisting_order_data = db.fetchall()[0] # Only one result is expected from the query
preexisting_order = Order(*list(preexisting_order_data))
order.reduce_order()
if preexisting_order.side == 'B':
if self.bid_size - order.size >= self.target_size:
price = self.calculate_price(preexisting_order)
print("{0} S {1:.2f}".format(order.timestamp, price))
elif self.bid_size >= self.target_size:
print('{0} S NA'.format(order.timestamp))
self.bid_size -= order.size
elif preexisting_order.side == 'S':
if self.ask_size - order.size >= self.target_size:
price = self.calculate_price(preexisting_order)
print('{0} B {1:.2f}'.format(order.timestamp, price))
elif self.ask_size >= self.target_size:
print('{0} B NA'.format(order.timestamp))
self.ask_size -= order.size
elif order.type_literal == 'A':
if order.side == 'B':
self.bid_size += order.size
order.add_order_to_book()
if self.bid_size >= self.target_size:
price = self.calculate_price(order)
print("{0} S {1:.2f}".format(order.timestamp, price))
elif order.side == 'S':
self.ask_size += order.size
order.add_order_to_book()
if self.ask_size >= self.target_size:
price = self.calculate_price(order)
print("{0} B {1:.2f}".format(order.timestamp, price))
@staticmethod
def verify_input(commands):
"""
Check validity of a given command. Print an error message to the console if an error is found.
:return: None if an issue is found. Otherwise return the original list of commands
"""
# Check number of commands, should either be 4 (Reduce) or 6 (Add)
if len(commands) is 4:
# Check timestamp
pass
# Check literal
if commands[1] != "R":
print("Invalid input detected; unrecognized literal: {0}. Please provide an R.".format(commands[1]),
end="")
return None
# Check order id
db.execute('SELECT * FROM orders WHERE orderId=? ORDER BY timestamp DESC', (commands[2],))
data = db.fetchall()
if len(data) == 0:
print("No record found with orderId: {0}. Reduce cannot be performed.".format(commands[2]),
end="")
return None
elif len(data) > 1:
print("Multiple records found with orderId: {0}. Reduce should only target one unique order.".format(
commands[2]), end="")
return None
# Check size type
try:
int(commands[3])
except ValueError:
print("Invalid input detected; non-integer value provided for size: {0}.".format(commands[3]), end="")
return None
# Check size value
if int(commands[3]) < 0:
print("Invalid input detected; negative integer provided for size: {0}.".format(commands[3]), end="")
return None
# All checks passed
return commands
elif len(commands) is 6:
# Check timestamp
pass
# Check literal
if commands[1] != "A":
print("Invalid input detected; unrecognized literal: {0}.".format(commands[1]), end="")
return None
# Check order id
db.execute('SELECT * FROM orders WHERE orderId=? ORDER BY timestamp DESC', (commands[2],))
data = db.fetchall()
if len(data) > 0:
print("Record with orderId {0} already exists. Cannot insert a new record with duplicate Id.".format(
commands[2]), end="")
return None
# Check side
if commands[3] not in ["B", "S"]:
print("Invalid input detected; unrecognized side: {0}. Please provide a B or S.".format(commands[3]),
end="")
return None
# Check price
try:
float(commands[4])
except ValueError:
print("Invalid price detected; non-float value provided for price: {0}.".format(commands[4]), end="")
return None
# Check size type
try:
int(commands[5])
except ValueError:
print("Invalid input detected; non-integer value provided for size: {0}.".format(commands[5]), end="")
return None
# Check size value
if int(commands[5]) < 0:
print("Invalid input detected; negative integer provided for size: {0}.".format(commands[5]), end="")
return None
# All checks passed
return commands
else:
print("Unexpected number of commands provided: {0}.".format(len(commands)), end="")
return None
def initialize_database():
"""
Prepare a database prior to processing input. This function will delete an on-disk database file if found, so if you
want to keep previous databases, relocate or rename it before running this script.
"""
global db
global db_con
# db_con = sqlite3.connect('book.db') # Use to create a database on disk
db_con = sqlite3.connect(':memory:') # Use for performance boost but no database on disk
db = db_con.cursor()
try:
db.execute('DROP TABLE orders')
db_con.commit()
except sqlite3.OperationalError:
pass
finally:
db.execute('''CREATE TABLE orders
(timestamp INTEGER, type TEXT, orderId TEXT, size INTEGER, price REAL, side TEXT)''')
db_con.commit()
def main():
"""
Create a new book to open the input file, parse input from the file, then begin processing input line-by-line.
"""
initialize_database()
book = Book(sys.argv[1])
for line in book.input_data:
book.process_command(line)
if __name__ == '__main__':
main()
|
bef1890ddee968d62ecb44f0926de06da4b4dc91 | abidmuin/AI_Lab | /BFS.py | 1,247 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 08:58:22 2019
@author: muin
"""
from collections import defaultdict
class Graph:
#Constructor
def __init__(self):
#default dictionary to store graph
self.graph = defaultdict(list)
#function to add edge to graph
def addEdge(self, u,v):
self.graph[u].append(v)
#function to print a bfs of graph
def bfs(self, s):
#mark all the vertices as not visited
visited = [False] * (len(self.graph))
#create a queue for bfs
queue = []
#mark source node as visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
#dequeue a vertex from queue and print it
s = queue.pop(0)
print (s, end = " ")
for i in self. graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
print ("Following is BFS" " (Starting from vertex 2)")
g.bfs(2) |
40f259e226818c6752ea031bae1c052893eaa918 | martynov85m/pyTests | /04_student.py | 1,176 | 4 | 4 | # -*- coding: utf-8 -*-
# (цикл while)
# Ежемесячная стипендия студента составляет educational_grant руб., а расходы на проживание превышают стипендию
# и составляют expenses руб. в месяц. Рост цен ежемесячно увеличивает расходы на 3%, кроме первого месяца
# Составьте программу расчета суммы денег, которую необходимо единовременно попросить у родителей,
# чтобы можно было прожить учебный год (10 месяцев), используя только эти деньги и стипендию.
# Формат вывода:
# Студенту надо попросить ХХХ.ХХ рублей
educational_grant, expenses = 10000, 12000
# TODO здесь ваш код
i = 0
inflation = 0.03
total = 2000
while i < 9:
total += (((expenses * inflation) + expenses) - educational_grant)
inflation += 0.03
i += 1
print("Студенту надо попросить", total, "рублей.") |
a61ca628156a0b89bbf084475faf02727f41280f | LeenaKH123/Python2 | /06_advanced-python-concepts/06_07_setcomp_union.py | 1,110 | 4.21875 | 4 | # Use the union operator `|` to intersect the two given sets
# inside of a set comprehension that squares each item of the
# set if the number is higher than `2`.
# You should write the whole code logic in only one line.
#
# Expected output: {16, 9, 25, 49}
#
# Remember that sets are unordered collections, so your numbers
# might come out in a different order.
s = {1, 2, 3, 4}
t = {2, 3, 4, 5, 7}
# ---working code 1 ----
# union_set = set()
# for itemS in s:
# for itemT in t:
# if itemS > 2:
# union_set.add(itemS)
# if itemT > 2:
# union_set.add(itemT)
# union_set_squared = [number**2 for number in union_set]
# print(union_set_squared)
#-----end of working code 1------
#working code 2
# union_set = s | t
# union_set2 = set()
# for x in union_set:
# if x>2:
# union_set2.add(x)
# union_set_squared = [number**2 for number in union_set2]
# print(union_set_squared)
# ---end of working code 2 ---
# union_set = set([number**2 for number in s|t if number > 2 ])
union_set = {number**2 for number in s|t if number > 2}
print(union_set) |
e501dba7446860753ad3b1b2637ca862e7703bda | arsaikia/Data_Structures_and_Algorithms | /Data Structures and Algorithms/Cracking The Coding Interview/Arrays and Strings/5. One Away.py | 1,307 | 3.984375 | 4 | '''
1.5 One Away: There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check if they are
one edit (or zero edits) away.
EXAMPLE
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bae -> false
'''
def oneAway(s1, s2) -> bool:
if abs(len(s1) - len(s2)) > 1:
return False
if len(s1) == len(s2):
return replaceChar(s1, s2)
if len(s1) + 1 == len(s2):
return insertChar(s1, s2)
if len(s2) + 1 == len(s1):
return insertChar(s2, s1)
def replaceChar(s1, s2):
isReplaced = False
idx = 0
while idx < len(s1):
if s1[idx] != s2[idx]:
if isReplaced:
return False
isReplaced = True
return True
def insertChar(stringOne, stringTwo):
idxOne, idxTwo = 0, 0
while idxOne < len(stringOne) and idxTwo < len(stringTwo):
if stringOne[idxOne] != stringTwo[idxTwo]:
if idxOne != idxTwo:
return False
idxOne += 1
else:
idxOne += 1
idxTwo += 1
return True
if __name__ == "__main__":
s1, s2 = "pale", "bae"
print(oneAway(s1, s2))
|
27cdd19f57e62ffd7c3649eee3dcda7ff4b2ceb1 | eugen1701/BKT-plan | /menu.py | 2,521 | 3.546875 | 4 | #CONSTANTS:
NUMBER_DIRECTIONS = 8
NUMBER_OF_THE_UPPERLEFT_EDGE = 0
NUMBER_OF_THE_LOWERRIGHT_EDGE = 9 #because python I cannot set it in main :)
di = [-1, -1, 0, 1, 1, 1, 0, -1]
dj = [0, 1, 1, 1, 0, -1, -1, -1]
#DECLARATION:
matrice = []
matrice2 = []
#matrice is for the data we read and matrice2 is for computing the paths, the results
n = 0
xp = 0
yp = 0
#xp and yp are the initial position of the P (paznic)
#PROCEDURES:
def bune(i, j):
return i>=NUMBER_OF_THE_UPPERLEFT_EDGE and i<=NUMBER_OF_THE_LOWERRIGHT_EDGE and j>=NUMBER_OF_THE_UPPERLEFT_EDGE and j<=NUMBER_OF_THE_LOWERRIGHT_EDGE
def solutie(i, j):
return i == NUMBER_OF_THE_UPPERLEFT_EDGE or j == NUMBER_OF_THE_UPPERLEFT_EDGE or i == NUMBER_OF_THE_LOWERRIGHT_EDGE or j == NUMBER_OF_THE_LOWERRIGHT_EDGE
#it is a solution when the coordonates are on the edge of the matrix
def afis():
for i in range(10):
print(matrice2[i])
print("\n")
print("\n")
print("\n")
def bkt(pas, i , j):
for k in range(NUMBER_DIRECTIONS):
ii = i + di[k]
jj = j + dj[k]
if bune(ii, jj):
if matrice[ii][jj] == 0 and matrice2[ii][jj] == 0:
matrice2[ii][jj] = pas
if solutie(ii, jj):
afis()
matrice[ii][jj] = -1 # infinit loop but why? BUG ---> solved
matrice2[ii][jj] = 0# because I was putting 0 it was following always the same path
break
bkt(pas+1, ii, jj)
matrice2[ii][jj]=0 # It puts zero when it reverse
#MAIN:
def main():
file_object = open("data.txt", "r")
stuff = file_object.readlines()
n = int(stuff[0])
NUMBER_OF_THE_LOWERRIGHT_EDGES = n-1
for i in range(n):
line = []
for j in range(n):
line.append(0)
matrice.append(line)
stuff = stuff[1:]
for i in range(n):
for j in range(n):
try:
if stuff[i][j] == "x" :
matrice[i][j] = -1
elif stuff[i][j] == "P":
matrice[i][j] = 1
xp = i
yp = j
except:
break
for i in range(n):
line = []
for j in range(n):
if i == xp and j == yp:
line.append(1)
else:
line.append(0)
matrice2.append(line)
bkt(2, xp, yp)
main() |
5cf3208cdd55b8300b541000192bab8fadb470ee | vikasdongare/python-for-everbody | /Using Python to Access Web Data/Assign2.py | 512 | 3.921875 | 4 | #In this assignment you will read through and parse a file with text and numbers
#You will extract all the numbers in the file and compute the sum of the numbers
#Date :- 29 April 2020
#Done By :- Vikas Dongare
import re
name = input("ENTER FILENAME: ")
if len(name) < 1: name = "sample.txt"
handle = open(name)
sum = 0
for line in handle:
num = re.findall('[0-9]+',line)
if len(num) < 1:
continue
for sno in num:
no = int(sno)
sum = sum + no
print("SUM: ",sum)
|
e14c5a6c8279621ac9775e68821535853f05a9a2 | WickedWahine/calculator-2 | /calculator.py | 1,364 | 4.25 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
#Start loop to receive calculation request
while True:
input_string = input("Calculate > ")
tokens = input_string.split(' ')
operator = tokens[0]
#Allow user to quit calculator app
if 'q' in tokens:
print("You will exit")
break
else:
if len(tokens) < 2:
print("I need at least 1 operator and 1 number")
continue
elif len(tokens) == 2:
num1 = float(tokens[1])
elif len(tokens) == 3:
num1 = float(tokens[1])
num2 = float(tokens[2])
else:
print("Include no more than 2 numbers")
continue
if operator == "+":
print(add(num1, num2))
elif operator == "-":
print(subtract(num1, num2))
elif operator == "*":
print(multiply(num1, num2))
elif operator == "/":
print(divide(num1, num2))
elif operator == "pow":
print(power(num1, num2))
elif operator == "mod":
print(mod(num1, num2))
elif operator == "cube":
print(cube(num1))
elif operator == "square":
print(square(num1))
else:
print("I need one operator followed by numbers") |
ca9f45a6fbfc6745ea7880e5910e36ab0fe9c159 | UtkarshGoelUT/Git-Contri-Tutorial | /char_count.py | 352 | 3.84375 | 4 | # return dictionary with charater as key and number of occurences as value
def char_count(s):
# initializing dicionary
count = dict()
# iterating over string
for c in s:
if c in count:
count[c] += 1
# find the error here
return count
if __name__ == "__main__":
s = input()
print(char_count(s))
|
d0bd6a5abe4d04708e3a09d149845066ba8dd50c | nickbuker/toy_airflow | /src/file_creator.py | 204 | 3.515625 | 4 | class FileCreator:
def __init__(self, file: str):
self.file = file
def create(self) -> None:
with open(self.file, 'w+') as f:
f.write('Hello, PuPPy!')
return
|
a0b5644e3c0997760724051c66d8b78aad3fec47 | AtsukiImamura/parking-kyoto | /constants/maneuver.py | 1,183 | 3.734375 | 4 |
from enum import Enum
def get_by_key(key):
"""
ケバブケースの文字列から動作タイプを取得する。定義されていない場合は Maneuver.STRAIGHT を返す
"""
for man in Maneuver:
if key == man.to_kebab_case():
return man
return Maneuver.STRAIGHT
class Maneuver(Enum):
"""
右左折などの動作タイプを定義
"""
STRAIGHT = 0
TURN_SLIGHT_RIGHT = 1
TURN_RIGHT = 10
TURN_SHARP_RIGHT = 20
UTURN_RIGHT = 30
RUMP_RIGHT = 40
FORK_RIGHT = 50
TURN_SLIGHT_LEFT = -1
TURN_LEFT = -10
TURN_SHARP_LEFT = -20
UTURN_LEFT = -30
RUMP_LEFT = -40
FORK_LEFT = -50
def to_string(self):
"""
動作タイプ名称だけの文字列にして返す
"""
return str(self).replace('Maneuver.', '')
def to_string_lower_case(self):
"""
小文字にして返す
"""
return self.to_string().lower()
def to_kebab_case(self):
"""
ケバブケースにして返す
"""
return self.to_string_lower_case().replace('_', '-')
# def get_by_string(str_code):
|
e64450c52f65ff365c173d3ec4226c08969d8072 | vim-hjk/python-algorithm | /code/merge_2.py | 910 | 4 | 4 | def mergesort(num):
if len(num) > 1:
mid = len(num) // 2
left = num[:mid]
right = num[mid:]
left_list = mergesort(left)
right_list = mergesort(right)
return merge(left_list, right_list)
else:
return num
def merge(left_list, right_list):
left_idx = 0
right_idx = 0
num = []
while left_idx < len(left_list) and right_idx < len(right_list):
if left_list[left_idx] < right_list[right_idx]:
num.append(left_list[left_idx])
left_idx += 1
else:
num.append(right_list[right_idx])
right_idx += 1
while left_idx < len(left_list):
num.append(left_list[left_idx])
left_idx += 1
while right_idx < len(right_list):
num.append(right_list[right_idx])
right_idx += 1
return num
num = [3, 5, 1, 2, 9, 6, 4, 8, 7]
print(mergesort(num)) |
b042b3a3edde2e5a083c4157b258d566c2eda36d | lgabs/udacity-bikeshare | /chicago_bikeshare_pt.py | 17,787 | 4.125 | 4 | # coding: utf-8
# autor: Luan Fernandes (lgabs)
# Resumo do código:
# Trata-se de tarefas que exploram os dados de uso de bicicletas compartilhadas na região de Chicago pela empresa Divvy
# As tarefas compõem o projeto 1 do curso de Data Science 1 da Udacity
# Começando com os imports
import csv
import matplotlib.pyplot as plt
# Vamos ler os dados como uma lista de dicionários em que os labels das features são chaves
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
#reader = csv.reader(file_read)
reader = csv.DictReader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verificar quantas linhas nós temos
print("Número de linhas:")
print(len(data_list))
# Imprimindo a primeira linha de data_list para verificar se funcionou.
# Como a lista é uma lista de dicionários, esta linha será a primeira viagem e suas informações (features).
print("Linha 0: ")
print(data_list[0])
# Imprimindo as informações da primeira viagem (primeira linha do arquivo csv):
print("Dados da primeira viagem registrada:")
print(list(data_list[0].values()))
input("Aperte Enter para continuar...")
# TAREFA 1
# TODO: Imprima as primeiras 20 linhas usando um loop para identificar os dados.
print("\n\nTAREFA 1: Imprimindo as primeiras 20 amostras")
for k in range(20):
print(list(data_list[k].values()))
# Sendo uma lista de dicionários, cada índice da lista é uma viagem registrada em forma de
# dicionário. Podemos acessar as features usando os seus próprios nomes como chaves
# Exemplo: sample = data_list[k] retorna a k-ésima viagem como um dicionário. sample['Gender'] retorna o gênero.
# As features são:
# ['Start Time', 'End Time', 'Trip Duration', 'Start Station', 'End Station', 'User Type', 'Gender', 'Birth Year']
input("Aperte Enter para continuar...")
# TAREFA 2
# TODO: Imprima o `gênero` das primeiras 20 linhas
print("\nTAREFA 2: Imprimindo o gênero das primeiras 20 amostras")
# Impressão com a numeração para conferir as 20 amostras
for i, sample in enumerate(data_list[:20]):
print('{:>7}: {}'.format(i+1,sample['Gender']))
input("Aperte Enter para continuar...")
# TAREFA 3
# TODO: Crie uma função para adicionar as colunas(features) de uma lista em outra lista, na mesma ordem
# Solução: já que se optou por uma lista de dicionários, usamos diretamente o label da feature desejada.
# Para não alterar o tratamento dos asserts (que acessam a feature pelo índice e não pelo label),
# criou-se uma lista de fetaures para associar o índice de entrada com a respectiva feature
def column_to_list(data: list, index: int):
# Função para criar uma lista de valores de uma certa feature a partir do dataset.
# Argumentos:
# data: lista de dicionários com as features de cada viagem e seus valores
# index: índice que representa o label de uma feature
# Retorna:
# feature_list: lista com os valores das features desejadas para as viagens descritas em 'data'
feature_list = []
features = list(data[0].keys())
feature_list = [trip[features[index]] for trip in data]
return feature_list
# Vamos checar com os gêneros se isso está funcionando (apenas para os primeiros 20)
print("\nTAREFA 3: Imprimindo a lista de gêneros das primeiras 20 amostras")
print(column_to_list(data_list, -2)[:20])
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(column_to_list(data_list, -2)) is list, "TAREFA 3: Tipo incorreto retornado. Deveria ser uma lista."
assert len(column_to_list(data_list, -2)) == 1551505, "TAREFA 3: Tamanho incorreto retornado."
assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", "TAREFA 3: A lista não coincide."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Agora sabemos como acessar as features, vamos contar quantos Male (Masculinos) e Female (Femininos) o dataset tem
# TAREFA 4
# TODO: Conte cada gênero. Você não deveria usar uma função para fazer isso.
male = 0
female = 0
for trip in data_list:
if trip['Gender'] == 'Male':
male += 1
elif trip['Gender'] == 'Female':
female += 1
# Verificando o resultado
print("\nTAREFA 4: Imprimindo quantos masculinos e femininos nós encontramos")
print("Masculinos: ", male, "\nFemininos: ", female)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert male == 935854 and female == 298784, "TAREFA 4: A conta não bate."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Por que nós não criamos uma função para fazer isso?
# TAREFA 5
# TODO: Crie uma função para contar os gêneros. Retorne uma lista.
# Isso deveria retornar uma lista com [count_male, count_female] (exemplo: [10, 15] significa 10 Masculinos, 15 Femininos)
def count_gender(data: list):
# Função para contar o número de usuários para cada gênero (Masculino ou Feminino).
# Argumentos
# data: lista de dicionários com as features de cada viagem e seus valores
# Retorna:
# [male,female]: uma lista com as quantidades de cada gênero
male = 0
female = 0
for trip in data:
if trip['Gender'] == 'Male':
male += 1
elif trip['Gender'] == 'Female':
female += 1
return [male, female]
print("\nTAREFA 5: Imprimindo o resultado de count_gender")
print(count_gender(data_list))
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(count_gender(data_list)) is list, "TAREFA 5: Tipo incorreto retornado. Deveria retornar uma lista."
assert len(count_gender(data_list)) == 2, "TAREFA 5: Tamanho incorreto retornado."
assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TAREFA 5: Resultado incorreto no retorno!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Agora que nós podemos contar os usuários, qual gênero é mais prevalente?
# TAREFA 6
# TODO: Crie uma função que pegue o gênero mais popular, e retorne este gênero como uma string.
# Esperamos ver "Masculino", "Feminino", ou "Igual" como resposta.
def most_popular_gender(data: list):
# Função para determinar o gênero mais popular.
# Argumentos:
# data: lista de dicionários com as features de cada viagem e seus valores
# Retorna:
# answer: string com o gênero mais popular. Caso a popularidade seja igual, retorna 'Igual'.
answer = ""
# gerar a lista com número de homens e mulheres com função já desenvolvida count_gender
n_genders = count_gender(data_list)
if n_genders[0] > n_genders[1]:
answer += 'Masculino'
elif n_genders[0] < n_genders[1]:
answer += 'Feminino'
else:
answer += 'Igual'
return answer
print("\nTAREFA 6: Qual é o gênero mais popular na lista?")
print("O gênero mais popular na lista é: ", most_popular_gender(data_list))
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(most_popular_gender(data_list)) is str, "TAREFA 6: Tipo incorreto no retorno. Deveria retornar uma string."
assert most_popular_gender(data_list) == "Masculino", "TAREFA 6: Resultado de retorno incorreto!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Se tudo está rodando como esperado, verifique este gráfico!
print("\nGráfico de quantidades de uso para cada gênero:")
gender_list = column_to_list(data_list, -2)
types = ["Male", "Female"]
quantity = count_gender(data_list)
y_pos = list(range(len(types)))
plt.bar(y_pos, quantity)
plt.ylabel('Quantidade')
plt.xlabel('Gênero')
plt.xticks(y_pos, types)
plt.title('Quantidade por Gênero')
plt.show(block=True)
input("Aperte Enter para continuar...")
# TAREFA 7
# TODO: Crie um gráfico similar para user_types. Tenha certeza que a legenda está correta.
print("\nTAREFA 7: Verifique o seguinte gráfico! Ele indica as quantidades de usos entre homens e mulheres")
def count_users(data: list):
# Função para contar os usuários de cada tipo.
# Argumentos:
# data: lista de dicionários com as features de cada viagem e seus valores
# Retorna:
# [subscribers, customers]: lista com a quantidade de cada tipo de usuário
subscribers = 0
customers = 0
for trip in data:
if trip['User Type'] == 'Subscriber':
subscribers += 1
elif trip['User Type'] == 'Customer':
customers += 1
return [subscribers, customers]
user_list = column_to_list(data_list, 6)
user_types = ["Subscriber", "Customer"]
user_quantity = count_users(data_list)
y_pos = list(range(len(user_types)))
plt.bar(y_pos, user_quantity)
plt.ylabel('Quantidade')
plt.xlabel('Tipo de Usuário')
plt.xticks(y_pos, types)
plt.title('Quantidade por Tipo de Usuário')
plt.show(block=True)
input("Aperte Enter para continuar...")
# TAREFA 8
# TODO: Responda a seguinte questão
male, female = count_gender(data_list)
print("\nTAREFA 8: Por que a condição a seguir é Falsa?")
print("male + female == len(data_list):", male + female == len(data_list))
answer = "Porque há viagens onde a informação de gênero é uma string vazia ''. Pelas 20 primeiras amostras, há viagens onde a string a 'End Station' é destacada por um sinal de asterisco e não há informações de gênero ou ano de nascimento. Assim, a soma de contagens 'Male' e 'Female' é menor que total de contagens de usos das bicicletas."
print("resposta:", answer)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert answer != "Escreva sua resposta aqui.", "TAREFA 8: Escreva sua própria resposta!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Vamos trabalhar com trip_duration (duração da viagem) agora. Não conseguimos tirar alguns valores dele.
# TAREFA 9
# TODO: Ache a duração de viagem Mínima, Máxima, Média, e Mediana.
# Você não deve usar funções prontas para fazer isso, como max() e min().
def statistics_from_list(data: list):
# Função que calcula estatísticas básicas das durações de viagens.
# Argumentos:
# data: lista de strings representando as durações das viagens
# Retorna:
# min_trip: duração mínima das viagens
# max_trip: duração máxima das viagens
# mean_trip: média de duração das viagens
# median_trip: mediana da duração das viagens
# Vamos criar uma lista de floats para operar sobre ela, pois o argumento vem em formato de string
trip_durations = [float(i) for i in data]
# para calcular a mediana, a lista precisa estar ordenada
trip_durations.sort()
n = len(trip_durations)
min_trip = trip_durations[0]
max_trip = trip_durations[0]
mean_trip = trip_durations[0]/n
for elem in trip_durations[1:]:
if min_trip > elem:
min_trip = elem
if max_trip < elem:
max_trip = elem
mean_trip += elem/n
if n%2 == 0:
median_trip = (trip_durations[int(n/2-1)] + trip_durations[int(n/2+1-1)])/2
else:
median_trip = trip_durations[int((n+1)/2-1)]
return min_trip, max_trip, mean_trip, median_trip
min_trip, max_trip, mean_trip, median_trip = statistics_from_list(column_to_list(data_list, 2))
print("\nTAREFA 9: Imprimindo o mínimo, máximo, média, e mediana")
print("Min: ", min_trip, "Max: ", max_trip, "Média: ", mean_trip, "Mediana: ", median_trip)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert round(min_trip) == 60, "TAREFA 9: min_trip com resultado errado!"
assert round(max_trip) == 86338, "TAREFA 9: max_trip com resultado errado!"
assert round(mean_trip) == 940, "TAREFA 9: mean_trip com resultado errado!"
assert round(median_trip) == 670, "TAREFA 9: median_trip com resultado errado!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# TAREFA 10
# Gênero é fácil porque nós temos apenas algumas opções. E quanto a start_stations? Quantas opções ele tem?
# TODO: Verifique quantos tipos de start_stations nós temos, usando set()
# talvez o ideal seja o objeto se chamar 'station_type' ou 'stations', mas vou usar o sugerido.'user_types' foi recomendado acima para tipo de usuário
start_stations_list = column_to_list(data_list, 3)
user_types = list(set(start_stations_list))
print("\nTAREFA 10: Imprimindo as start stations:")
print(len(user_types))
print(user_types)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert len(user_types) == 582, "TAREFA 10: Comprimento errado de start stations."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
print("\nTAREFA 11: Verificação da documentação do código (ver código em um editor de texto).")
# TAREFA 11
# Volte e tenha certeza que você documenteou suas funções. Explique os parâmetros de entrada, a saída, e o que a função faz. Exemplo:
# def new_function(param1: int, param2: str) -> list:
'''
Função de exemplo com anotações.
Argumentos:
param1: O primeiro parâmetro.
param2: O segundo parâmetro.
Retorna:
Uma lista de valores x.
'''
input("Aperte Enter para continuar...")
# TAREFA 12 - Desafio! (Opcional)
# TODO: Crie uma função para contar tipos de usuários, sem definir os tipos
# para que nós possamos usar essa função com outra categoria de dados.
print("Você vai encarar o desafio? (yes ou no)")
answer = "yes"
print(answer)
def count_items(column_list: list):
# Função que calcula quantas corrências distintas há em uma lista de valores de features retirada do dataset
# Assim, pode-se aplicá-la em qualquer uma das features do dataset
# Argumentos:
# column_list: lista de valores de features para cada viagem do dataset
# Retorna:
# item_types: tipos distintos de valores para a feature em questão
# count_items: ocorrências de cada tipo dentro da column_list
item_types = list(set(column_list))
item_types.sort() # o sort ajudará quando os types tem ordem própria (ex: meses em formato numérico ou ano de nascimento)
count_items = []
for item_type in item_types:
count = []
count = [i for i in column_list if i == item_type]
count_items.append(len(count))
return item_types, count_items
if answer == "yes":
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
column_list = column_to_list(data_list, -2)
types, counts = count_items(column_list)
print("\nTAREFA 11: Imprimindo resultados para count_items()")
print("Tipos:", types, "Counts:", counts)
assert len(types) == 3, "TAREFA 11: Há 3 tipos de gênero!"
assert sum(counts) == 1551505, "TAREFA 11: Resultado de retorno incorreto!"
# -----------------------------------------------------
input("\nA seguir, temos as tarefas adicionais. Aperte Enter para continuar...")
# ---------------------------------------------------------
# PERGUNTAS ADICIONAIS
# ---------------------------------------------------------
# TAREFA 13
# Faça um gráfico mensal mostrando o uso das biciletas.
print("\nTAREFA 13: gráfico mensal de uso das bicicletas:")
# Vamos gerar a lista de starttime e endtime e em seguida os meses:
start_datetimes = column_to_list(data_list,0)
end_datetimes = column_to_list(data_list,1)
start_month = [date[5:7] for date in start_datetimes]
# Vamos verificar se alguma rota ultrapassa um mês (ao pegar a bicicleta no final do último dia de um mês, por exemplo)
count_month_passes = 0
for i,j in zip(start_datetimes, end_datetimes):
if i[5:7] != j[5:7]: # "Rota ultrapassa um mês!"
count_month_passes += 1
print('Existem {} rota(s) que ultrapassam um mês (cerca de {}% do total)'.format(count_month_passes, round(count_month_passes/len(data_list)*100,6)))
# A evidência de algum caso acima distorce um pouco a contagem do uso por mês, mas no geral não deve comprometer um simples panorama dos meses de maior e menor uso
# Assim, vamos usar como referência a lista start_month
months, month_counts = count_items(start_month)
y_pos = list(range(len(months)))
plt.bar(y_pos, month_counts)
plt.ylabel('Quantidade')
plt.xlabel('Mês')
plt.xticks(y_pos, months)
plt.title('Quantidade de usos por mês')
plt.show(block=True)
input("Aperte Enter para continuar...")
# TAREFA 14
# Qual as estações mais populares para ínicio e fim de viagem? O número de start stations é igual ao número de end stations?
print("\nTAREFA 14: número de start/end stations e as estações mais populares (leva algum tempo):")
# No meu computador, esta tarefa levou cerca de 4 min
start_stations_types, start_stations_count = count_items(column_to_list(data_list,3))
end_stations_types, end_stations_count = count_items(column_to_list(data_list,4))
popular_start_station = {'Name': '', 'Count': 0}
popular_end_station = {'Name': '', 'Count': 0}
for elem, count in zip (start_stations_types, start_stations_count):
if count > popular_start_station['Count']:
popular_start_station['Name'] = elem
popular_start_station['Count'] = count
for elem, count in zip(end_stations_types, end_stations_count):
if count > popular_end_station['Count']:
popular_end_station['Name'] = elem
popular_end_station['Count'] = count
print('Start Stations: {}\nMost popular: {} ({} usos)\n'.format(len(start_stations_types), popular_start_station['Name'], popular_start_station['Count']))
print('End Stations: {}\nMost popular: {} ({} usos)'.format(len(end_stations_types), popular_end_station['Name'], popular_end_station['Count']))
print('------ Fim do Projeto 1 ------') |
632e73e544dcfa1f77dda3d11c631ca9ba15ab71 | manojnayakkuna/leetcode_easy | /problems/leetcode_476_numberComplement.py | 1,347 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
Example 1: Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2: Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
"""
# Time - 77%
def findComplement(num):
new_string = ''
for char in str(bin(num)).split('b')[1]:
new_string += '0' if char == '1' else '1'
return int(new_string, 2)
# Time - 75% (Without using defaukt functions)
def findComplement1(num):
new_string = ''
for char in decimalToBinary(num):
new_string += '0' if char == '1' else '1'
return binaryToDecimal(int(new_string))
def decimalToBinary(decimalVal):
binaryVal = ''
while decimalVal:
lastBit = decimalVal % 2
decimalVal = decimalVal // 2
binaryVal = str(lastBit) + binaryVal
return binaryVal
def binaryToDecimal(binaryVal):
decimalVal = 0
base = 1
while binaryVal:
lastBit = binaryVal % 10
binaryVal = binaryVal // 10
decimalVal += lastBit * base
base = base*2
return decimalVal |
775f325220328192092331ed46821b5e614f23af | Nitin-patil2209/US-state-game | /main.py | 727 | 3.671875 | 4 | from turtle import Turtle, Screen
import pandas
data = pandas.read_csv("50_states.csv")
list_of_states = data["state"].to_list()
screen = Screen()
i = 1
turtleg = Turtle()
screen.title("U.S State Game")
img = "blank_states_img.gif"
screen.addshape(img)
turtleg.shape(img)
while i <= 51:
screenprompt = screen.textinput(title=f"{i} Guess state", prompt="Enter state name")
if screenprompt in list_of_states:
state_name = Turtle()
state_name.hideturtle()
city = data[data.state == screenprompt]
x = int(city.x)
y = int(city.y)
state_name.penup()
state_name.goto(x,y)
state_name.write(screenprompt)
i += 1
screen.mainloop() |
a53c785051eb587ef90e8e39bf1123f08119ea4f | lancerdancer/leetcode_practice | /code/trie/211_add_and_search_word.py | 1,841 | 3.953125 | 4 | """
https://leetcode.com/problems/add-and-search-word-data-structure-design/
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can
represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
"""
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.is_word = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
current = self.root
for c in word:
current = current.children[c]
current.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure.
A word could contain the dot character '.' to represent any one letter.
"""
if word is None:
return False
current = self.root
return self.dfs(current, word, 0)
def dfs(self, node, word, index):
if node is None:
return False
if index >= len(word):
return node.is_word
char = word[index]
if char != '.':
return self.dfs(node.children.get(char), word, index + 1)
for child in node.children:
if self.dfs(node.children[child], word, index + 1):
return True
return False
|
3fe096e53a31c92da006403f6acef2c0f3ecbf4d | bpuderer/python-snippets27 | /stdlib/time_qs.py | 1,541 | 4 | 4 | import time
print "snoozing 300 ms...zzzzzzz"
time.sleep(0.3)
# precision is platform dependent but a float is always returned
print "seconds since epoch as a float:", time.time()
# returns string for a tuple/struct_time in format "%a %b %d %H:%M:%S %Y"
# if no arg is provided it uses localtime()
print "current local time string:", time.asctime()
print "when is epoch?", time.asctime(time.gmtime(0))
# seconds since epoch to local string
# if no arg provided it uses time()
print "current local time string:", time.ctime()
print "10 minutes ago from current local time string:", time.ctime(time.time()-600)
# seconds since epoch to struct_time in UTC
# if no arg is provided is uses time()
print "current UTC time as struct_time", time.gmtime()
# same as gmtime() except local
print "local time as struct_time", time.localtime()
# reverse of localtime() and arg is required
print "sec since epoch from a *local* struct_time", time.mktime(time.localtime())
# struct_time to string with format string
# defaults to localtime() if t arg not provided
print "local time with format string", time.strftime("%a, %B %d, %Y %I:%M:%S %p")
# no %f for microseconds as in datetime
print "UTC time with format string", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# string to struct_time
# defaults to format from ctime() if string arg not provided: "%a %b %d %H:%M:%S %Y"
print "local struct_time from string", time.strptime(time.ctime())
print "struct_time from string", time.strptime("31/10/2016 07:30:00 PM", "%d/%m/%Y %I:%M:%S %p")
|
b081dab1bd11ed6c1e0c434e6978ed23c72dec78 | BhushanTayade88/Core-Python | /Feb/day 11/table.py | 104 | 3.703125 | 4 | n=int(input("Enter any no :"))
print("Table of Numer ",n)
for i in range(1,11):
print(n,"x",i,"=",n*i) |
fe959408275196b2eb1e81b02cf9f00a146dc846 | vikram-vijay/Exercism_python | /simple-cipher/simple_cipher.py | 791 | 3.515625 | 4 | from random import choices
from string import ascii_lowercase as letters
from itertools import cycle
class Cipher:
def __init__(self, key="".join(choices(letters, k=100))):
self.key = key
assert self.key.islower(), ValueError("key should be all lower case.")
@staticmethod
def _new_text(string, i, j, diff=False):
if diff:
return string[(string.index(i) + string.index(j)) % len(string)]
else:
return string[(string.index(i) - string.index(j)) % len(string)]
def encode(self, text):
return "".join([self._new_text(letters, i, j, True) for i, j in zip(text, cycle(self.key))])
def decode(self, text):
return "".join([self._new_text(letters, i, j, False) for i, j in zip(text, cycle(self.key))])
|
a231d8bf67fedee787fec9f89ead07a4acc68bf5 | william1357chen/fcc-scientific-computing-with-python | /fcc-arithmetic-formatter/arithmetic_arranger.py | 2,783 | 3.84375 | 4 | def arithmetic_arranger(problems, ans = False):
arranged_problems = ""
# check if there are too many problems. The limit is 5
if len(problems) > 5:
return "Error: Too many problems."
for i in range(len(problems)):
problems[i] = problems[i].split()
problem = problems[i]
operator = problem[1]
if operator not in "+-":
return "Error: Operator must be '+' or '-'."
first_operand = problem[0]
second_operand = problem[2]
if len(first_operand) > 4 or len(second_operand) > 4:
return "Error: Numbers cannot be more than four digits."
num_dash = len(first_operand) + 2 if (len(first_operand) > len(second_operand)) else len(second_operand) + 2
problem.append(num_dash)
try:
problem[0] = int(first_operand)
problem[2] = int(second_operand)
answer = problem[0] + problem[2] if operator == '+' else problem[0] - problem[2]
problem.append(answer)
except ValueError:
return "Error: Numbers must only contain digits."
# For now, each problem is a list of [first_operand, operator, second_operand, num_dash, answer]
# deal with first operand first
for i in range(len(problems)):
first_operand = str(problems[i][0])
num_dash = problems[i][3]
num_spaces = num_dash - len(first_operand)
arranged_problems += (" " * num_spaces) + first_operand
if i != (len(problems) - 1):
arranged_problems += " " * 4
else:
arranged_problems += '\n'
# deal with second operand
for i in range(len(problems)):
second_operand = str(problems[i][2])
operator = problems[i][1]
num_dash = problems[i][3]
arranged_problems += operator
num_spaces = num_dash - 1 - len(second_operand)
arranged_problems += (" " * num_spaces) + second_operand
if i != (len(problems) - 1):
arranged_problems += " " * 4
else:
arranged_problems += '\n'
# deal with dashes
for i in range(len(problems)):
num_dash = problems[i][3]
arranged_problems += ("-" * num_dash)
if i != (len(problems) - 1):
arranged_problems += " " * 4
elif ans is True:
arranged_problems += '\n'
# deal with answers if ans is True
if ans is True:
for i in range(len(problems)):
answer = str(problems[i][4])
num_dash = problems[i][3]
num_spaces = num_dash - len(answer)
arranged_problems += (" " * num_spaces) + answer
if i != (len(problems) - 1):
arranged_problems += " " * 4
return arranged_problems
|
b92f01ceeb830fd3b62864eda4699f436f301f62 | GSimas/PyThings | /Coursera/Python for Everybody/2-Data Structures/assignment9_4.py | 864 | 4.34375 | 4 | ## Python for Everybody Coursera
## Assignment 9_4
## Gustavo Simas da Silva - 2017
## Python Data Structures, Dictionaries
#use mbox-short.txt as filename
name = input("Enter file:")
if len(name) < 1: name = "mbox-short.txt"
fh = open(name)
all_emails = list()
mail_count = dict()
#iterates through lines of the file and collects all emails
for line in fh:
if 'From ' in line:
all_emails.append(line.split()[1])
#iterates through each email and creates dictionary with ocurrences count
for email in all_emails:
mail_count[email] = mail_count.get(email,0) + 1
max_mail = None
max_count = None
#iterates through keys and values of dictionary and searches for greatest occurrence
for key,value in mail_count.items():
if max_count is None or value > max_count:
max_mail = key
max_count = value
#prints the result
print(max_mail,max_count)
|
f0db15166f9fb876a23a774eef96569d7c7ab431 | PedroHenriqueSimoes/Exercicios-Python | /Mundo 2/File 057.py | 315 | 3.890625 | 4 | sex = ((str(input('Qual seu genero? [M/F] '))).strip()).upper()[0]
while sex !='M' and sex != 'F':
sex = ((str(input('Não entendi o que digitou ! Tente outra vez [M/F] '))).strip()).upper()[0]
if sex == 'M':
print('Sexo masculino registrado !')
else:
print('Sexo feminino registrado !')
print('FIM !')
|
2976357b8eba00691dd4a806c4c67f54a643842b | erjan/coding_exercises | /lexicographically_smallest_equivalent_string.py | 6,657 | 4.03125 | 4 | '''
You are given two strings of the same length s1 and s2 and a string baseStr.
We say s1[i] and s2[i] are equivalent characters.
For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.
Equivalent characters follow the usual rules of any equivalence relation:
Reflexivity: 'a' == 'a'.
Symmetry: 'a' == 'b' implies 'b' == 'a'.
Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.
For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.
Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.
'''
class UnionFind:
def __init__(self, size):
self.root = [i for i in range(size)]
# Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex.
# The initial "rank" of each vertex is 1, because each of them is
# a standalone vertex with no connection to other vertices.
self.rank = [1] * size
# The find function here is the same as that in the disjoint set with path compression.
def find(self, x):
if x == self.root[x]:
return x
self.root[x] = self.find(self.root[x])
return self.root[x]
# The union function with union by rank
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
if self.rank[rootX] > self.rank[rootY]:
self.root[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.root[rootX] = rootY
else:
self.root[rootY] = rootX
self.rank[rootX] += 1
def connected(self, x, y):
return self.find(x) == self.find(y)
class Solution:
def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
uf = UnionFind(26)
for i in range(len(s1)):
uf.union(ord(s1[i])-ord('a'), ord(s2[i])-ord('a'))
res = ""
indexes = defaultdict(list)
for i in range(len(uf.root)):
if not indexes[uf.root[i]]:
indexes[uf.root[i]].append(i)
for base in baseStr:
root = uf.find(ord(base)-ord('a'))
t = indexes[root]
res += chr(t[0] + ord('a'))
return res
-------------------------------------------------------
class Solution:
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
g = defaultdict(list)
for a, b in zip(A, B):
g[a].append(b)
g[b].append(a)
def findEquivalent(u):
seen = set()
least = 'z'
def dfs(u):
nonlocal least
if u in seen:
return
seen.add(u)
least = min(least, u)
for v in g[u]:
dfs(v)
dfs(u)
return seen, least
smallest = {}
for c in A:
if c in smallest:
continue
equiv, least = findEquivalent(c)
for e in equiv:
smallest[e] = least
return ''.join(smallest[c] if c in smallest else c for c in S)
--------------------------------------------------------------------------------------------------------
class Solution:
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
"""
Union Find (Disjoint Set)
Complexities:
Time: O(N), N - number of unqiue characters
Space: O(N), N - number of unqiue characters, actually can be O(1) because number of eglish letters is 26 which is constant
"""
parent = {char: char for char in string.ascii_lowercase}
def _find(char: str) -> str:
while parent[char] != char:
char = parent[char]
return char
def _union(char1: str, char2: str) -> None:
char1_set = _find(char1)
char2_set = _find(char2)
if char1_set != char2_set:
if ord(char1_set) < ord(char2_set):
parent[char2_set] = char1_set
else:
parent[char1_set] = char2_set
for char1, char2 in zip(A, B):
_union(char1, char2)
return ''.join([_find(char) for char in S])
---------------------------------------------------------------------------------------------------
Here are similar problems (that are annotated) where you can try out this method:
Problem synonymous-sentences with a similar Solution
Problem the-earliest-moment-when-everyone-become-friends with a similar Solution
Hope this helps!
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
group_id = 0
char_id = {}
group = {}
for a,b in zip(A,B):
if a in char_id and b in char_id:
if char_id[a] == char_id[b]:
continue
elif char_id[a] < char_id[b]:
group[char_id[a]] |= group[char_id[b]]
obsolete_id = char_id[b]
for char in group[char_id[b]]:
char_id[char] = char_id[a]
del group[obsolete_id]
else:
group[char_id[b]] |= group[char_id[a]]
obsolete_id = char_id[a]
for char in group[char_id[a]]:
char_id[char] = char_id[b]
del group[obsolete_id]
elif a in char_id:
group[char_id[a]] |= set([b])
char_id[b] = char_id[a]
elif b in char_id:
group[char_id[b]] |= set([a])
char_id[a] = char_id[b]
else:
group[group_id] = set([a,b])
char_id[a] = group_id
char_id[b] = group_id
group_id += 1
smallest_equivalent_char = {g : min(group[g]) for g in group}
return ''.join(smallest_equivalent_char[char_id[char]] if (char in char_id) else char for char in S)
--------------------------------------------------------------------------------------------------------------------
class Solution:
def smallestEquivalentString(self, A: str, B: str, S: str) -> str:
def root(c):
return c if parent[c] == c else root(parent[c])
parent = {s: s for s in string.ascii_lowercase}
for a, b in zip(A, B):
p1, p2 = root(a), root(b)
if p1 <= p2:
parent[p2] = p1
else:
parent[p1] = p2
return ''.join(root(s) for s in S)
|
973e0eebc3d620ec08d3f25b97a8220b6fd0ff2b | maggiepitt/tic-tac-toe | /tictactoe.py | 2,728 | 3.796875 | 4 | #main
player1 = input ("Player 1, please enter a name: ")
player2 = input ("Player 2, please enter a name: ")
players = [player1, player2]
players.sort()
for i in players:
print (players[0]+", you are X!")
print (players[1]+", you are O!")
break
row1 = [" ", " ", " "]
row2 = [" ", " ", " "]
row3 = [" ", " ", " "]
board = [row1, row2, row3]
rows = 3
def turn_x():
row = int(input (players[0]+", pick a row: "))
column = int(input (players[0]+", please pick a column: ")) -1
if row == 1 and row1[column] != "X" and row1[column] != "O":
row1[column] = row1[column].replace(" ", "X")
elif row == 2 and row2[column] != "X" and row2[column] != "O":
row2[column] = row2[column].replace(" ", "X")
elif row == 3 and row3[column] != "X" and row3[column] != "O":
row3[column] = row3[column].replace(" ", "X")
else:
print ("Sorry, try again.")
turn_x()
return
def turn_o():
row = int(input (players[1]+", pick a row: "))
column = int(input (players[1]+", please pick a column: ")) - 1
if row == 1 and row1[column] != "X" and row1[column] != "O":
row1[column] = row1[column].replace(" ", "O")
elif row == 2 and row2[column] != "X" and row2[column] != "O":
row2[column] = row2[column].replace(" ", "O")
elif row == 3 and row3[column] != "X" and row3[column] != "O":
row3[column] = row3[column].replace(" ", "O")
else:
print ("Sorry, try again.")
turn_o()
return
def wingame():
w = 0
if row1[0] == row1[1] == row1[2]:
if row1[0] != " ":
w = w + 1
elif row2[0] == row2[1] == row2[2]:
if row2[0] != " ":
w = w + 1
elif row3[0] == row3[1] == row3[2]:
if row3[0] != " ":
w = w + 1
elif row1[0] == row2[0] == row3[0]:
if row1[0] != " ":
w = w + 1
elif row1[1] == row2[1] == row3[1]:
if row1[1] != " ":
w = w + 1
elif row1[2] == row2[2] == row3[2]:
if row1[2] != " ":
w = w + 1
elif row1[0] == row2[1] == row3[2]:
if row1[0] != " ":
w = w + 1
elif row1[2] == row2[1] == row3[0]:
if row1[2] != " ":
w = w + 1
return w
def show_board():
print (row1)
print (row2)
print (row3)
return
def game():
while wingame() == 0:
turn_x()
show_board()
if wingame() == 1:
print (players[0]+" won the game!")
break
else:
turn_o()
show_board()
if wingame() == 1:
print (players[1]+" won the game!")
break
return
game()
|
51033624394c62c952b6c453f0d94e4a26252199 | codewithgauri/HacktoberFest | /python/En19cs306027_Lovesh_Kumrawat_Self_created_function_similar_to_'.astype'_in_numpy.py | 838 | 3.5 | 4 | # In 'numpy' we can convert values of matrix into 'integer' by 'np.matrix('1.4 0.6;1.8 3.2;1.4 4.2',dtype=int)' or 'matrix_variable.astype('int32')' but i created a function for this.
import numpy as np
def matrix_integer_values_any_shape(inp): #* For any shape of matrix.
lst=[]
mtx=np.matrix([int(j) for i in np.array(inp) for j in i])
for i in range(0,inp.shape[0]*inp.shape[1],inp.shape[1]):
temp=[]
[temp.append(mtx[0,i+j]) for j in range(inp.shape[1])],lst.append(temp)
return np.matrix(lst)
print('Real Matrix with Floating Values:')
z_4_3=np.matrix('1.4 3.6 5.7 4.3;1.8 3.2 34.64 235.77;1.4 34.213 4.2 653.567')
print(z_4_3,z_4_3.shape,'\n')
print('With Self Created Function:')
z=matrix_integer_values_any_shape(z_4_3)
print(z,z.shape,'\n')
print('With Inbuilt Function:')
z=z.astype('int32')
print(z,z.shape,'\n')
|
e9bbac8440944a604eb55584129a3f815457e964 | AaronBangs/PyCheckers | /py_checkers/ai_api/bot.py | 3,252 | 3.796875 | 4 | #JMJ
#Agent.py
#An interface to work with the class competition.
#Programmed by Ben Campbell
"""
Board Conventions:
Ben and I discovered while trying to get our bots to play each other that we need a standard convention for numbering the board. We've decided on the following conventions:
1. The columns are numbered left to right from A to H.
2. The rows are numbered bottom to top from 1 to 8.
3. The black pieces are on the top of the board (rows 6-8), and the red pieces are on the bottom of the board (rows 1-3). The initial configuration is such that squares A1 and H8 have checkers, and squares A8 and H1 are empty.
For reference, the initial configuration should look like this (each 'b' is a black piece, and each 'r' is a red piece):
8 ███ b ███ b ███ b ███ b
7 b ███ b ███ b ███ b ███
6 ███ b ███ b ███ b ███ b
5 ███ ███ ███ ███
4 ███ ███ ███ ███
3 r ███ r ███ r ███ r ███
2 ███ r ███ r ███ r ███ r
1 r ███ r ███ r ███ r ███
A B C D E F G H
When passing a move, the move should be stored in a tuple. The first element is the coordinates of the piece being moved. The second element is a list that contains the coordinates of the ending square, or the coordinates of all the steps in a multiple jump. Each coordinate should be a string of the form "AxB" where A is the x-coordinate (column) and B is the y-coordinate (row). For example, a move from E3 to D4 would be sent as ("5x3", ["4x4"]). A triple jump going from E3 to G5 to E7 to C5 would be sent as ("5x3", ["7x5", "5x7", "3x5"]).
"""
class Bot:
def __init__(self, color):
self.color = color
def make_move(self):
"""
Returns a tuple. The first is the coordinates for the piece that's moving.
The second item is an array that contains the positions it
ends up in or the steps in a multiple jump. All coordinates are in a string
format "AxB" where A is the x coordinate and B is the Y coordinate.
for a piece at (2,3) jumping to (4,5) and then (2,7)
it should return ("2x3", ["4x5", "2x7"])
"""
raise NotImplementedError()
def receive_move(self, move):
"""
Receives a move from the other bot and applies it to
to its own gamestate. The move is in the same format that makemove sends in.
If it receives an invalid move, it returns False.
Else, it returns true.
"""
raise NotImplementedError()
def get_board_str(self):
"""
returns a string representing the board. You can do this however you want,
as long as it makes sense.
"""
raise NotImplementedError()
def undo_last_move(self):
"""
called when the other bot returns false for recieve_move. This is sent to the
bot who made the move, telling it to undo the last move it made. If the last move
had several jumps, all of them are undone, so the board is in the same state it
was in before the move was made.
"""
raise NotImplementedError()
|
7a96bb4b679a75f3462f8750b9f0ca9355c50962 | MartaVohnoutovaBukovec/IOS-655-Python-a-Bash | /IOS 655 Python a Bash/homework/Lysov/AL_HW_10/subst_decipher.py | 1,256 | 4.03125 | 4 | #!/usr/bin/env python3
#
# Subject: UAI / 655, Lecturer Ing. Marta Vohnoutová
# Homework No 10: create a program that breaks the substitution cipher
# using 'brute force' approach by seeking patterns in the English dictionary
#
# Author: Alexandre Lysov
# Date: April 2017
#
# on Linux: python3 subst_decipher.py < emsg.txt
# on Windows: python subst_decipher.py < emsg.txt
#
# Note: all files were creaed in Windows !
# If database cannot be opened, try to delete the en_dict.db file -
# the program will attempt to recreate it from en_words.txt file.
# Be aware of possible issues with line endings between Linux and Windows.
from enDict import enDict
def main():
en_dict = enDict()
if (en_dict.access("en_dict.db") != 0):
print("Cannot open dictionary.")
return 1
eMsg = ""
line = ""
while True:
try:
line = input(">")
if line:
eMsg += line.strip() + ' '
else:
break
except EOFError:
break
eMsg = eMsg.strip()
if (len(eMsg) > 0):
print("Encrypted message:")
print(eMsg)
dMsg = en_dict.decipher(eMsg)
print(dMsg)
return 0
main()
|
b4a7a4abc8098c4d3bd27e3532532d101ae0e8ca | eklavyapatel/Access-Control-System | /canAccess.py | 2,187 | 3.71875 | 4 | from Objects import *
# Test whether a user can perform a specified operation on an object. Optionally, an object may be NULL, in which case CanAccesschecks allows access if a user is part of a group for an operation on which no object group was defined.
# The program will check whether the user is allowed to perform the specified operation on the object. That means that there exists a valid access right for an operation where the user is in usergroupname and the object is in the corresponding objectgroupname.
# As with AddAccess, the program will accept two or three strings. If object is missing, it is considered null and the software allows access only if no object groups were defined for that {operation, usergroupname} set.
# Note that the parameters here are user names and object names, not user groups and object groups.
def canAccessNull(operation,user):
for i in allUsers:
if (i.name == user):
for j in i.groups:
for k in allPermissions:
if (j == k.usergroupname):
for l in k.access:
if (l == operation):
print ("::: Yes. "+user+" can "+operation)
return
#print("::: No. "+user+" can not "+operation)
print("::: No. "+user+" can not "+operation)
def canAccess(operation,user,object_to_check):
for i in allUsers:
if (i.name == user):
for j in i.groups:
for k in allPermissions:
if (j == k.usergroupname):
for l in k.access:
if (l == operation):
for m in allGroups:
for n in m.objects:
if (object_to_check == n):
print("::: Yes. "+user+" can "+operation +" "+object_to_check)
return
#print("::: No. "+user+" can not "+operation)
print ("::: No. "+user+" can not "+operation+" "+object_to_check) |
c2cb537f158dd780c9a2af8848369339e53f997f | ht-dep/Algorithms-by-Python | /Problem Solving with Algorithms and Data Structures using python/05 Sorting and Searching/Sort/01 bubble sort/bubble_sort.py | 484 | 3.984375 | 4 | # coding:utf-8
# bubble sort:循环比较两个相邻位置之间的大小关系
def bubbleSort(num_list):
L = len(num_list)
while L > 1:
for i in range(L-1):
if num_list[i]>num_list[i+1]:
temp = num_list[i]
num_list[i] = num_list[i+1]
num_list[i+1] = temp
L -= 1
return num_list
if __name__ == "__main__":
num_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print bubbleSort(num_list)
|
e1adb5f703564b298c888369d03340d9e2e4eff3 | sasdf/ADLxMLDS2017 | /hw2/special/utils.py | 275 | 3.5 | 4 | #!/usr/bin/env python3
# coding=utf8
# version: 1.0.0
def trim_phone(x):
r = []
l = -1
c = 0
for p in x:
if p != l:
l = p
c = 0
else:
c += 1
if c == 1:
r.append(p)
return r
|
cf167583c3c263737f388df9f1cd6a566f9df818 | drugotosto/Simulazione | /analisiOperazionale/bootlneckAnalysis.py | 2,183 | 3.609375 | 4 | __author__ = 'maury'
import numpy as np
def calcoloVisite(md,ind):
""" Visit vector is computed using
V = VQ
The Scipy library can solve only linear system
in the form A X = b
So we transform the system in:
VQ = V => VQ -V = 0
=> V (Q -I) = 0 => V Q' = 0
then we have:
V Q' = 0
if we transpose the VQ' product, since Q is square, we have:
(VQ').T = 0 <=> Q'.T V.T = 0
The resulting system is not yet determined so we substitute
an equation (let's say the first) with V_0 = 1"""
# transition matrix
q = np.array(md.q)
# identity matrix
i = np.identity(len(q))
# transform into an homegeneus system
q = q - i
# create the ordinate vector
b = np.zeros(len(q))
# normalizing term (derived from the equation V_0 = 1)
b[ind] = 1
# convert the system to the form AX = 0
qt = q.transpose()
# substitutes the first equation with V_0
qt[ind] = b
# solve the system in the form AX = 0
v = np.linalg.solve(qt, b)
# Aggiorno il valore delle visite alle varie stazioni nel modello
md.aggiornaVisite(v)
return v
def calcoloDomande(md):
visite=[]
servizi=[]
# Recupero delle visite di ogni stazione sotto forma di Array di numpy dal modello
for staz in md.stazioni:
visite.append(staz.visite)
v=np.array(visite)
# Recupero dei tempi di servizio delle varie stazioni sotto forma Array di numpy dal modello
for staz in md.stazioni:
servizi.append(staz.s)
s=np.array(servizi)
# Calcolo relative domande per le varie stazioni
d=np.zeros(4)
d=v*s
# Aggiorna le varie domande per le varie stazioni nel modello
md.aggiornaDomande(d)
return d
def controlloStazione(md):
x=[]
for staz in md.stazioni:
if staz.tipo!="infinite":
x.append(staz.domande)
else:
x.append(0)
# Ritorna una nuova lista in cui le domande delle stazioni infinite server sono messe a 0
return x
def calcoloU(dMax,md,indice_rif):
return (1/dMax*md.stazioni[indice_rif].s)*100 |
6e1e1be01326a849e17039f6c751a60f51b02558 | mtkent/SeniorProject | /binaryConvert.py | 344 | 3.921875 | 4 | def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')
# # decimal number
# dec = 4530 # = 13 bit number
convertToBinary(100)
# binary = 11001
# decimal = 0
# for digit in binary:
# decimal = decimal*2 + int(digit)
# print (decimal)
# bin = str(101001)
# toPrint = int(bin, base=2)
# print(" and ", toPrint)
|
31ce9b48c5ac9acdd6cb262ba7f93b5a4f390f84 | mglerner/MathematicalPhysics | /Bessel/basicbessel.py | 898 | 3.546875 | 4 | #!/usr/bin/env python
from __future__ import division
from numpy import array, linspace
import scipy
import scipy.special
from scipy.special import j0,j1,jn,y0,y1,yn
import matplotlib.pyplot as pl
x = linspace(0,20,10000)
fig = pl.figure()
N = raw_input("How many bessel functions of the first kind to plot? ")
N = int(N)
for n in range(N):
pl.plot(x,jn(n,x),label="$J_%s(x)$"%n)
pl.legend()
pl.grid('on')
pl.show()
N = raw_input("How many bessel functions of the second kind to plot? ")
pl.clf()
N = int(N)
for n in range(N):
pl.plot(x,yn(n,x),label="$Y_%s(x)$"%n)
pl.legend()
pl.grid('on')
pl.show()
N = raw_input("Oops! How many bessel functions of the second kind to plot? ")
x0 = raw_input("Where to start x")
N,x0 = int(n),float(x0)
x = linspace(x0,20,10000)
pl.clf()
N = int(N)
for n in range(N):
pl.plot(x,yn(n,x),label="$Y_%s(x)$"%n)
pl.legend()
pl.grid('on')
pl.show()
|
f728d9fa7c7a1c32173b014984f16bc34fa838db | wangshunzi/Python_Demo | /01-微信+体脂率计算/05-微信+体脂率计算.py | 2,900 | 3.953125 | 4 | # 案例要求: 给定一个人的体重,身高,年龄,性别,打印其体脂率
class Person:
def __init__(self, name, age, sex, height, weight):
try:
self.body_fat = 0
self.name = name
if isinstance(age, str):
self.age = int(age)
if isinstance(sex, str):
if sex in ("男", "女"):
self.sex = 1 if sex == "男" else 0
else:
self.sex = int(bool(sex))
if isinstance(height, str):
self.height = float(height)
if self.height > 100:
self.height /= 100
if isinstance(weight, str):
self.weight = float(weight)
except Exception:
raise Exception("数据格式不正确, 请按如下格式检查:('Sz', 18, '男', 1.70, 55)")
def get_body_fat(self):
BMI = self.weight / (self.height * self.height)
# 体脂率 = (1.2 * BMI + 0.23 * 年龄 - 5.4 - 10.8*性别(男:1 女:0)) / 100
self.body_fat = (1.2 * BMI + 0.23 * self.age - 5.4 - 10.8 * self.sex) / 100
# 判断是否正常
# 正常成年人的体脂率分别是男性15%~18%和女性25%~28%
normal_ranges = ((0.25, 0.28), (0.15, 0.18))
normal_range = normal_ranges[self.sex]
min_value, max_value = normal_range
body_fat_result = "正常"
if self.body_fat < min_value:
body_fat_result = "偏瘦"
elif self.body_fat > max_value:
body_fat_result = "偏胖"
return "{} 您好,您的体脂率为{},正常范围在{}-{};所以,您{}!".format(self.name, self.body_fat, min_value, max_value, body_fat_result)
if __name__ == '__main__':
# name = input("请输入您的姓名:")
# age = input("请输入您的年龄:")
# sex = input("请输入您的性别(男/女):")
# height = input("请输入您的身高(m):")
# weight = input("请输入您的体重(kg):")
# person = Person(name, age, sex, height, weight)
# print(person.get_body_fat())
import itchat
@itchat.msg_register(itchat.content.TEXT)
def recive_text(msg):
from_user = msg["FromUserName"]
content = msg["Text"]
# 使用正则表达式,按照规则解析
import re
result = re.match(r"(.*)[,,\s*](.*)[,,\s*](.*)[,,\s*](.*)[,,\s*](.*)", content)
if result:
groups = result.groups()
# print(groups)
person = Person(*groups)
itchat.send_msg(person.get_body_fat(), toUserName=from_user)
else:
itchat.send_msg("请严格按照格式: 姓名,年龄,性别,身高(m),体重(kg)", toUserName=from_user)
itchat.auto_login(hotReload=True, enableCmdQR=False)
itchat.run()
|
91f107b4b1cc73dd7a69855199b2e12e302b0f4a | fractal1729/trash-classifier | /Features/extra_stuff/extra_edge_sliders.py | 3,082 | 3.53125 | 4 | #import the necessary packages
import argparse
from Tkinter import *
import cv2
import imutils
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="Path to the image to be scanned")
args = vars(ap.parse_args())
# load the image and compute the ratio of the old height
# to the new height, clone it, and resize it
image = cv2.imread(args["image"])
ratio = image.shape[0] / 500
orig = image.copy
image = imutils.resize(image, height=500)
# convert the image to grayscale, blur it, and find edges
# in the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale rgb
gray = cv2.GaussianBlur(gray, (5, 5), 0) # blurs image
edged = cv2.Canny(gray, 75, 100) # finds edges of min dimensions 75,100
# show the original image and the edge detected image
print "STEP 1: Edge Detection"
# cv2.imshow("Image", image)
# cv2.imshow("Edged", edged)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
# find the contours in the edged image, keeping only the
# largest ones, and initialize the screen contour
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
# loop over the contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
# cv2.imshow(str(peri), image)
# if our approximated contour has four points, then we
# can assume that we have found our screen
if len(approx) == 4:
screenCnt = approx
break
# show the contour (outline) of the piece of paper
# print "STEP 2: Find contours of paper"
# cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
# cv2.imshow("Outline", image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#########################################################
lowert = 0.0
uppert = 0.0
gausrad = 1
def draw():
global lowert
global uppert
global gausrad
cv2.destroyAllWindows()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale rgb
gray = cv2.GaussianBlur(gray, (gausrad, gausrad), 0) # blurs image
edged = cv2.Canny(gray, lowert, uppert) # finds edges of min dimensions 75,100
cv2.imshow(str(uppert), edged)
cv2.imshow("gray", gray)
cv2.moveWindow("gray", 1000, 0)
def updatelow(val):
global lowert
lowert = float(val)
draw()
def updateupper(val):
global uppert
uppert =float(val)
draw()
def updateBlur(var):
global gausrad
if (int(var) % 2 == 1):
gausrad = max(1,int(var))
draw()
root = Tk()
var = DoubleVar()
var2 = DoubleVar()
var3 = DoubleVar()
scale = Scale( root, variable = var , command=updatelow,to_=200)
scale.pack(side=LEFT)
scale2 = Scale( root, variable = var2 , command=updateupper,to_=300)
scale2.pack(side=RIGHT)
scale3 = Scale( root, variable = var3 , command=updateBlur, orient=HORIZONTAL,from_=1,to_=99)
scale3.pack(side=BOTTOM)
root.mainloop()
|
98fadaa24406457cdc5669979002817cc57727f4 | dalalsunil1986/Interview-Prep | /Medium/breadthfirstsearch.py | 1,991 | 4.28125 | 4 | # Do not edit the class below except
# for the breadthFirstSearch method.
# Feel free to add new properties
# and methods to the class.
from collections import deque
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
# sol 1
def breadthFirstSearch(self, array):
"""
Sol 1: This method uses a deque whereas the other uses a list, but pop front is O(n) with list and O(1) with
a deque and here we just append node name when we pop out of queue (i.e., when we visit it). This way is in line
with the conventional implementation of BFS with adding node to "seen" list as soon as we visit it, one-by-one
instead of adding all the children of a node when we visit it.
Sol 2: We instead add all of the children of a node to the output array as soon as we visit it instead of adding
each child one by one when we visit them (i.e., when they are popped). This works because we add the root
initially, and then ALL of its children on first iteration, then all children of left child on next iteration,
then all children of mid/right child on next iteration, etc.
:param array:
:return:
"""
bfs_queue = deque()
bfs_queue.append(self)
while bfs_queue:
# node visited, add to array after popping
curr_node = bfs_queue.popleft()
array.append(curr_node.name)
# put all children nodes of current node in queue to visit
bfs_queue.extend(curr_node.children)
return array
# sol 2
def breadthFirstSearch(self, array):
bfs_queue = [self]
array.append(self.name)
while bfs_queue:
node = bfs_queue.pop(0)
array.extend([node.name for node in node.children])
bfs_queue.extend(node.children)
return array
|
67c709027732791799706d8d0aedd308532d262f | lygeneral/LeetCode | /Python/Array/middle/15_3sum.py | 1,667 | 3.6875 | 4 | '''
15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
通过次数373,027
提交次数1,237,156
'''
class Solution:
def threeSum(self, nums):
'''
@describe: 排序+双指针,排序后第一层遍历i,然后j和k双指针
@param nums: 数组
@return: 元组
'''
nums.sort()
res = []
i = 0
while i < len(nums):
# i跳过重复数字,例如[0,0]
while i > 0 and i < len(nums) and nums[i - 1] == nums[i]:
i += 1
j = i + 1
k = len(nums) - 1
while j < k:
if 0 == nums[i] + nums[j] + nums[k]:
res.append([nums[i], nums[j], nums[k]])
j += 1
k -= 1
# i之后出现多个重复的数字则跳过,例如[-2,0,0,2,2]
while j < len(nums) and nums[j] == nums[j - 1]:
j += 1
while k > 0 and nums[k] == nums[k + 1]:
k -= 1
elif 0 > nums[i] + nums[j] + nums[k]:
j += 1
else:
k -= 1
i += 1
return res
if __name__ == '__main__':
nums = [-2,0,0,0,-1,-1,1,1,2,2]
s = Solution()
print(s.threeSum(nums)) |
fad5097c471a11095cd9586e86eec728f5c29efc | williamslai/driving | /driving.py | 338 | 3.859375 | 4 | #driving
country = input('請輸入國家')
age = int(input('請輸入年齡'))
if country == '台灣':
if age >= 18:
print('你可以考駕照')
else:
print('不可以考駕照')
elif country == '美國':
if age >= 16:
print('你可以考駕照')
else:
print('不可以考駕照')
else:
print('只能輸入台灣&美國')
|
0eab71a12f7464d35fbfc77953de5ea81b465f7d | saisudheer123/sudheer3python | /palindrome.py | 146 | 3.546875 | 4 | sai=int(raw_input())
sum=0
n=sai
while sai!=0:
rem=sai%10
sum=sum*10+rem
sai=sai/10
if sum==n:
print("yes")
else:
print("no")
|
eb07cb091bdd28a65d602b73a25e4798ce7c6d97 | Linkitz/exercises-coronapython | /chapter_3_3_9.py | 887 | 4.09375 | 4 | # 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use len() to print a message indicating the number of people you are inviting to dinner.
# Exercise 3-5
strangeperson = ['Strange Nº 1', 'Strange Nº 2', 'Strange Nº 3']
print("Yoooo! " + strangeperson[0] + ", let's dinner!")
print("Yoooo! " + strangeperson[1] + ", let's dinner!")
print("Yoooo! " + strangeperson[2] + ", let's dinner!")
popedperson = strangeperson.pop(1)
print("Unfortunately " + popedperson + " could not join us.")
addguest = 'Strange Nº 4'
strangeperson.insert(1,addguest)
print(addguest + " is the new guest!")
print("Yoooo! " + strangeperson[0] + ", let's dinner!")
print("Yoooo! " + strangeperson[1] + ", let's dinner!")
print("Yoooo! " + strangeperson[2] + ", let's dinner!")
print("There are " + str(len(strangeperson)) + " persons invited to dinner.") |
ec0a0698929c2836cef786bf0cfb439023400529 | styphoiz/code-challenges | /task4.py | 282 | 3.859375 | 4 | def task4(num1,num2):
if(num1 == 3 or num2 ==3):
for i in str(int(num1 + num2)):
if i=="3":
return True
return False
else:
return False
#tests
print(task4(3,5))
print(task4(3,10))
print(task4(13,10))
print(task4(20,3))
|
d8bf4aa2d843da7379dfe38e0c88692260de1bf5 | Jennifer974/my-projects | /data_scientist_projects.py | 1,464 | 3.90625 | 4 | class DataScientist():
'''This class describes Data Science projects I realized.
'''
def __init__(self, github='Jennifer974', school='VIVADATA'):
'''This function initializes attributes of DataScientist class
'''
self.github = github #Name of my Github account
self.school = school #Name of my school
def data_scientist_projects(self):
'''This function prints desciption of Data Science projects I realized.
Parameters
--------------
Returns
--------------
Projects description
'''
#Projects Dictionary
projects_dict = {'University of Oxford': 'Voice identification',
'Kaggle':
{'Anomaly detection': 'Credit card fraud detection',
'NLP': 'Quora insincere questions classification',
'Churn': 'Telcom Customer Churn'}}
print('I\'m a Data Scientist at', self.school, '(Github :', self.github, ') \nI realize this following projects :')
for project, description in projects_dict.items():
print('-', project, ':', description)
def main():
'''This function is defined to print class output.
'''
#Instanciate DataScientist class
my_profile = DataScientist()
#Execute data_scientist_projects function
my_profile.data_scientist_projects()
if __name__ == "__main__":
main()
|
1427fa269da1beb8166b3c6df473f2f4da2d23bf | laxmanuppada/Python-Lab | /day2/Life-in-weeks.py | 384 | 3.984375 | 4 | age = input("what is your current age ? : ")
# print (age)
age_as_int = int(age)
years_remaining = 90 - age_as_int
days_remaining = years_remaining * 365
weeks_remaining = years_remaining * 52
months_remaining = years_remaining * 12
# print(days_remaining)
message = f"you have {days_remaining} days, {weeks_remaining} weeks, {months_remaining} months left"
print (message)
|
1e8db3c251d7294be8a97058fd2e5a2b366e057c | korayszn/Pre-Release-2021 | /PreleaseMaterial.py | 3,708 | 4.125 | 4 | TutorGroup = input("Type the tutor group to set up votes for Eg. 7A")
while len(TutorGroup) != 2 and len(TutorGroup) != 3:
TutorGroup = input("Error. Type the tutor group to set up votes for Eg. 7A: ")
NumStudents = int(input("Please input the number of students in this tutor group: "))
while NumStudents < 28 or NumStudents > 35:
NumStudents = int(input("Error. Please input the number of students in the tutor group: "))
NumCandidates = int(input("How many candidates are in this tutor group?"))
while NumCandidates < 1 or NumCandidates > 4:
NumCandidates = int(input("Error. How many candidates are in this tutor group? 1-4 max "))
NamesCandidates = [""] * NumCandidates
Votes = [0] * NumCandidates
Abstain = 0
for count in range(0, NumCandidates):
NamesCandidates[count] = input("Type the name of the candidate: ")
Tie = True
while Tie == True:
VoterIDUsed = [0] * NumStudents
for count in range(0, NumStudents):
VoterID = int(input("Please enter your unique student voter number: "))
while VoterID in VoterIDUsed:
print("Sorry, this voter number has already been used to vote. You may not vote again. ")
VoterID = int(input("Please enter your unique student voter number: "))
VoterIDUsed[count] = VoterID
print("Here are the names of the candidates so you can vote: ", NamesCandidates)
for i in range(0, NumCandidates):
print("Type ", i + 1, "to vote for: ", NamesCandidates[i])
print("To abstain from voting press 0")
VoteInput = int(input())
while VoteInput < 0 or VoteInput > NumCandidates:
VoteInput = int(input("Error, type the candidate number or type 0 to abstain."))
if VoteInput == 0:
Abstain = Abstain + 1
elif VoteInput == 1:
Votes[0] = Votes[0] + 1
elif VoteInput == 2:
Votes[1] = Votes[1] + 1
elif VoteInput == 3:
Votes[2] = Votes[2] + 1
else:
Votes[3] = Votes[3] + 1
print ("TutorGroup: ", TutorGroup)
for count in range(0, NumCandidates):
print("Candidate Name: ", NamesCandidates[count])
print("Number of Votes: ", Votes[count])
print("Number of Abstained: ", Abstain)
winners = ""
most = Votes[0]
countwinners = 0
for count in range(0, NumCandidates):
if Votes[count] > most:
most = Votes[count]
for count in range(0, NumCandidates):
if Votes[count] == most:
winner = NamesCandidates[count]
print("This candidate is a winner ", winner)
countwinners = countwinners + 1
Percentages = [0.0] # initialise array to 4 elements
NumStudentsVoted = NumStudents - Abstain
for count in range(0, NumCandidates):
Percentages[count] = (Votes[count] / NumStudentsVoted) * 100 # percentage based on what candidate got
print("The percentage of votes for: ", NamesCandidates[count], "is", Percentages[count])
print("The number of abstained votes is: ", Abstain)
print("The number of votes casted is: ", NumStudentsVoted)
if countwinners == 1:
print("Thanks you, the vote is complete. 1 winner has been decided", winner)
Tie = False
break
else:
Tie = True
print("There is a tie. We will repeat the votes with the tied candidates: ")
Abstain = 0
NamesNewCandidates = [""]
for count in range(0, NumCandidates):
if Votes[count] == most:
NamesNewCandidates.append(NamesCandidates[count])
NamesNewCandidates.pop(0)
print(NamesNewCandidates)
NamesCandidates = NamesNewCandidates |
b00a8e297133ef6a32834f0c714254c4f24cc8ee | GhulamMustafaGM/PythonChallenges | /Basketball RosterApp.py | 2,590 | 4.03125 | 4 | # Lists Challenge - Basketball Roster Program
print("Welcome to the Basketball Roster Program")
# Get user input and define our roster
roster = []
player = input("\nWho is your point guard: ").title()
roster.append(player)
player = input("Who is your shooting guard: ").title()
roster.append(player)
player = input("Who is your small forward: ").title()
roster.append(player)
player = input("Who is your power forward: ").title()
roster.append(player)
player = input("Who is your center: ").title()
roster.append(player)
# Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
# Remove an injured player
injured_player = roster.pop(2)
print("\nOh no, " + injured_player + " is injured.")
roster_length = len(roster)
print("Your roster only has " + str(roster_length) + " players.")
# Add a new player
added_player = input("Who will take " + injured_player + "'s spot: ").title()
roster.insert(2, added_player)
# Display roster
print("\n\tYour starting 5 for the upcoming basketball season")
print("\t\tPoint Guard:\t\t" + roster[0])
print("\t\tShooting Guard:\t\t" + roster[1])
print("\t\tSmall Forward:\t\t" + roster[2])
print("\t\tPower Forward:\t\t" + roster[3])
print("\t\tCenter:\t\t\t" + roster[4])
print("\nGood luck " + roster[2] + " you will do great!")
roster_length = len(roster)
print("Your roster now has " + str(roster_length) + " players.")
# output
# Welcome to the Basketball Roster Program
# Who is your point guard: David
# Who is your shooting guard: John
# Who is your small forward: Calle
# Who is your power forward: Mike
# Who is your center: James
# Your starting 5 for the upcoming basketball season
# Point Guard: David
# Shooting Guard: John
# Small Forward: Calle
# Power Forward: Mike
# Center: James
# Oh no, Calle is injured.
# Your roster only has 4 players.
# Who will take Calle's spot: Carl
# Your starting 5 for the upcoming basketball season
# Point Guard: David
# Shooting Guard: John
# Small Forward: Carl
# Power Forward: Mike
# Center: James
# Good luck Carl you will do great!
# Your roster now has 5 players. |
08a1c96fc366b8ba554ddc14d48ba206cfa8c531 | Gideon-Felt/Homework-Bottega | /11-11-19/Filter_Emails_and_departments.py | 1,893 | 4.1875 | 4 | """
You have been given a raw data dump that has an array of objects. The objects keys are companies, and the values are arrays of emails followed by a 3 digit department number.
I need you to write a program that will go through the data, return the emails for each company and what department number that email belongs to.
"""
data =[
{ "Google": ["test@test.com 123", "test@test.com 321", "test@test.com 451", "test@test.com 123" ]},
{ "Yahoo": ["test@test.com 123", "test@test.com 321", "test@test.com 451", "test@test.com 451" ]},
{ "IBM": ["test@test.com 888", "test@test.com 123", "test@test.com 888", "test@test.com 123" ]},
{ "GREGS": ["test@test.com 123", "test@test.com 888", "test@test.com 123", "test@test.com 123" ]},
{ "AUTO SHOP": ["test@test.com 888", "test@test.com 555", "test@test.com 555", "test@test.com 123" ]},
{ "PAWN SHOP": ["test@test.com 123", "test@test.com 123", "test@test.com 123", "test@test.com 123" ]},
{ "Nike": ["test@test.com 123", "test@test.com 123", "test@test.com 555", "test@test.com 123" ]},
{ "Franks": ["test@test.com 123", "test@test.com 888", "test@test.com 555", "test@test.com 123" ]},
{ "Tims": ["test@test.com 123", "test@test.com 123", "test@test.com 888", "test@test.com 123" ]},
{ "Apple": ["test@test.com 123", "test@test.com 555", "test@test.com 123", "test@test.com 123" ]},
{ "Sony": ["test@test.com 123", "test@test.com 123", "test@test.com 123", "test@test.com 123" ]},
{ "Disney": ["test@test.com 123", "test@test.com 888", "test@test.com 123", "test@test.com 123" ]},
{ "Popies": ["test@test.com 123", "test@test.com 123", "test@test.com 123", "test@test.com 123" ]},
{ "Sally": ["test@test.com 123", "test@test.com 555", "test@test.com 888", "test@test.com 123" ]},
{ "Henry": ["test@test.com 123", "test@test.com 555", "test@test.com 555", "test@test.com 555" ]},
{ "Dave's": ["test@test.com 123", "test@test.com 888", "test@test.com 555", "test@test.com 123" ]}
]
def eamil_and_department_filter(data):
for company in data:
for key, value in company.items():
print(f"Company: {key}")
for string in value:
email, department = string.split(' ')
print(f"{email}, Dept# {department}")
print('\n')
eamil_and_department_filter(data) |
49cc39121a6eb26d733af1158bf335aa5a4c376a | mandrakean/Estudo | /Python_Guan/ex069.py | 649 | 3.921875 | 4 | print('-=-'*20)
print('Cadastro de pessoas')
print('-=-'*20)
print('')
sup18 = 0
h = 0
m20 = 0
teste = 'S'
while teste is 'S':
idade = int(input('digite a idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('digite o sexo (M/F): ')).upper().strip()[0]
if idade < 20 and sexo is "F":
m20 += 1
if sexo is "M":
h += 1
if idade >= 18:
sup18 += 1
teste = ' '
while teste not in 'SN':
teste = str(input('quer fazer outro cadastro (S/N)? ')).upper().strip()[0]
print(f'Existem {sup18} pessoas maiores de 18 anos, {m20} mulheres abaixo de 20 anos e ao todo {h} homens.')
|
2da454af1558927b7e56640e0391784aef1760f5 | dhazu/Mygit | /python_workbook/ch1/ex9.py | 1,012 | 3.84375 | 4 | """Exercise 9: Compound Interest
Pretend that you have just opened a new savings account that earns 4 percent interest
per year. The interest that you earn is paid at the end of the year, and is added
to the balance of the savings account. Write a program that begins by reading the
amount of money deposited into the account from the user. Then your program should
compute and display the amount in the savings account after 1, 2, and 3 years. Display
each amount so that it is rounded to 2 decimal places."""
#Solution:
P = float(input("Enter the amount of money deposited (in rupees): "))
r = 0.04
n = 12
t = 1
# Compute the amonut after each year
A1 = P * (1+r/n) ** (n*t)
A2 = A1 * (1+r/n) ** (n*t)
A3 = A2 * (1+r/n) ** (n*t)
# Display the amount
print("The amount in the savings after the first year is {:.2f} rupees".format(A1))
print("The amount in the savings after the second year is {:.2f} rupees".format(A2))
print("The amount in the savings after the third year is {:.2f} rupees".format(A3))
|
6ff7e7e86a8b49b3ed11ff81ff7e41f03896cf20 | Mjusten/pythonElaborata | /Aula07_Ex02.py | 241 | 3.84375 | 4 | soma = lambda x,y,z : x+y+z
entrada1 = float(input("Entre o primeiro valor: "))
entrada2 = float(input("Entre o segundo valor: "))
entrada3 = float(input("Entre o terceiro valor: "))
saida = soma(entrada1,entrada2,entrada3)
print(saida) |
503188d81e07fe54d1ec2a93aa0b5e77765af641 | janethuyx/algorithm | /diameter_binary_tree.py | 510 | 3.6875 | 4 |
class Solution:
"""
@param root: a root of binary tree
@return: return a integer
"""
def diameterOfBinaryTree(self, root):
# write your code here
self.max = 0
self.dfs(root)
return self.max
def dfs(self, node):
if not node:
return 0
left_length = self.dfs(node.left)
right_length = self.dfs(node.right)
self.max = max(self.max, left_length + right_length)
return max(left_length, right_length) + 1
|
8627f0e47e8483c3d334c062809d5a7c86809758 | 4LuckyMove/Education_Space_Lab | /MVC_MVP_MVVM/MVP/model.py | 415 | 3.5 | 4 | class ModelCalculator:
def __init__(self):
self.result = 0
def calc(self, val1, operation, val2):
if operation == '+':
self.result = val1 + val2
elif operation == '-':
self.result = val1 - val2
elif operation == '*':
self.result = val1 * val2
elif operation == '/':
self.result = val1 / val2
return self.result |
c96774bb58457b697504d0a70c79007ff0a99f24 | ShaeBrown/seng474 | /proj.py | 2,722 | 3.53125 | 4 | import csv
import sys
#create array to put attributes into
data_array= []
#array for classes
class_array= []
#open pordate file
f=open("pordate.csv", "r")
reader=csv.reader(f)
#go through data file and create arrays of 0 and 1's for each student (breakdown on google docs)
for row in reader:
tmp= []
cmp=[]
#male or female
if(row[0]=='F'):
tmp.extend([0,1])
elif(row[0]=='M'):
tmp.extend([1,0])
else:
#this for first line with headers
continue
#age 15-22
if(row[1]=='15'):
tmp.extend([1,0,0,0,0,0,0,0])
elif(row[1]=='16'):
tmp.extend([0,1,0,0,0,0,0,0])
elif(row[1]=='17'):
tmp.extend([0,0,1,0,0,0,0,0])
elif(row[1]=='18'):
tmp.extend([0,0,0,1,0,0,0,0])
elif(row[1]=='19'):
tmp.extend([0,0,0,0,1,0,0,0])
elif(row[1]=='20'):
tmp.extend([0,0,0,0,0,1,0,0])
elif(row[1]=='21'):
tmp.extend([0,0,0,0,0,0,1,0])
else:
tmp.extend([0,0,0,0,0,0,0,1])
#study time 1-4
if(row[2]=='1'):
tmp.extend([1,0,0,0])
elif(row[2]=='2'):
tmp.extend([0,1,0,0])
elif(row[2]=='3'):
tmp.extend([0,0,1,0])
else:
tmp.extend([0,0,0,1])
#failure 0-4
if(row[3]=='0'):
tmp.extend([1,0,0,0,0])
elif(row[3]=='1'):
tmp.extend([0,1,0,0,0])
elif(row[3]=='2'):
tmp.extend([0,0,1,0,0])
elif(row[3]=='3'):
tmp.extend([0,0,0,1,0])
else:
tmp.extend([0,0,0, 0,1])
#activites yes or no
if(row[4]=='yes'):
tmp.extend([1,0])
else:
tmp.extend([0,1])
#Higher yes or no
if(row[5]=='yes'):
tmp.extend([1,0])
else:
tmp.extend([0,1])
#romantic yes or no
if(row[6]=='yes'):
tmp.extend([1,0])
else:
tmp.extend([0,1])
#Fam rel 1-5
if(row[7]=='1'):
tmp.extend([1,0,0,0,0])
elif(row[7]=='2'):
tmp.extend([0,1,0,0,0])
elif(row[7]=='3'):
tmp.extend([0,0,1,0,0])
elif(row[7]=='4'):
tmp.extend([0,0,0,1,0])
else:
tmp.extend([0,0,0, 0,1])
#Free time 1-5
if(row[8]=='1'):
tmp.extend([1,0,0,0,0])
elif(row[8]=='2'):
tmp.extend([0,1,0,0,0])
elif(row[8]=='3'):
tmp.extend([0,0,1,0,0])
elif(row[8]=='4'):
tmp.extend([0,0,0,1,0])
else:
tmp.extend([0,0,0, 0,1])
#Goout 1-5
if(row[9]=='1'):
tmp.extend([1,0,0,0,0])
elif(row[9]=='2'):
tmp.extend([0,1,0,0,0])
elif(row[9]=='3'):
tmp.extend([0,0,1,0,0])
elif(row[9]=='4'):
tmp.extend([0,0,0,1,0])
else:
tmp.extend([0,0,0, 0,1])
#absences 1-5
if(row[10]=='1'):
tmp.extend([1,0,0,0,0])
elif(row[10]=='2'):
tmp.extend([0,1,0,0,0])
elif(row[10]=='3'):
tmp.extend([0,0,1,0,0])
elif(row[10]=='4'):
tmp.extend([0,0,0,1,0])
else:
tmp.extend([0,0,0, 0,1])
#G3 1-3 into class array
if(row[11]=='1'):
cmp.extend([1,0,0])
elif(row[11]=='2'):
cmp.extend([0,1,0])
else:
cmp.extend([0,0,1])
#add student to big arrays
data_array.append(tmp)
class_array.append(cmp)
#close file
f.close() |
6fc8482d210dda5ddf5ed8f4fc83417623b9a12d | Cryptofrye/vegas | /vegas/player.py | 1,377 | 3.703125 | 4 | import vegas.invalid_bet
class Player(object):
"""A roulette Player (abstract class)."""
def __init__(self, table, verbose=False):
"""Constructor."""
self.table = table
self.stake = 100
self.roundsToGo = 1
self.verbose = verbose
def setStake(self, stake):
"""Set Player's stake to be the given amount."""
self.stake = stake
def setRounds(self, rounds):
"""Set Player's stake to be the given number."""
self.roundsToGo = rounds
def playing(self):
"""Assert whether the Player is still playing in the Game."""
halts = [
self.stake < self.table.minimum,
self.roundsToGo == 0
]
return (False if any(halts) else True)
def placeBets(self):
"""Place Bets on the Table (to be implemented in subclasses)."""
pass
def _place_bet(self, bet):
"""Process placing a Bet (checks and stake updates)."""
if (self.stake - bet.amountBet) < 0:
raise vegas.invalid_bet.InvalidBet
self.stake -= bet.amountBet
self.table.placeBet(bet)
def win(self, bet):
"""Process a Bet that was won."""
self.stake += bet.winAmount()
if self.verbose:
print("Won ${} on {}".format(bet.amountBet, bet.outcome.__str__()))
def lose(self, bet):
"""Process a Bet that was lost."""
if self.verbose:
print("Lost ${} on {}".format(bet.amountBet, bet.outcome.__str__()))
|
fdad571b11cb63f86958d6717aa33b07301e8593 | lizetheP/PensamientoC | /programas/Laboratorios/4_While/tareaCiclos.py | 765 | 4.15625 | 4 | def factorial(n):
i = 1
acum = 1
while i <= n:
acum = acum*i
i= i+1
return acum
def multiplicacion(n1, n2):
i = 1
acum = 0
while i <= n2:
acum = acum + n1
i = i + 1
return acum
def menu():
print()
print("1. Factorial")
print("2. Multiplicación")
while True:
menu()
opcion = int(input("Introduce una opcion: "))
if opcion == 1:
num = int(input("Introduce un número: "))
res = factorial(num)
print(res)
elif opcion == 2:
num1 = int(input("Introduce un número: "))
num2 = int(input("Introduce otro número: "))
res = multiplicacion(num1, num2)
print(res)
else:
print("Opción inválida")
break
|
62eff33d377ade411916b96b85821a3de52c5a60 | crosstuck/iot-analytics | /iot_analytics/models.py | 2,547 | 3.53125 | 4 | class BaseEvent(object):
def is_valid(self):
"""
An account ID and an event type are required.
"""
if self.property_id and self.type and self.type in EVENT_TYPES:
return True
return False
def clean_data(self, data):
"""
Removes any fields from the data that are not valid
fields on the event object.
"""
for item in data:
if item not in self.fields:
del data[item]
return data
class Event(BaseEvent):
"""
An event is something that happens.
An example of an event may be something such as a button being pressed.
"""
def __init__(self, property_id, data):
self.property_id = property_id
self.type = 'event'
self.fields = (
'device_id',
'category',
'action',
'label',
'value',
)
self.data = self.clean_data(data)
# Add the type to the data
self.data['type'] = self.type
class Error(BaseEvent):
def __init__(self, property_id, data):
self.property_id = property_id
self.type = 'error'
self.fields = (
'device_id',
'description',
'is_fatal',
)
self.data = self.clean_data(data)
# Add the type to the data
self.data['type'] = self.type
class Timing(BaseEvent):
def __init__(self, property_id, data):
self.property_id = property_id
self.type = 'timing'
self.fields = (
'device_id',
'category',
'name',
'time',
'label',
)
self.data = self.clean_data(data)
# Add the type to the data
self.data['type'] = self.type
class ApiHit(BaseEvent):
def __init__(self, property_id, data):
self.property_id = property_id
self.type = 'hit'
self.fields = (
'device_id',
'hostname',
'path',
'title',
)
self.data = self.clean_data(data)
# Add the type to the data
self.data['type'] = self.type
EVENT_TYPES = {
'event': Event,
'error': Error,
'timing': Timing,
'hit': ApiHit
}
def get_model_for_type(event_type):
from iot_analytics.exceptions import InvalidTypeException
# Make sure that the type is valid
if event_type not in EVENT_TYPES:
raise InvalidTypeException()
return EVENT_TYPES[event_type]
|
79629994e53654d6b8f014c0932662dcd289f5fb | sunminnies/python3 | /05list.py | 4,598 | 3.890625 | 4 | # 파이썬 리스트
attendList = ['순철','병헌','민우','찬호','민태']
print(attendList)
numbers = [1,2,3,4,5,6,7,8,9]
print(numbers)
complex = [1, 2.0, 3.1415, 40, '5', "6"]
print(complex)
for data in numbers: # iterable
print(data)
for data in complex:
print(data)
len(numbers)
msg = 'Hello, World!'
len(msg)
# 메세지 입력받고 문자열 길이 출력
msg = '내 이름은 홍길동입니다.'
print(f'입력한 문자열의 길이: {len(msg)}')
print(len(['Hello Python!!']))
print(len('Hello Python!!'))
# 리스트의 모든 항목 조회
print(complex[0])
print(complex[1])
print(complex[2])
print(complex[3])
print(complex[4])
print(complex[5])
for i in range(6):
print(complex[i])
for i in range(len(complex)):
print(complex[i])
for item in complex:
print(item)
for idx, item in enumerate(complex):
print(f'{idx}, {item}')
print(complex.index(3.1415))
sports = ['baseball', 'basketball', 'tennis', 'golf', 'soccer']
print(sports.index('soccer'))
print(sports[len(sports)-1])
language = ['c/c++', 'c#', 'python', 'java']
print(language.index('python'))
hobby = ['독서', '등산', '요리']
hobby.append('배구')
print(hobby)
number = [1, 2, 3, 4, 5, 7, 8, 9]
number.append(10)
number.insert(5, 6)
print(number)
weather = ['The', 'weather', 'very']
weather.insert(2, 'is')
weather.insert(4, 'cold')
# 성적처리 프로그램
# 3명의 학생데이터 입력 후 총첨, 평균, 학점 처리하여 결과 출력
names = []
kors = []
engs = []
mats = []
for i in range(3):
name = input('이름은? ')
names.append(name)
kor = int(input('국어점수는? '))
kors.append(kor)
eng = int(input('영어점수는? '))
engs.append(eng)
mat = int(input('수학점수는? '))
mats.append(mat)
tots = []
avgs = []
grds = []
for i in range(3):
tots.append(kors[i] + engs[i] + mats[i])
avgs.append(tots[i] / 3)
grds.append('가')
# if avgs[i] >= 90: grds[i] = '수'
# if avgs[i] >= 80: grds[i] = '우'
# if avgs[i] >= 70: grds[i] = '미'
# if avgs[i] >= 60: grds[i] = '양'
if avgs[i] >= 90:
grds[i] = '수'
if 80 <= avgs[i] < 90:
grds[i] = '우'
if 70 <= avgs[i] < 80:
grds[i] = '미'
if 60 <= avgs[i] < 70:
grds[i] = '양'
for i in range(3):
print(f'{names[i]}, {kors[i]}, {engs[i]}, {mats[i]} \n'
f'{tots[i]}, {avgs[i]}, {grds[i]} \n')
# 리스트 수정: 리스트[인덱스] = 수정할값
hobby
hobby[1] = '여행'
hobby
# 리스트 삭제
# pop: 맨 뒤의 항목을 제거
# pop(위치): 해당 위치의 항목을 제거
# remove: 요소값으로 항목 제거
hobby
hobby.pop()
sports
sports.pop(2)
language
language.remove('java')
# 과일 리스트에서 야채 삭제하기
fruits = ['사과', '망고', '당근', '수박', '포도', '참외', '토마토']
fruits
# 위치값으로 삭제
fruits.pop(2)
fruits.pop(5)
# 값으로 삭제
fruits.remove('당근')
fruits.remove('토마토')
# 합격 여부 판정하기
exam = [55, 35, 40, 70, 65, 30]
cnt = len(exam)
sum = 0
fails = 0
result = '아쉽습니다. 불합격하셨습니다.'
for i in range(cnt):
if exam[i] < 40: fails += 1 # 과락수 증가
sum += exam[i]
avg = sum / cnt
if fails == 0 and avg >= 60:
result = '축하합니다. 합격하셨습니다.'
print(f'평균점수: {avg:.2f}')
print(result)
# 정렬하기
numbers = [5,1,3,4,2,6]
numbers.sort()
numbers
numbers.sort(reverse=True)
numbers
# 모의고사 점수 정렬하기
exam = [90, 100, 88, 85, 95, 92, 70, 75, 100, 92, 78, 80, 75, 95, 90, 100, 84]
exam.sort(reverse=True)
exam
# 문자정렬(한글)
names = ['김길동', '박길동', '이길동', '정길동', '홍길동']
names.sort()
names
# 문자정렬(영어)
units = ['scv', 'marine', 'firebat', 'ghost', 'dropship', 'battlecruiser', 'valkyrie']
units.sort()
units
# 리스트 슬라이싱
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
alphabet.reverse()
alphabet
alphabet[2:6] # 2 ~ 5까지 추출
alphabet[0:5] # 0 ~ 4까지 추출
alphabet[:5] # 0 ~ 4까지 추출
alphabet[3:8] # 3 ~ 7까지 추출
alphabet[5:10] # 5 ~ 끝까지 추출
alphabet[5:] # 5 ~ 끝까지 추출
alphabet[3:9] # 3 ~ 8까지 추출
alphabet[-4:] # 오른쪽을 기준으로 n번째 요소부터 추출
alphabet[6:] # 같은 결과값 (6 ~ 끝까지 추출)
# a, b, c, d 추출
alphabet[0:4]
alphabet[:4]
alphabet[-10:4]
alphabet[:-6]
# d, c, b, a 추출
alphabet[::-1] # 역순 추출
alphabet[-7::-1]
alphabet[3::-1]
alphabet[-7:-11:-1]
# g, h, e, d 추출
|
8cb87158bddbbfb99bf494811bfd911874eab124 | JyHu/PYStudy | /source/sublime/QuesIn2CTO/ques18.py | 617 | 3.953125 | 4 | #coding:utf-8
'''
题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
'''
import math
def simSum(num, nums):
assert ((nums < 0) or not isinstance(nums, (int, long)) or (num < 0) or not isinstance(num, (int ,long))), "错误的数据类型"
# if (nums < 0) or not isinstance(nums, (int, long)) or (num < 0) or not isinstance(num, (int ,long)):
# return 0
count = 0
for i in range(0, nums):
for j in range(0, i + 1):
count += int(math.pow(10, j)) * num
return count
print simSum(3.3, 3)
|
4a673877070d7a9d9cd6e370062449c8d18fadeb | daianasousa/Gerador-de-Comprimentos | /personalizacao_de_comprimentos.py | 1,453 | 4.125 | 4 | from random import *
executa = True
adjetivos = [ "maravilhoso", "acima da média", "excelente" ]
hobbies = ["andar de bicicleta", "programar", "fazer chá" ]
print("Gerador de Cumprimentos")
print("--------------------")
nome = input("Qual é o seu nome?: ")
print('''
Menu
c = obter cumprimento
a = adicionar hobby
d = remover hobby
p = imprimir hobbies
q = sair
''')
while executa == True:
menuChoice = input("\n>_").lower()
#'c' para um cumprimento
if menuChoice == 'c':
print("Aqui está o seu cumprimento" , nome , ":" )
#obtém um item ateatório de ambas as listas e adiciona-os ao cumprimento
print( nome , "você é" , choice(adjetivos) , "em" , choice(hobbies) )
print( "De nada!" )
#'a' para adicionar hobby
elif menuChoice == 'a':
itemToAdd = input("Adicione o hobby: ")
hobbies.append(itemToAdd)
#'d' para remover um hobby
elif menuChoice == 'd':
itemToDelete = input("insira o hobby a ser removido: ")
#só remove um item se ele estiver na lista
if itemToDelete in hobbies:
hobbies.remove(itemToDelete)
else:
print("O hobby não está na lista!")
#'p' para imprimir a lista de hobbies
elif menuChoice == 'p':
print(hobbies)
#'q' para sair
elif menuChoice == 'q':
executa = False
else:
print("Insira uma opção válida!")
|
4a9a02bfc0a4543efca9c67ad95b1b40be3191fd | goagain/Contests | /codeforces/1058/D/d.py | 794 | 3.609375 | 4 | import math
line = input().split()
n = int(line[0])
m = int(line[1])
k = int(line[2])
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, (a % b))
target = n * m * 2 // k
if n * m * 2 % k or k < 2:
print("NO")
else:
target = int(target)
exgcd = gcd(target, n)
if exgcd <= n and target // exgcd <= m:
width = exgcd
height = target // width
print('YES')
print(0, 0)
print(width, 0)
print(0, height)
else:
exgcd = gcd(target, m)
if exgcd <= m and target // exgcd <= n:
height = exgcd
width = target // height
print('YES')
print(0, 0)
print(width, 0)
print(0, height)
else:
print("NO") |
ad41e7ad6ec43b090ce51192781d785353be497a | fredkeemhaus/zero_base_algorithm | /algo/4-3.py | 883 | 3.515625 | 4 | def solution(a):
match = ''
stack = list()
# print(a)
for index in range(len(a)):
left, right = '', ''
# stack이 비어있을 경우 일단 문자열 하나를 추가한다
if len(stack) == 0:
stack.append(a[index])
else:
# left > 스택에 들어있던 문자열
# right > 스택에 넣으려고 했던 문자열
left = stack.pop()
right = a[index]
for i in range(len(left)):
if left[i] in right:
match += left[i]
for i in range(len(match)):
if match[i] not in stack:
stack.append(match[i])
stack = "".join(stack)
return len(stack)
print(solution(['abcd', 'abce', 'abchg', 'abcfwqw', 'abcdfg']))
print(solution(['abcd', 'gbce', 'abchg', 'abcfwqw', 'abcdfg'])) # 0
|
e16e3716d08cc0c0826127c6a67882e261689d33 | ysmintor/MLAlgorithm | /work23/LeetCode66.py | 1,369 | 4 | 4 | from typing import List
# 66. Plus One
# Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
#
# The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
#
# You may assume the integer does not contain any leading zero, except the number 0 itself.
#
# Example 1:
# Input: [1,2,3]
# Output: [1,2,4]
# Explanation: The array represents the integer 123.
# Example 2:
# Input: [4,3,2,1]
# Output: [4,3,2,2]
# Explanation: The array represents the integer 4321.
# Runtime: 28 ms, faster than 99.76% of Python3 online submissions for Plus One.
# Memory Usage: 13.1 MB, less than 70.80% of Python3 online submissions for Plus One.
# also learn something from typing package https://docs.python.org/3/library/typing.html
class Solution:
def plusOne(self, digits: List[int])->List[int]:
index = len(digits) - 1
carry = 0
while index >= 0:
carry = 1 if digits[index] == 9 else 0
if carry == 1:
digits[index] = 0
index -= 1
else:
digits[index] += 1
break
if carry == 1:
digits.insert(0, 1)
return digits
if __name__ == '__main__':
solution = Solution()
print(solution.plusOne([9])) |
dd86a5e2219834d137099b9d103506de318489dd | Hishikoz/vscode2019 | /python/006 function.py | 1,009 | 4.21875 | 4 | # 在参数名前面的*表示args是一个可变参数
# 即在调用add函数时可以传入0个或多个参数
def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1,2,3))
def is_palindrome(num):
temp = num
total = 0
while temp > 0:
total = total *10 + temp % 10
temp //=10
return total == num
if __name__ == '__main__':
num = int(input('请输入正整数:'))
if is_palindrome(num):
print('%d是回文数' % num)
"""
如果我们导入的模块除了定义函数之外还中有可以执行代码,
那么Python解释器在导入这个模块时就会执行这些代码,
事实上我们可能并不希望如此,因此如果我们在模块中编写了执行代码,
最好是将这些执行代码放入如下所示的条件中,这样的话除非直接运行该模块,
if条件下的这些代码是不会执行的,因为只有直接执行的模块的名字才是“__main__”。
""" |
b9a3ce444339451026d9d55cb755cae739d56e70 | xiaochenai/leetCode | /Python/Text Justification.py | 953 | 3.5 | 4 | class Solution:
# @param words, a list of strings
# @param L, an integer
# @return a list of strings
def fullJustify(self, words, L):
res = []
i = 0
while i<len(words):
size=0
begin=i
while i < len(words):
newsize = len(words[i]) if size==0 else size+len(words[i])+1#count in at least one space between words
if newsize<=L:size = newsize
else:break
i = i + 1
spaceCount = L-size
if i-begin-1>0 and i<len(words): #i-begin-1 is 0 or bigger than 0: means how many words in this line. not last line and more than one word
everyCount = spaceCount/(i-begin-1)
spaceCount = spaceCount%(i-begin-1)
else:
everyCount=0
j=begin
while j<i:
if j==begin:s=words[j]
else:
s = s + " "*(everyCount+1)
if spaceCount>0 and i<len(words):
s = s + " "
spaceCount = spaceCount - 1
s = s + words[j]
j = j + 1
s = s + " "*spaceCount
res.append(s)
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.