blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4bab89a132d0756d10e3d9a48fb14b37e1bf7c47 | LeBron-Jian/BasicAlgorithmPractice | /GreedyAlogrithm/change_money.py | 845 | 3.640625 | 4 | #_*_coding:utf-8_*_
#题目:假设商店老板需要找零 n 元钱,钱币的面额有100元,50元,20元,5元,1元,如何找零使得所需钱币的数量最少?(注意:没有10元的面额)
# 需求:如果需要找 376元零钱,如何使得所需钱币最少?
# 思路:我们需要从大额钱币开始,然后往小额钱币遍历,这样才能保证数量最少。
# t表示商店有的零钱的面额
t = [100, 50, 20, 5, 1]
# n 表示n元钱
def change(t, n):
m = [0 for _ in range(len(t))]
for i, money in enumerate(t):
m[i] = n // money # 除法向下取整
n = n % money # 除法取余
return m, n
print(change(t, 376)) # ([3, 1, 1, 1, 1], 0)
# 我对自己写的代码的时间复杂度和空间复杂度的理解是:空间复杂度为O(n),时间复杂度为O(n)
|
afb3a8a22817d216cd226b7a58409b4981ebca99 | quake0day/oj | /Leetcode/Reverse Words in a String II.py | 930 | 3.578125 | 4 | # class Solution(object):
# def reverseWords(self, s):
# """
# :type s: a list of 1 length strings (List[str])
# :rtype: nothing
# """
# stack = []
# final_string = ""
# for item in s:
# if item != " ":
# stack.append(item)
# else:
# while len(stack) != 0:
# final_string += stack.pop()
# final_string += " "
# while(len(stack)) != 0:
# final_string += stack.pop()
# final_string += " "
# return final_string[::-1]
class Solution(object):
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
for i in xrange(len(s) / 2):
s[i], s[len(s)-i-1] = s[len(s)-i-1], s[i]
return s
a = Solution().reverseWords(['t','h','e'])
print a |
5c12d16d540780b96ade75284731ff698c307cdd | FelipeGrueso/proyecto-maquina-de-cafe | /maquina de café v3.py | 2,696 | 4.09375 | 4 | agua = 400
leche = 540
café = 120
cups = 9
money = 550
while True:
action = input("Write action (buy, fill, take): ")
if action == "exit":
break
if action == "buy":
tipo = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ")
if action == "back":
continue
elif tipo == "1":
if agua <250:
print("Sorry, not enough water!")
elif café <16:
print("Sorry, not enough coffee!")
elif cups <1:
print("Sorry, not enough water!")
else:
agua -= 250
café -= 16
money += 4
cups -= 1
print("I have enough resources, making you a coffee!")
elif tipo == "2":
if agua <350:
print("Sorry, not enough water!")
elif café <20:
print("Sorry, not enough coffee!")
elif leche <75:
print("Sorry, not enough milk!")
elif cups <1:
print("Sorry, not enough water!")
else:
agua -= 350
leche -= 75
café -= 20
money += 7
cups -= 1
print("I have enough resources, making you a coffee!")
elif tipo == "3":
if agua <200:
print("Sorry, not enough water!")
elif café <12:
print("Sorry, not enough coffee!")
elif leche <100:
print("Sorry, not enough milk!")
elif cups <1:
print("Sorry, not enough water!")
else:
agua -= 200
leche -= 100
café -= 12
money += 6
cups -= 1
print("I have enough resources, making you a coffee!")
if action == "fill":
agua += int(input("Write how many ml of water you want to add: "))
leche += int(input("Write how many ml of milk you want to add: "))
café += int(input("Write how many grams of coffee beans you want to add: "))
cups += int(input("Write how many disposable coffee cups you want to add: "))
if action == "take":
print(f"I gave you ${money}")
money = 0
if action == "remaining":
print(f"""
The coffee machine has:
{agua} of water
{leche} of milk
{café} of coffee beans
{cups} of disposable cups
${money} of money
""")
|
774f1e1565a2e076ab4fa4021edda763acfc077a | qq450674576/shiyanlou-code | /jump7.py | 112 | 3.734375 | 4 | a=0
while a<100:
a=a+1
if a%7==0:
pass
elif a//10==7:
pass
elif a%10==7:
continue
else:
print(a)
|
8085318e2af09eee96dfb9ff6cfe42a58c03ae0c | YusefQuinlan/PythonTutorial | /Intermediate/2.2 Tkinter/2.2.12_Tkinter_Lambda_Command.py | 3,209 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 18:10:54 2020
@author: Yusef Quinlan
"""
"""
The following demonstrates that using the button without passing an argument
to the function xreturn() an error is produced.
"""
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The following button returns x times 8")
Label1.pack()
x = 3
def xreturn(j):
Label(Window, text=str(x * j)).pack()
Button1 = Button(Window, text="this button returns x times 8", command=xreturn).pack()
Window.mainloop()
"""
if we pass 8 to the xreturn command normally then the xreturn function packs a
label of the value x * 8 before the button renders and the button does not function
as intended, no idea why this happens in tkinter, but for whatever reason one
cannot simply pass a function with an argument to the command parameter of a
tkinter widget.
"""
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The following button returns x times 8")
Label1.pack()
x = 3
def xreturn(j):
Label(Window, text=str(x * j)).pack()
Button1 = Button(Window, text="this button returns x times 8", command=xreturn(8)).pack()
Window.mainloop()
"""
However by passing the command as a lambda and passing a value into a variable and
using the function with that variable as an argument, we can use the function
with a parameter without any weird errors or unintended functionality.
"""
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The following button returns x times 8")
Label1.pack()
x = 3
def xreturn(j):
Label(Window, text=str(x * j)).pack()
Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack()
Window.mainloop()
"""
The following demonstrates that we can pass several argument values to
xreturn(j) to several buttons, and they all work as intended thanks to lambda.
"""
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The following button returns x times 8")
Label1.pack()
x = 3
def xreturn(j):
Label(Window, text=str(x * j)).pack()
Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack()
Button2 = Button(Window, text="this button returns x times 5", command= lambda j=5: xreturn(j)).pack()
Button3 = Button(Window, text="this button returns x times 2", command= lambda j=2: xreturn(j)).pack()
Window.mainloop()
# Showing that lambda can be used for more than one function such as xset.
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The following button returns x times 8")
Label1.pack()
x = 3
def xreturn(j):
Label(Window, text=str(x * j)).pack()
def xset(i):
global x
x = i
Button1 = Button(Window, text="this button returns x times 8", command= lambda j=8: xreturn(j)).pack()
Button2 = Button(Window, text="this button returns x times 5", command= lambda j=5: xreturn(j)).pack()
Button3 = Button(Window, text="this button returns x times 2", command= lambda j=2: xreturn(j)).pack()
Button4 = Button(Window, text="this button sets x to 2", command= lambda setval=2: xset(setval)).pack()
Window.mainloop() |
f8f4625e86d93464570bb210325ce36ae54e2e95 | DagOnStar/dagonstar | /dagon/communication/__init__.py | 510 | 3.53125 | 4 | import socket
def is_port_open(host, port, timeout=5):
"""
verifies if a port is open in a remote host
:param host: IP of the remote host
:type host: str
:param port: port to check
:type port: int
:param timeout: timeout max to check
:type timeout: int
:return: True if the port is open
:rtype: bool
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
return result is 0
|
a7dc3d4c17c9f69c6e2744b5db26de6ca28b0e19 | prateek1404/AlgoPractice | /CareerCup/Amazon/range.py | 884 | 3.609375 | 4 | def ranger(ar,key,start,end):
start1=0
start2=0
end1=len(ar)-1
end2 = len(ar)-1
foundLeft = False
foundRight = False
while foundLeft==False and start1<=end1:
mid1= (start1+end1)/2
print "current mid1", mid1
if ar[mid1]==key:
if mid1==0:
foundLeft==True
else:
if ar[mid1-1]!=key:
foundLeft=True
else:
end1= mid1-1
else:
if ar[mid1]>key:
end1 = mid1-1
else:
print "updating start1"
start1 = mid1+1
print "found left", mid1
while foundRight==False:
mid2 = (start2+end2)/2
if ar[mid2]==key:
if mid2==len(ar)-1:
foundRight=True
else:
if ar[mid2+1]!=key:
foundRight=True
else:
start2=mid2+1
else:
if ar[mid2]>key:
end2= mid2-1
else:
start2 = mid2+1
print mid1,mid2
ar=map(int,[1,23,4123,11,32,3,23,432,23,423,423,4])
ar = sorted(ar)
print ar
ranger(ar,23,0,len(ar)-1)
|
5d4e8ca1767a205384d24d4377da89c4cb343848 | Berseneva/Python_tasks | /Lesson15_3_2.py | 1,044 | 3.859375 | 4 | def one():
count = 0
for i in num:
if i.isdigit() == True:
i = int(i)
count += i
else:
pass
print(count)
print()
def two():
count = 0
for i in num:
if i.isdigit() == True:
i = int(i)
if count < i:
count = i
else:
pass
print(count)
print()
def three():
count = int(num)
for i in num:
if i.isdigit() == True:
i = int(i)
if count > int(i):
count = i
else:
pass
print(count)
print()
try:
while True:
num = input('Введите число: ')
act = int(input('Что делаем с числом: 1 - суммируем его цифры, 2 - находим максимальную цифру, 3 - находим минимальную цифру? '))
if act == 1:
one()
elif act == 2:
two()
elif act == 3:
three()
else:
print('Для выбора действия введите число от 1 до 3')
print()
except ValueError:
print('Ошибка ввода')
|
b7d7a763413e4bfa1d08dbe9032e1244038d7fb0 | kiiikii/ptyhon-learn | /lab-loop-control-2.py | 1,484 | 4.5625 | 5 | # The continue statement - the Ugly Vowel Eater
# ------------------------
# Scenario
# ----------------
# The continue statement is used to skip the current block and move ahead to the next iteration, without executing the statements inside the loop.
# It can be used with both the while and for loops.
# task is very special: you must design a vowel eater! Write a program that uses :
# a for loop;
# the concept of conditional execution (if-elif-else)
# the continue statement.
# Your program must :
# ask the user to enter a word;
# use userWord = userWord.upper() to convert the word entered by the user to upper case;
# we'll talk about the so-called string methods and the upper() method very soon - don't worry;
# use conditional execution and the continue statement to "eat" the following vowels A, E, I, O, U from the inputted word;
# print the uneaten letters to the screen, each one of them on a separate line.
# Prompt the user to enter a word
# and assign it to the userWord variable.
userword = input("enter the letter : ")
userword = userword.upper()
for letter in userword:
# Complete the body of the for loop.
if letter == 'A' :
continue
elif letter == 'I' :
continue
elif letter == 'U' :
continue
elif letter == 'E' :
continue
elif letter == 'O' :
continue
else :
print(letter) |
e8b48691b1b235e64260191d57da517f3cf85fe3 | ht-dep/Algorithms-by-Python | /Python Offer/04.The Forth Chapter/36.BinarySearchTree_to_DoubleLinkList.py | 1,743 | 3.65625 | 4 | # coding:utf-8
'''
二叉搜索树->双向链表
输入一颗二叉搜索树, 将该二叉搜索树转换成一个排序的双向链表
不能创建任何新的节点,只能调整树中节点的指针
'''
class BinaryTreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
order = []
# 中序遍历
def inOrder(self, pRoot):
if pRoot is None:
return None
self.inOrder(pRoot.left)
self.order.append(pRoot.val)
self.inOrder(pRoot.right)
return self.order
# 转换成双向链表
def Convert(self, pRoot):
if pRoot is None:
return None
# 转换左子树
self.Convert(pRoot.left)
left = pRoot.left
if left:
while left.right:
left = left.right
pRoot.left, left.right = left, pRoot
# 转换右子树
self.Convert(pRoot.right)
right = pRoot.right
if right:
while right.left:
right = right.left
pRoot.right, right.left = right, pRoot
# 转换根节点
while pRoot.left:
pRoot = pRoot.left
return pRoot
if __name__ == '__main__':
pRoot1 = BinaryTreeNode(10)
pRoot2 = BinaryTreeNode(6)
pRoot3 = BinaryTreeNode(14)
pRoot4 = BinaryTreeNode(4)
pRoot5 = BinaryTreeNode(8)
pRoot6 = BinaryTreeNode(12)
pRoot7 = BinaryTreeNode(16)
pRoot1.left = pRoot2
pRoot1.right = pRoot3
pRoot2.left = pRoot4
pRoot2.right = pRoot5
pRoot3.left = pRoot6
pRoot3.right = pRoot7
s = Solution()
root = s.Convert(pRoot1)
print root.right.val
|
d47d171bbd0e9c2e516e859d4894abc66af2227c | briannpaull/Python-Basic-Projects | /notepad.py | 2,801 | 3.53125 | 4 | #imoort packages
from tkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename #save and open file
import os #open file path
#created function to create new file
def newFile():
global file
root.title("Untitled - Notepad")
file = None
TextArea.delete(1.0, END)
#created function to open file
def openFile():
global file
file = askopenfilename(defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if file == "":
file = None
else:
root.title(os.path.basename(file) + " - Notepad")
TextArea.delete(1.0, END)
f = open(file, "r")
TextArea.insert(1.0, f.read())
f.close()
#created function to save file
def saveFile():
global file
if file == None:
file = asksaveasfilename(initialfile = 'Untitled.txt', defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if file =="":
file = None
else:
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()
root.title(os.path.basename(file) + " - Notepad")
print("File Saved")
else:
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()
#created function for quite and editing
def quitApp():
root.destroy()
def cut():
TextArea.event_generate(("<Cut>"))
def copy():
TextArea.event_generate(("<Copy>"))
def paste():
TextArea.event_generate(("<Paste>"))
#Created text area
root = Tk()
root.title("Untitled - Notepad")
root.geometry("644x788")
TextArea = Text(root, font="lucida 13")
file = None
TextArea.pack(expand=True, fill=BOTH)
#created menubar
MenuBar = Menu(root)
FileMenu = Menu(MenuBar, tearoff=0)
#menu for new file
FileMenu.add_command(label="New", command=newFile)
#menu for open file
FileMenu.add_command(label="Open", command = openFile)
#menu for save fle
FileMenu.add_command(label = "Save", command = saveFile)
FileMenu.add_separator()
#menu for exit
FileMenu.add_command(label = "Exit", command = quitApp)
MenuBar.add_cascade(label = "File", menu=FileMenu)
#menu for editing text
EditMenu = Menu(MenuBar, tearoff=0)
EditMenu.add_command(label = "Cut", command=cut)
EditMenu.add_command(label = "Copy", command=copy)
EditMenu.add_command(label = "Paste", command=paste)
MenuBar.add_cascade(label="Edit", menu = EditMenu)
#saved menubar
root.config(menu=MenuBar)
#created crollbar
Scroll = Scrollbar(TextArea)
Scroll.pack(side=RIGHT, fill=Y)
Scroll.config(command=TextArea.yview)
TextArea.config(yscrollcommand=Scroll.set)
root.mainloop()
|
4b4a897209cb3f63275ffcb29444580ed2f1fa14 | Lucero1867/ejercicios.php | /Digitos.py | 88 | 3.671875 | 4 | numero = str(input("Ingrese numero: "))
print(numero, "tiene", len(numero), "digitos")
|
3ab5dbd6436183e69a9f256c883671738b9e17b6 | fantasylsc/LeetCode | /Algorithm/Python/50/0028_Implement_strStr.py | 2,235 | 4.1875 | 4 |
'''
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
'''
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)
if n == 0:
return 0
if m < n:
return -1
for i in range(0, m - n + 1):
for j in range(n):
if haystack[i + j] != needle[j]:
break
if j == n - 1:
return i
return -1
# Rabin Carp
# class Solution:
# def strStr(self, haystack: str, needle: str) -> int:
# L, n = len(needle), len(haystack)
# if L > n:
# return -1
#
# # base value for the rolling hash function
# a = 26
# # modulus value for the rolling hash function to avoid overflow
# modulus = 2 ** 31
#
# # lambda-function to convert character to integer
# h_to_int = lambda i: ord(haystack[i]) - ord('a')
# needle_to_int = lambda i: ord(needle[i]) - ord('a')
#
# # compute the hash of strings haystack[:L], needle[:L]
# h = ref_h = 0
# for i in range(L):
# h = (h * a + h_to_int(i)) % modulus
# ref_h = (ref_h * a + needle_to_int(i)) % modulus
# if h == ref_h:
# return 0
#
# # const value to be used often : a**L % modulus
# aL = pow(a, L, modulus)
# for start in range(1, n - L + 1):
# # compute rolling hash in O(1) time
# h = (h * a - h_to_int(start - 1) * aL + h_to_int(start + L - 1)) % modulus
# if h == ref_h:
# return start
#
# return -1
|
880dd596103ff5cd7554d27624815d089335603b | mythnc/codility-practice | /lesson7_Stacks_and_Queues/StoneWall.py | 406 | 3.546875 | 4 | #!/usr/bin/env python
def solution(B):
stack = []
count = 0
for h in B:
while len(stack) > 0 and h < stack[-1]:
stack.pop()
count += 1
if len(stack) == 0 or h > stack[-1]:
stack.append(h)
return count + len(stack)
def test():
h = [8, 8, 5, 7, 9, 8, 7, 4, 8]
assert solution(h) == 7
if __name__ == '__main__':
test()
|
5a2b6aea82dffe49acd53005936de379dc497788 | diegogcc/py-pluralsight | /advanced/advanced-python/8-abstract_base_classes/weapons03.py | 2,606 | 4.15625 | 4 | """
Implementing abstract base classes using the standard library abc
abc module
- ABCMeta metaclass
1. implements __subclasscheck__() and __instancecheck__() -> delegate to:
__subclasshook__()
returns True, False or NotImplemented
2. register a class as a virtual subclass with an abstract base class
class Text(metaclass=ABCMeta):
pass
Text.register(str) # returns the class it registers
issubclass(str, Text) # True
isinstance("Hello", Text) # True
@Text.register
class Prose:
pass
issubclass(Prose, Text) # True
- ABC base class
A class named 'ABC' that has 'ABCMeta' as its metaclass.
making it easier to declare abstract base classes (see Sword2)
- @abstracmethod decorator
"""
from abc import ABC, ABCMeta
class Sword(metaclass=ABCMeta): # virtual base class
@classmethod
def __subclasshook__(cls, sub):
return ((hasattr(sub, 'swipe') and callable(sub.swipe)
and
hasattr(sub, 'sharpen') and callable(sub.sharpen))
or NotImplemented)
def thrust(self):
print("Thrusting...")
class Sword2(ABC):
@classmethod
def __subclasshook__(cls, sub):
return ((hasattr(sub, 'swipe') and callable(sub.swipe)
and
hasattr(sub, 'sharpen') and callable(sub.sharpen))
or NotImplemented)
def thrust(self):
print("Thrusting...")
class BroadSword:
def swipe(self):
print("Swoosh!")
def sharpen(self):
print("Shink!")
class SamuraiSword:
def swipe(self):
print("Slice!")
def sharpen(self):
print("Shink!")
class Rifle:
def fire(self):
print("Bang!")
@Sword.register
class LightSaber:
def swipe(self):
print("Ffffkrrrshhzwooom.woom..woom")
if __name__ == "__main__":
issubclass(SamuraiSword, Sword) # True
issubclass(Rifle, Sword) # False
broad_sword = BroadSword()
isinstance(broad_sword, Sword) # True
""" Class Lightsaber registered as a subclass of Sword, but it doesn't implement the sharpen method"""
issubclass(LightSaber, Sword) # True
""" Using the regular class ABC we can also declare the abstract base class """
issubclass(SamuraiSword, Sword2) # True
issubclass(LightSaber, Sword2) # False |
3656b796925c171525e404058f0fdbf168ee45d5 | ampaire/witchallenges3 | /challenge2.py | 111 | 3.796875 | 4 | list1 =[1,2,3,4,5,6,7,8,9]
mylist =[1,2,3,5,6,7,9]
x = [i for i in range(1, 10) if i not in mylist]
print(x)
|
98ce7143a5c5e69d1a99af9a0dda1e229d6e7434 | zkevinbai/LPTHW | /KND_Bottles.py | 2,290 | 4.0625 | 4 | # version 1
"""
total = 100000
free = 1
time = 0
print "Total number of bottled children is now: ", total
print \
while total > 0:
x = free
total = total - x
time = 100001 - total
free = time
print "Total number of bottled children is now: ", total
print "Total number of children freed is now: ", free
print "Total amount of time taken is: ", time, "minutes,"
print time/60,"hours,", time/60/24, "days, or", time/60/24/7, "weeks"
print \
Results:
Total number of bottled children is now: -31071
Total number of children freed is now: 131072
Total amount of time taken is: 131072 minutes,
2184 hours, 91 days, or 13 weeks
"""
# this first iteration is okay, but its not taking into consideration that
# 5 kids working at the same time is still one minute
# version 2
"""
total = 100000
free = 1
time = 0
print "Total number of bottled children is now: ", total
print \
while total > 0:
total = total - free
time = time + 1
free = 1 + 100000 - total
print "Total number of bottled children is now: ", total
print "Total number of children freed is now: ", free
print "Total amount of time taken is: ", time, "minutes,"
print \
Results:
Total number of bottled children is now: -31071
Total number of children freed is now: 131072
Total amount of time taken is: 17 minutes,
0 hours, 0 days, or 0 weeks
"""
# figured it out, very interesting - this is a direct play off the doubling
# rice for each square on the chess board problem
# one last issue though, we don't want to display negative time
# version 3
total = 100000
free = 1
time = 0
print "Total number of bottled children is now: ", total
print \
while total > 0:
if total - free > 0:
total = total - free
time = time + 1
free = 1 + 100000 - total
else:
free = free + total - 1
total = 0
time = time + 1
print "Total number of bottled children is now: ", total
print "Total number of children freed is now: ", free
print "Total amount of time taken is: ", time, "minutes,"
print \
"""
Results:
Total number of bottled children is now: 0
Total number of children freed is now: 100000
Total amount of time taken is: 17 minutes,
"""
# this version is perfect, no negative sums
|
c5d41b2463e84b55d60f1582eaa61fe276f541a9 | jacksonyoudi/AlgorithmCode | /PyProject/leetcode/history/bublle_sort.py | 571 | 3.625 | 4 | from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
length = len(nums)
# 优化,如果一次都没有交换
# 冒泡排序特点
for i in range(length):
is_swap = False
for j in range(length - i - 1):
# 判断大小并交换
if nums[j] > nums[j + 1]:
is_swap = True
nums[j], nums[j + 1] = nums[j + 1], nums[j]
if is_swap is False:
return nums
return nums
|
c4768ce7583abae3d6fa0e2a8aabdcd77f3d7227 | GaloisLovWind/Python-CoreProgram | /5_number/1_basic/question.py | 1,960 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Galois
# @Date: 2019/10/22 23:36
# @File: question.py
# @Software: Program
# @Desc: 编写的代码只是其中的部分,有些过于重复和简单,没有编写执行
"""
cmd: python app.py --file_name=5_number
enter keyboard : 1
"""
import operator
def test1() -> None:
""" Number Type """
aInt: int = 1
aFloat: float = 3.5
aBool: bool = False
aComplex: complex = 1 + 1j
print("aInt = ", aInt)
print("aFloat = ", aFloat)
print("aBool = ", aBool)
print("aComplex = ", aComplex)
def test2() -> None:
""" operator """
print("1.1 + (1 + 1.1j) = ", 1.1 + (1 + 1.1j))
print("1.1 + 1 = ", 1.1 + 1)
print("1 + True = ", 1 + True)
print("-" * 20, " calculate operator")
print("2 * 3 = ", 2 * 3)
print("2 / 3 = ", 2 / 3)
print("2 // 3 = ", 2 // 3)
print("2 ** 3 = ", 2 ** 3)
print("2 % 3 = ", 2 % 3)
print("-" * 20, " bit operator")
print("2 >> 3 = ", 2 >> 3)
print("2 << 3 = ", 2 << 3)
print("2 ^ 3 = ", 2 ^ 3)
print("2 & 3 = ", 2 & 3)
print("2 | 3 = ", 2 | 3)
print("~2 = ", ~2)
def test3() -> None:
""" build-in function python3 不存在 cmp 方法,使用的是 operator 模块的中方法"""
print("operator.gt(-6 ,2) =", operator.gt(-6, 2))
print("operator.gt(-6 ,2) =", operator.gt(0xFF, 255))
print("str(0xFF) = ", str(0xFF))
print("type(0xFF) = ", type(0xFF))
print("type(1 + 1j) = ", type(1 + 1j))
print("-" * 20)
print("int(1.1) = ", int(1.1))
print("complex(2, 4) = ", complex(2, 4))
print("float(4) = ", float(4))
def test4() -> None:
""" Special build-in function """
c: C = C()
print("bool(c) = ", bool(c)) # Python3 不支持 __nonzero__ 改成 __bool__
class C(object):
def __nonzero__(self) -> None:
return False
def __bool__(self):
return True
# def __len__(self):
# return 1 |
48b022306b881bca45bfd8a738bd39656acca895 | b1ueskydragon/PythonGround | /leetcode/p0101/solve02.py | 1,164 | 3.953125 | 4 | """
Iteratively (stack)
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
stack = [root, root]
while stack:
r = stack.pop()
l = stack.pop()
if not l and not r:
continue
if not l or not r:
return False
if l.val != r.val:
return False
stack.append(r.right)
stack.append(l.left)
stack.append(r.left)
stack.append(l.right)
return True
if __name__ == '__main__':
s = Solution()
# [1, 2, 2, 3, 4, 4, 3]
a = TreeNode(1)
a.left = TreeNode(2)
a.right = TreeNode(2)
a.left.left = TreeNode(3)
a.left.right = TreeNode(4)
a.right.left = TreeNode(4)
a.right.right = TreeNode(3)
print(s.isSymmetric(root=a))
# [1, 2, 2, null, 3, null, 3]
b = TreeNode(1)
b.left = TreeNode(2)
b.right = TreeNode(2)
b.left.right = TreeNode(3)
b.right.right = TreeNode(3)
print(s.isSymmetric(root=b))
|
39ff35170fbb798f4f2e8248677dd094f02f44f3 | BBBocian/Python | /Other/100+ Pytchon challenging programming/random_choice.py | 840 | 3.578125 | 4 | import random
def random_even_0_10():
x = random.choice([x for x in range(0,11) if x%2 ==0])
print(x)
#random_even_0_10()
def random_even_div_5_7():
x = random.choice([x for x in range(201) if x%5==0 and x%7==0])
print(x)
#random_even_div_5_7()
def random5_in_100_200():
for i in range(5):
print(random.choice([x for x in range(100,201)]))
# or:
#print(random.sample(range(100,201),5))
#random5_in_100_200()
def random5_even_in_100_200():
x = random.sample(([x for x in range(100,201) if x%2==0]),5)
print(x)
#random5_even_in_100_200()
def random5_div_by_5_7_in_100_200():
x=random.sample([x for x in range(1,1001) if x%5==0 and x%7==0],5)
print(x)
#random5_div_by_5_7_in_100_200()
def random_int_7_15():
x = random.randrange(7,15)
print(x)
random_int_7_15()
|
887aa4163eb140150d35e18bf5b1c28be3391c01 | R-3030casa/Scripte_Python | /Donwload_python/Script cursoemvideo/exer000.py | 250 | 3.796875 | 4 | '''
1º Criar um script em python que leia o nome de uma pessoa e mostre uma
mensagem de boas - vindas de acordo com o valor digitado.
'''
nome=input("Digite seu nome : ")
print("\n Olá ",nome,"! \n prazer em te conhecer, seja muito bem vindo(a).")
|
3976227ae003e943e6fe8f331ce6abb2becec950 | magladde/Python-CSC-121 | /Lesson 12/geometryProject/rectangle.py | 255 | 3.9375 | 4 | def area(width, length):
""" Returns area of rectangle with given length and width """
return width * length
def perimeter(width, length):
""" Returns perimeter of rectrangle with given length and width """
return 2 * (width + length) |
ef0f4c4fe4adbe9d1e140f21989c7bb289464e09 | jayant4/deploy_version_3 | /Five_Number_Summary.py | 686 | 3.703125 | 4 | # calculate a 5-number summary
from numpy import percentile
import streamlit as st
st.title('Calculate Five Number Summary ')
data = (st.text_input(" Enter Sample values separated by ' , ' example : '1,2,3' : "))
#[1,3,2,6,8,9,10,5]
# calculate quartiles
def calculate(new_l):
quartiles = percentile(new_l, [25, 50, 75])
# calculate min/max
data_min, data_max = min(new_l),max(new_l)
# print 5-number summary
st.write(f"""
Min: {data_min} \n
Q1: {quartiles[0]} \n
Median: {quartiles[1]}\n
Q3: {quartiles[2]}\n
Max: {data_max}\n
""")
if (st.button("calculate")):
new_l = list(map(int, data.split(",")))
calculate(new_l)
|
25837c7e80da9484d4805ecb51539b1785846a6f | eduardogm81/ud_curso_data_science | /1.intro_a_python/4.estructuras_de_datos_basicas_2_tuplas.py | 550 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
*******************************************************************************
TUPLAS (TUPLES)
*******************************************************************************
Las tuplas son versiones de las listas que no se pueden modificar.
"""
mosqueteros = ("Athos", "Porthos", "Aramis")
print(type(mosqueteros))
print(mosqueteros)
#%%
#podemos acceder a los elementos de una tupla de igual forma que a una lista
print(mosqueteros[1:])
#%%
# sin embargo, no podemos modificarla
mosqueteros[3] = "D'artagnan"
#%% |
b017e5296cdd73ec7abcbcfa31e48ad0e618b042 | Dipeoliver/python_class | /EstruturaC_Controle/Class_80_break_Continue.py | 351 | 4 | 4 |
# continue - continua no laço for
# irá imiprimir apenas numeros impares
for x in range(1, 11):
if x % 2 == 0: # (%2) numeros divisiveis por 2
continue # pula a sequencia
print(x)
print("----------")
# break - sai do laço for
for x in range(1, 11):
if x == 5: # quando x for 5 entra no break
break
print(x)
|
c2815abd3d17a6ce2cdb724ad89a387afed51a3a | Maidno/Muitos_Exercicios_Python | /exe40.py | 277 | 4.0625 | 4 | nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print(media)
if media <= 5:
print('Reprovado!')
elif media >= 7:
print('Aprovado !')
elif 7 > media >= 5:
print('Aluno de recuperação') |
1d3f0c5690bae08e0a2f6dd1c749e5d63df62275 | StanislavMakhrov/OneLayerPerceptron | /pure_python/vector_.py | 308 | 3.5625 | 4 | import numpy as np
class Vector:
def __init__(self, x, d):
if len(x.shape) > 2:
self.__x = list(np.asarray(x).reshape(-2))
else:
self.__x = list(x)
self.__d = d
def get_x(self):
return self.__x
def get_d(self):
return self.__d
|
3d1bc22628b2b746f18b80f9d4f0badea5bd3fb9 | JeevanMahesha/python_program | /collections/Company_logo.py | 213 | 3.515625 | 4 | import collections as c
val = 'bbbccaaadeeee'
val = sorted(val)
val = dict(c.Counter(val))
val = [(k, v)
for k, v in sorted(val.items(), key=lambda k: k[1], reverse=True)]
val = val[:3:]
print(val)
|
2c0eb0e8a35c21c7d92b924e7e30300ed58fbb03 | sxlongwork/pythonPro | /面向对象/4-对象的初始状态(构造函数)/构造函数.py | 539 | 4.03125 | 4 | class People(object):
# name = ""
# age = 0
height = 0
weight = 0
# self就代表当前正在创建的对象
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("run......")
def eat(self, food):
print("eat {}".format(food))
'''
构造函数:__init__() 在创建对象时会自动调用
注意:如果不显示写出构造函数,会自动添加并执行无参的构造函数
'''
per = People("xiaoming", 24)
print(per.name, per.age)
|
79b4f513a674b08cbbd283cd938a4697bfaa1e5f | AlmDiana/15EjerciciosNumpy | /Codigo/main.py | 4,929 | 4.25 | 4 | import numpy as np
#Ejercicio 6
print("\n1. << Ejercicio 6 >>\n")
print("Create a vector with values ranging from 10 to 49\n")
z = np.arange(10,50)
print(z)
print("\n")
#Ejercicio 12
print("\n2. << Ejercicio 12 >>\n")
print("Create a 10x10 array with random values and find the minimum and maximum values\n")
Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
print("\n")
#Ejercicio 18
print("\n3. << Ejercicio 18 >>\n")
print("Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?\n")
print(np.unravel_index(100,(6,7,8)))
print("\n")
#Ejercicio 24
print("\n4. << Ejercicio 24 >>\n")
print("What is the output of the following script? \n")
print("Output 1: ")
print(sum(range(5),-1)) # Salida: 9
from numpy import *
print ("Output 2:")
print(sum(range(5),-1)) # Salida: 10
#Ejercicio 30
print("\n5. << Ejercicio 30 >>\n")
print("Consider a generator function that generates 10 integers and use it to build an array\n")
#Función que genera 10 elementos
def generate():
for x in range(10):
yield x
#Construcción del array
K = np.fromiter(generate(),dtype=float,count=-1)
print("ARRAY: ", K)
#Ejercicio 37
print("\n6. << Ejercicio 37 >>\n")
print("Create random vector of size 10 and replace the maximum value by 0\n")
matriz = np.random.randint(0, 100, 10)
print("Arreglo original: ")
print(matriz)
matriz[matriz.argmax()] = 0
print("Arreglo remplazado: ")
print(matriz)
#Ejercicio 42
print("\n7. << Ejercicio 42 >>\n")
print("How to find the closest value (to a given scalar) in an array?\n")
Z = np.random.randint(0, 1000, 100)
print("Arreglo: \n", Z)
valor = input("\n Ingrese un valor aleatorio entre 0 y 1000: ")
index = (np.abs(Z-int(valor))).argmin()
print(Z[index])
#Ejercicio 48
print("\n8. << Ejercicio 48 >>\n")
print("Generate a generic 2D Gaussianlike array\n")
#La funcion Gaussiana o campana de Gaus se utiliza para inferir la probabilidad de un valor
x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
d = np.sqrt(x*x+y*y)
sigma, mu = 1.0, 0.0
gaussiana = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) )
print("2D Gaussian como array:")
print(gaussiana)
#Ejercicio 54
print("\n9. << Ejercicio 54 >>\n")
print("Create an array class that has a name attribute \n")
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
#Ejercicio 60
print("\n10. << Ejercicio 60 >>\n")
print("How to get the diagonal of a dot product?\n")
A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))
# Slow version
print("SLOW VERSION: ",np.diag(np.dot(A, B)))
# Fast version
print("FAST VERSION: ",np.sum(A * B.T, axis=1))
# Faster version
print("FASTER VERSION: ", np.einsum("ij,ji->i", A, B))
#Ejercicio 66
print("\n11. << Ejercicio 66 >>\n")
print("How to compute averages using a sliding window over an array?\n")
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
print("ARRAY:", moving_average(Z, n=3))
#Ejercicio 72
print("\n12. << Ejercicio 72 >>\n")
print("Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]?\n")
from numpy.lib import stride_tricks
Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(" ARRAY: \n", R)
#Ejercicio 78
print("\n13. << Ejercicio 78 >>\n")
print("Consider a 16x16 array, how to get the blocksum (block size is 4x4)?\n")
Z = np.ones((16,16))
k = 4
S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), np.arange(0, Z.shape[1], k), axis=1)
print(S)
#Ejercicio 84
print("\n14. << Ejercicio 84 >>\n")
print("Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B?\n")
A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))
C = (A[..., np.newaxis, np.newaxis] == B)
rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0]
print(rows)
#Ejercicio 90
print("\n15. << Ejercicio 90 >>\n")
print("Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n.\n")
X = np.asarray([[1.0, 0.0, 3.0, 8.0],
[2.0, 0.0, 1.0, 1.0],
[1.5, 2.5, 1.0, 0.0]])
n = 4
M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
M &= (X.sum(axis=-1) == n)
print(X[M])
|
bda917ead48fef7e31f6abb82b2121f85cbc8ce1 | Jimwa2/Sudoku_Codecademy | /board.py | 12,992 | 4.125 | 4 | import random
class Board:
def __init__(self, difficulty):
self.difficulty = difficulty
self.board = {}
self.row_list = {}
self.column_list = {}
self.three_by_three_list = {}
self.poss_choices_row = {}
self.poss_choices_column = {}
self.poss_choices_three_by_three = {}
self.failed_coordinates = {}
def __repr__(self):
return str(self.board)
def create_board(self):
#This function creates an empty board by adding key:value pairs to the self.board dictionary.
#The keys are tuples of the (row, column, section) coordinates, and the values will be the number at that coordinate, currently set to None.
#The section is determined by checking the row and column using if statements, to see what three by three section they fit into.
row = 1
column = 1
section = 1
while (row <= 9):
if row in range(1, 4):
if column in range(1, 4):
section = 1
if column in range(4, 7):
section = 2
if column in range(7, 10):
section = 3
if row in range(4, 7):
if column in range(1, 4):
section = 4
if column in range(4, 7):
section = 5
if column in range(7, 10):
section = 6
if row in range(7, 10):
if column in range(1, 4):
section = 7
if column in range(4, 7):
section = 8
if column in range(7, 10):
section = 9
self.board[(row, column, section)] = None
if column == 9:
column = 1
row += 1
else:
column += 1
def generate_sublists(self):
#This function generates the lists used to adhere to the rules of Sudoku.
#Generates row, column, and three_by_three lists of coordinates.
for num in range(1, 10):
self.row_list[num] = []
self.column_list[num] = []
self.three_by_three_list[num] = []
for coordinate in self.board:
self.row_list[coordinate[0]].append(coordinate)
self.column_list[coordinate[1]].append(coordinate)
self.three_by_three_list[coordinate[2]].append(coordinate)
#Generates poss_choices lists of possible choices from 1 to 9.
key_pointer = 1
while key_pointer < 10:
self.poss_choices_row[key_pointer] = []
self.poss_choices_column[key_pointer] = []
self.poss_choices_three_by_three[key_pointer] = []
for i in range(1, 10):
self.poss_choices_row[key_pointer].append(i)
self.poss_choices_column[key_pointer].append(i)
self.poss_choices_three_by_three[key_pointer].append(i)
key_pointer += 1
def add_choice_to_coordinate(self, coordinate, choice_to_be_added):
self.board[coordinate] = choice_to_be_added
self.poss_choices_row[coordinate[0]].remove(choice_to_be_added)
self.poss_choices_column[coordinate[1]].remove(choice_to_be_added)
self.poss_choices_three_by_three[coordinate[2]].remove(choice_to_be_added)
print(coordinate, "set to:", choice_to_be_added)
def remove_choice_from_coordinate(self, coordinate):
choice_to_be_removed = self.board[coordinate]
self.board[coordinate] = None
self.poss_choices_row[coordinate[0]].append(choice_to_be_removed)
self.poss_choices_column[coordinate[1]].append(choice_to_be_removed)
self.poss_choices_three_by_three[coordinate[2]].append(choice_to_be_removed)
print(coordinate, "set to: None")
def swap_coordinate_values(self, coordinate, other_coord):
coordinate_value = self.board[coordinate]
other_coord_value = self.board[other_coord]
self.remove_choice_from_coordinate(coordinate)
self.add_choice_to_coordinate(coordinate, other_coord_value)
self.remove_choice_from_coordinate(other_coord)
self.add_choice_to_coordinate(other_coord, coordinate_value)
def look_for_possible_swap(self, coordinate):
choice_to_be_added = 0
poss_choices_row = self.poss_choices_row[coordinate[0]]
poss_choices_column = self.poss_choices_column[coordinate[1]]
poss_choices_three_by_three = self.poss_choices_three_by_three[coordinate[2]]
print("Looking for coordinate to swap with...")
#Search through other coordinates within the current row for a possible swap.
for other_coord in self.row_list[coordinate[0]]:
#For each choice within the current coordinate's poss_choices_row...
for choice in poss_choices_row:
#if the choice is in the other_coord's poss_choices_column and poss_choices_three_by_three...
if choice in self.poss_choices_column[other_coord[1]] and choice in self.poss_choices_three_by_three[other_coord[2]]:
#and the other_coord's value is a valid choice for the current coordinate...
if self.board[other_coord] in poss_choices_column and self.board[other_coord] in poss_choices_three_by_three:
choice_to_be_added = self.board[other_coord]
self.remove_choice_from_coordinate(other_coord)
self.add_choice_to_coordinate(other_coord, choice)
break
if choice_to_be_added:
self.add_choice_to_coordinate(coordinate, choice_to_be_added)
return
#Search through other coordinates within the current column for a possible swap.
for other_coord in self.column_list[coordinate[1]]:
###
for choice in poss_choices_column:
###
if choice in self.poss_choices_row[other_coord[0]] and choice in self.poss_choices_three_by_three[other_coord[2]]:
###
if self.board[other_coord] in poss_choices_row and self.board[other_coord] in poss_choices_three_by_three:
choice_to_be_added = self.board[other_coord]
self.remove_choice_from_coordinate(other_coord)
self.add_choice_to_coordinate(other_coord, choice)
break
if choice_to_be_added:
self.add_choice_to_coordinate(coordinate, choice_to_be_added)
return
#Search through other coordinates within the current three_by_three for a possible swap.
for other_coord in self.three_by_three_list[coordinate[2]]:
###
for choice in poss_choices_three_by_three:
###
if choice in self.poss_choices_row[other_coord[0]] and choice in self.poss_choices_column[other_coord[1]]:
###
if self.board[other_coord] in poss_choices_row and self.board[other_coord] in poss_choices_column:
choice_to_be_added = self.board[other_coord]
self.remove_choice_from_coordinate(other_coord)
self.add_choice_to_coordinate(other_coord, choice)
break
if choice_to_be_added:
self.add_choice_to_coordinate(coordinate, choice_to_be_added)
return
if not choice_to_be_added:
print("No valid choice found for coordinate:", coordinate)
self.failed_coordinates[coordinate] = None
#for other_coord in self.three_by_three_list[coordinate[2]]:
#if self.board[other_coord] in
def fix_failed_coordinates(self):
while self.failed_coordinates:
for coordinate in self.failed_coordinates:
self.failed_coordinates[coordinate] = [self.poss_choices_row[coordinate[0]][0], self.poss_choices_column[coordinate[1]][0], self.poss_choices_three_by_three[coordinate[2]][0]]
for coordinate in self.failed_coordinates:
#To fix coordinates which have only one possible choice in all three of their poss_choice lists.
if len(set(self.failed_coordinates[coordinate])) == 1:
self.add_choice_to_coordinate(coordinate, self.failed_coordinates[coordinate][0])
del self.failed_coordinates[coordinate]
break
#
if len(set(self.failed_coordinates[coordinate])) == 2:
#Find out which number is an option for two sublists...
counter_dict = {}
for num in self.failed_coordinates[coordinate]:
if num not in counter_dict:
counter_dict[num] = 1
else:
counter_dict[num] += 1
higher_count = max([(value, key) for key, value in counter_dict.items()])[1]
lower_count = min([(value, key) for key, value in counter_dict.items()])[1]
#...and which sublist does not have that number (row, column, or three_by_three).
sublist_to_change = self.failed_coordinates[coordinate].index(lower_count)
#change_queue = [coordinate, sublist_to_change]
#del self.failed_coordinates[coordinate]
for other_coord in self.failed_coordinates:
if self.failed_coordinates[other_coord][sublist_to_change] == higher_count:
if sublist_to_change == 0:
self.poss_choices_row[coordinate[0]] = [higher_count]
self.poss_choices_row[other_coord[0]] = [lower_count]
if sublist_to_change == 1:
self.poss_choices_column[coordinate[1]] = [higher_count]
self.poss_choices_column[other_coord[1]] = [lower_count]
if sublist_to_change == 2:
self.poss_choices_three_by_three[coordinate[2]] = [higher_count]
self.poss_choices_three_by_three[other_coord[2]] = [lower_count]
break
break
def min_len_list_index(self, row_list, column_list, three_by_three_list):
combined_list = [row_list, column_list, three_by_three_list]
min_len_list = min(combined_list, key = len)
return combined_list.index(min_len_list)
def populate_board(self):
for coordinate in self.board:
print("\nSetting coordinate ", coordinate)
choice_list = []
choice_to_be_added = 0
poss_choices_row = self.poss_choices_row[coordinate[0]]
poss_choices_column = self.poss_choices_column[coordinate[1]]
poss_choices_three_by_three = self.poss_choices_three_by_three[coordinate[2]]
print("poss_choices_row = " + str(poss_choices_row))
print("poss_choices_column = " + str(poss_choices_column))
print("poss_choices_three_by_three = " + str(poss_choices_three_by_three))
for choice in poss_choices_row:
if choice in poss_choices_column:
if choice in poss_choices_three_by_three:
choice_list.append(choice)
print("choice_list =", choice_list)
if choice_list:
choice_to_be_added = random.choice(choice_list)
self.add_choice_to_coordinate(coordinate, choice_to_be_added)
else:
self.look_for_possible_swap(coordinate)
print(self.poss_choices_row)
print(self.poss_choices_column)
print(self.poss_choices_three_by_three)
if self.failed_coordinates:
print("\nFixing failed coordinates:", self.failed_coordinates)
self.fix_failed_coordinates()
def set_difficulty(self):
coords_to_remove = 0
to_be_removed = ()
list_of_coords = list(self.board.keys())
if self.difficulty == 'easy':
coords_to_remove = 36
if self.difficulty == 'medium':
coords_to_remove = 46
if self.difficulty == 'hard':
coords_to_remove = 56
while coords_to_remove:
to_be_removed = random.choice(list_of_coords)
self.remove_choice_from_coordinate(to_be_removed)
list_of_coords.remove(to_be_removed)
coords_to_remove -= 1
test_board = Board('hard')
test_board.create_board()
test_board.generate_sublists()
test_board.populate_board()
print(test_board.row_list)
#print("\n", test_board) |
3b0f6448fe07c4f21ca5e91e5249816f80889e3f | Sandhiya-04/python-programming | /Beginner level/sum of n numbers.py | 76 | 3.59375 | 4 | san=int(input())
s=0
while(san>0):
s=s+san
san=san-1
print(s)
|
72911a4d908c9b088ee56180669e6522f555d4eb | CSUChico-CINS465/CINS465-F19-Examples | /test.py | 652 | 4.15625 | 4 | #!/usr/bin/python
print("Hello World")
x=3
x="c"
x=[1,2,3]
x=[1,"2",3]
def x(x):
print(x)
#
# x(x)
y="y"
x=3
z = str(x) + y
print(z)
x = [1,2,3]
x += [4]
x.append(5)
y = (1,2,3)
x+=[y]
try:
y += (4)
except:
print("Tuple's are immutable")
# print(x[5][2])
z = {"key":"value","list":x, "tuple":y}
print(z)
# print(x[2])
# print(y[2])
class MyClass:
"""A simple example class"""
def __init__(self):
self.data = []
self.i = 12345
def f(self, blah, alice=4, bob=5):
# self.bob= 4
return 'hello world ' + str(blah) + " " + str(alice) + " " + str(bob)
x = MyClass()
print(x.f(bob=1, blah="hi"))
|
d39e34c6b7f4fc82db4a6b69278e93ad4b874202 | chrysmur/Python-DS-and-Algorithms | /implementing_queues.py | 1,056 | 4 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = None
self.length = 0
def peek(self):
try:
return self.first.value
except:
raise Exception("Empty Queue")
def enqueue(self, value):
newNode = Node(value)
if self.first is None:
self.first = self.last = newNode
elif self.first == self.last:
self.first.next = newNode
self.last = newNode
self.last.next = newNode
self.last = newNode
self.length += 1
return self
def dequeue(self):
if self.first == self.last:
self.first = self.last = None
return self
self.first = self.first.next
return self
newq = Queue()
newq.enqueue("harley")
newq.enqueue("tom")
newq.enqueue("mary")
newq.dequeue()
newq.dequeue()
newq.dequeue()
print(newq.first.value)
print(newq.last.value) |
b8a2bfdc3ff9d78a2a5aa7ce68badeec98804f6e | Jackiecoder/Algorithm | /little bro/Queue & Stack/232_Implement Queue using Stacks.py | 1,215 | 3.984375 | 4 | '''
Compare with 225
'''
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = collections.deque()
self.stack_temp = collections.deque()
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
stack = self.stack
stack_temp = self.stack_temp
for _ in range(len(stack)):
stack_temp.append(stack.pop())
stack.append(x)
for _ in range(len(stack_temp)):
stack.append(stack_temp.pop())
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
stack = self.stack
return stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
stack = self.stack
res = stack.pop()
stack.append(res)
return res
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
stack = self.stack
return not bool(len(stack))
|
6ac591d4a4f9f23ac68c76ebc36a5b07f82acf7a | AravindVasudev/Interview-Prep-Group | /Aravind/problem-1.py | 3,397 | 3.9375 | 4 | ###############################################################################
# Given a linked list, rotate the list to the right by k places, where k is #
# non-negative. #
# Example 1: #
# Input: 1->2->3->4->5->NULL, k = 2 #
# Output: 4->5->1->2->3->NULL #
# Explanation: #
# rotate 1 steps to the right: 5->1->2->3->4->NULL #
# rotate 2 steps to the right: 4->5->1->2->3->NULL #
###############################################################################
import copy
class LinkedList:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def __len__(self):
slow, fast = self, self
length = 1
while (slow.next is not None) and (fast is not None) and \
(fast.next is not None):
slow = slow.next
fast = fast.next.next
length += 2
# Length is twice of midpoint distance. Remove 1 for even.
return length - 1 if fast is None else length
def __str__(self):
serialized = str(self.data)
ptr = self
while ptr.next is not None:
ptr = ptr.next
serialized += ' -> ' + str(ptr.data)
return serialized
def rotate_list_right(lst, k):
"""
:param lst: A LinkedList
:param k: A non-negative number of rotations
"""
if (lst is None) or (k is 0):
return lst
length = len(lst)
if k == length:
return lst
if k > length:
k %= length
ptr = lst
for _ in range(length - k - 1):
ptr = ptr.next
last_node = ptr
while last_node.next is not None:
last_node = last_node.next
last_node.next = lst
new_head = ptr.next
ptr.next = None
return new_head
def main():
"""
Test cases
"""
# TODO: Clean up
# Test Case 1
test_case_1 = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4, LinkedList(5)))))
output_1 = rotate_list_right(copy.deepcopy(test_case_1), 2)
print('Input: ', test_case_1)
print('Output: ', output_1)
# Test Case 2
test_case_2 = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4))))
output_2 = rotate_list_right(copy.deepcopy(test_case_2), 2)
print('Input: ', test_case_2)
print('Output: ', output_2)
# Test Case 3
test_case_3 = None
output_3 = rotate_list_right(test_case_3, 2)
print('Input: ', test_case_3)
print('Output: ', output_3)
# Test Case 4
test_case_4 = LinkedList(1)
output_4 = rotate_list_right(copy.deepcopy(test_case_4), 2)
print('Input: ', test_case_4)
print('Output: ', output_4)
# Test Case 5
test_case_5 = LinkedList(1, LinkedList(2))
output_5 = rotate_list_right(copy.deepcopy(test_case_5), 2)
print('Input: ', test_case_5)
print('Output: ', output_5)
# Test Case 6
test_case_6 = LinkedList(1, LinkedList(2))
output_6 = rotate_list_right(copy.deepcopy(test_case_6), 1)
print('Input: ', test_case_6)
print('Output: ', output_6)
if __name__ == '__main__':
main()
|
dfcb723d5b687f9cb6b227f40dc4b855c118e3f8 | FreddieBoi/pytd | /src/pathfinder.py | 13,128 | 4.15625 | 4 | '''
Pathfinder.
@author: Freddie
'''
from collections import defaultdict
from math import sqrt, fabs
import heapq
class PriorityQueueSet(object):
""" Combined priority queue and set data structure. Acts like
a priority queue, except that its items are guaranteed to
be unique.
Provides O(1) membership test and O(log N) removal of the
*smallest* item. Addition is more complex. When the item
doesn't exist, it's added in O(log N). When it already
exists, its priority is checked against the new item's
priority in O(1). If the new item's priority is smaller,
it is updated in the queue. This takes O(N).
Important: The items you store in the queue have identity
(that determines when two items are the same, as far as
you're concerned) and priority. Therefore, you must
implement the following operators for them: __hash__,
__cmp__ and __eq__.
* __eq__ will be used for exact comparison of items. It
must return True if and only if the items are identical
from your point of view (although their priorities can
be different)
* __cmp__ will be used to compare priorities. Two items
can be different and have the same priority, and even
be equal but have different priorities (though they
can't be in the queue at the same time)
* __hash__ will be used to hash the items for
efficiency. To implement it, you almost always have
to just call hash() on the attribute you're comparing
in __eq__
"""
def __init__(self):
""" Create a new PriorityQueueSet
"""
self.set = {}
self.heap = []
def __len__(self):
return len(self.heap)
def has_item(self, item):
""" Check if *item* exists in the queue
"""
return item in self.set
def pop_smallest(self):
""" Remove and return the smallest item from the queue.
IndexError will be thrown if the queue is empty.
"""
smallest = heapq.heappop(self.heap)
del self.set[smallest]
return smallest
def add(self, item):
""" Add *item* to the queue.
If such an item already exists, its priority will be
checked versus *item*. If *item*'s priority is better
(i.e. lower), the priority of the existing item in the
queue will be updated.
Returns True iff the item was added or updated.
"""
if not item in self.set:
self.set[item] = item
heapq.heappush(self.heap, item)
return True
elif item < self.set[item]:
# No choice but to search linearly in the heap
for idx, old_item in enumerate(self.heap):
if old_item == item:
del self.heap[idx]
self.heap.append(item)
heapq.heapify(self.heap)
self.set[item] = item
return True
return False
class GridMap(object):
""" Represents a rectangular grid map. The map consists of
rows X cols coordinates (squares). Some of the squares
can be blocked (by obstacles).
"""
def __init__(self, rows, cols):
""" Create a new GridMap with specified number of rows and columns.
"""
self.rows = rows
self.cols = cols
self.map = [[0] * self.cols for i in range(self.rows)]
self.blocked = defaultdict(lambda: False)
def set_blocked(self, coord, blocked=True):
""" Set the blocked state of a coordinate. True for
blocked, False for unblocked.
"""
self.map[coord[0]][coord[1]] = blocked
if blocked:
self.blocked[coord] = True
else:
if coord in self.blocked:
del self.blocked[coord]
def is_blocked(self, coord):
try:
return self.map[coord[0]][coord[1]]
except IndexError:
return True
def move_cost(self, c1, c2):
""" Compute the cost of movement from one coordinate to
another.
The cost is the Euclidean distance.
"""
return sqrt((c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2)
def successors(self, c):
""" Compute the successors of coordinate 'c': all the
coordinates that can be reached by one step from 'c'.
"""
slist = []
for drow in (-1, 0, 1):
for dcol in (-1, 0, 1):
if fabs(drow) == fabs(dcol):
continue
newrow = c[0] + drow
newcol = c[1] + dcol
if (0 <= newrow <= self.rows-1 and
0 <= newcol <= self.cols-1 and
self.map[newrow][newcol] == 0):
slist.append((newrow, newcol))
return slist
def printme(self):
""" Print the map to stdout in ASCII
"""
for row in range(self.rows):
for col in range(self.cols):
print "%s" % ('O' if self.map[row][col] else '.'),
print ''
class PathFinder(object):
""" Computes a path in a graph using the A* algorithm.
Initialize the object and then repeatedly compute_path to
get the path between a start point and an end point.
The points on a graph are required to be hashable and
comparable with __eq__. Other than that, they may be
represented as you wish, as long as the functions
supplied to the constructor know how to handle them.
"""
def __init__(self, successors, move_cost, heuristic_to_goal):
""" Create a new PathFinder. Provided with several
functions that represent your graph and the costs of
moving through it.
successors:
A function that receives a point as a single
argument and returns a list of "successor" points,
the points on the graph that can be reached from
the given point.
move_cost:
A function that receives two points as arguments
and returns the numeric cost of moving from the
first to the second.
heuristic_to_goal:
A function that receives a point and a goal point,
and returns the numeric heuristic estimation of
the cost of reaching the goal from the point.
"""
self.successors = successors
self.move_cost = move_cost
self.heuristic_to_goal = heuristic_to_goal
def compute_path(self, start, goal):
""" Compute the path between the 'start' point and the
'goal' point.
The path is returned as an iterator to the points,
including the start and goal points themselves.
If no path was found, an empty list is returned.
"""
# A* algorithm
closed_set = {}
start_node = Node(start)
start_node.g_cost = 0
start_node.f_cost = self._compute_f_cost(start_node, goal)
open_set = PriorityQueueSet()
open_set.add(start_node)
while len(open_set) > 0:
# Remove and get the node with the lowest f_score from
# the open set
#
curr_node = open_set.pop_smallest()
if curr_node.coord == goal:
return self._reconstruct_path(curr_node)
closed_set[curr_node] = curr_node
for succ_coord in self.successors(curr_node.coord):
succ_node = Node(succ_coord)
succ_node.g_cost = self._compute_g_cost(curr_node, succ_node)
succ_node.f_cost = self._compute_f_cost(succ_node, goal)
if succ_node in closed_set:
continue
if open_set.add(succ_node):
succ_node.pred = curr_node
return []
def _compute_g_cost(self, from_node, to_node):
return (from_node.g_cost +
self.move_cost(from_node.coord, to_node.coord))
def _compute_f_cost(self, node, goal):
return node.g_cost + self._cost_to_goal(node, goal)
def _cost_to_goal(self, node, goal):
return self.heuristic_to_goal(node.coord, goal)
def _reconstruct_path(self, node):
""" Reconstructs the path to the node from the start node
(for which .pred is None)
"""
pth = [node.coord]
n = node
while n.pred:
n = n.pred
pth.append(n.coord)
return reversed(pth)
class Node(object):
""" Used to represent a node on the searched graph during
the A* search.
Each Node has its coordinate (the point it represents),
a g_cost (the cumulative cost of reaching the point
from the start point), a f_cost (the estimated cost
from the start to the goal through this point) and
a predecessor Node (for path construction).
The Node is meant to be used inside PriorityQueueSet,
so it implements equality and hashinig (based on the
coordinate, which is assumed to be unique) and
comparison (based on f_cost) for sorting by cost.
"""
def __init__(self, coord, g_cost=None, f_cost=None, pred=None):
self.coord = coord
self.g_cost = g_cost
self.f_cost = f_cost
self.pred = pred
def __eq__(self, other):
return self.coord == other.coord
def __cmp__(self, other):
return cmp(self.f_cost, other.f_cost)
def __hash__(self):
return hash(self.coord)
def __str__(self):
return 'N(%s) -> g: %s, f: %s' % (self.coord, self.g_cost, self.f_cost)
def __repr__(self):
return self.__str__()
class GridPath(object):
""" Represents the game grid and answers questions about
paths on this grid.
After initialization, call set_blocked for changed
information about the state of blocks on the grid, and
get_next to get the next coordinate on the path to the
goal from a given coordinate.
"""
def __init__(self, rows, cols, goal):
self.map = GridMap(rows, cols)
self.goal = goal
# Path cache. For a coord, keeps the next coord to move to in order to
# reach the goal. Invalidated when the grid changes (with set_blocked)
self._path_cache = {}
def get_next(self, coord):
""" Get the next coordinate to move to from 'coord'
towards the goal.
"""
# If the next path for this coord is not cached, compute it
if not (coord in self._path_cache):
self._compute_path(coord)
# _compute_path adds the path for the coord to the cache.
# If it's still not cached after the computation, it means
# that no path exists to the goal from this coord.
if coord in self._path_cache:
return self._path_cache[coord]
else:
return None
def set_blocked(self, coord, blocked=True):
""" Set the 'blocked' state of a coord
"""
self.map.set_blocked(coord, blocked)
# Invalidate cache, because the map has changed
self._path_cache = {}
def _compute_path(self, coord):
pathfinder = PathFinder(self.map.successors, self.map.move_cost,
self.map.move_cost)
# Get the whole path from coord to the goal into a list,
# and for each coord in the path write the next coord in
# the path into the path cache
path_list = list(pathfinder.compute_path(coord, self.goal))
for i, path_coord in enumerate(path_list):
next_i = i if i == len(path_list) - 1 else i + 1
self._path_cache[path_coord] = path_list[next_i]
return path_list
if __name__ == "__main__":
# test the pathfinder
start = 0, 0
goal = 1, 7
test_map = GridMap(8, 8)
blocked = [(1, 1), (0, 2), (1, 2), (0, 3), (1, 3), (2, 3), (2, 5), (2, 5),
(2, 5), (2, 7)]
for b in blocked:
test_map.set_blocked(b)
# test_map.set_blocked((1,0))
test_map.printme()
pathfinder = PathFinder(test_map.successors, test_map.move_cost,
test_map.move_cost)
import time
t = time.clock()
path = list(pathfinder.compute_path(start, goal))
print "Elapsed: %s" % (time.clock() - t)
print path
if len(path) == 0:
print "Blocking!"
|
9484982ae015a4832a0822476e7120b83cc31c8b | GBeckerRS/trabGBredes | /cliente.py | 2,067 | 3.515625 | 4 | #!/usr/bin/env/python
import sys
from terminal import *
from arquivo import *
from socket_cliente import *
class Cliente:
def __init__ (self, interfaceGrafica, tamanhoBuffer):
self.interfaceGrafica = interfaceGrafica
self.ip = ''
self.porta = 0
self.nomeArquivo = ""
self.term = None
self.arquivo = None
self.tamanhoBuffer = tamanhoBuffer
def executa (self):
dados = ''
# Inicializa atributos do cliente
self.inicializa ()
# Le dados do arquivo que sera enviado
self.arquivo = Arquivo (self.nomeArquivo)
self.arquivo.abre ('r')
dados = self.arquivo.le ()
self.arquivo.fecha ()
soc = Socket_cliente (self.ip, self.porta, self.tamanhoBuffer)
print 'Inciando a transmissao de dados...'
tamanho = len (dados)
tamanhoPacote = self.tamanhoBuffer
if (tamanho < tamanhoPacote):
tamanhoPacote = tamanho
inicio = 0
final = tamanhoPacote
contadorPacotes = 0
while inicio < (tamanho -1):
print 'Enviando o pacote: ' + str (contadorPacotes)
# Envia dados para o servidor
soc.enviaDados (dados [inicio:final])
inicio = final
final += tamanhoPacote
contadorPacotes += 1
print 'Encerrando a transmissao, foram enviados ' + \
str (contadorPacotes) + \
' pacotes para o host...'
def inicializa (self):
if (self.interfaceGrafica == 'N'):
# Inicializa a interface em modo texto
self.term = Terminal ()
else:
# Inicializa a interface grafica (nao implementada)
self.term = Terminal ()
# Requisita o ip do host
self.ip = self.term.leIp ()
# Requisita a porta do cliente
self.porta = self.term.lePorta ()
# Requisita o caminho do arquivo
self.nomeArquivo = self.term.leCaminhoArquivo ('Digite nome (caminho completo) do arquivo a enviar')
|
46b05e39e4caee295432c1139351ac81ad96b82d | zhaojinyun15/permutation-arithmetic | /main.py | 1,597 | 3.640625 | 4 | import random
import time
import permutation
def create_random_list(list_len):
"""
生成随机数list
:param list_len:
:return:
"""
if list_len < 0:
raise Exception('params error!')
if list_len > 100000:
raise Exception('too long list!')
max_num = list_len * 10
random_list = []
for i in range(list_len):
random_list.append(random.randint(1, max_num))
# yield random.randint(1, max_num)
return random_list
def check_permutation(unchecked_list, order='asc'):
"""
检查list是否已排序
:param unchecked_list:
:param order:
:return:
"""
if order not in ['asc', 'desc']:
raise Exception('order param should be asc or desc!')
for i in range(len(unchecked_list)):
if i + 1 < len(unchecked_list):
if (order == 'asc' and unchecked_list[i] > unchecked_list[i + 1]) or \
(order == 'desc' and unchecked_list[i] < unchecked_list[i + 1]):
return False
return True
if __name__ == '__main__':
random_list = create_random_list(100000)
# print(random_list)
start_time = time.time()
# permutation.bubble(random_list)
# permutation.insertion(random_list)
# permutation.merge(random_list, 0, len(random_list) - 1)
# permutation.shell(random_list)
# permutation.heap(random_list)
permutation.quick(random_list, 0, len(random_list) - 1)
end_time = time.time()
print(f'takes time: {(end_time - start_time) * 1000} ms')
# print(random_list)
print(check_permutation(random_list))
|
44e23ee50f64db9c69e055f61d1926b04a79d7b3 | georgiosdoumas/Manning-liveProject | /CreateIteratorGenerator.py | 2,285 | 3.75 | 4 | class CountIterator:
def __init__(self, limit):
self.limit = limit
self.count = 0
def __next__(self):
if self.count < self.limit:
value = self.count
self.count += 1
return value
else:
raise StopIteration
def __iter__(self):
return self
class FibonaciIterator:
def __init__(self, maxfib):
self.limit = maxfib
self.previous = 1
self.current = 1
self.count = 0
def __next__(self):
if self.count < self.limit:
if self.count == 0:
self.count += 1
return self.previous
elif self.count == 1:
self.count += 1
return self.current
else:
temp = self.previous + self.current
self.previous = self.current
self.current = temp
self.count += 1
return self.current
else:
raise StopIteration
def __iter__(self):
return self
def count_generator(limit):
count = 0
while count < limit:
yield count
count += 1
def FibonaciGenerator(maxfib):
previous = 0
current = 1
while current < maxfib:
if previous == 0:
yield current
previous += 1
else:
yield current
temp = current
current = temp + previous
previous = temp
countiter01 = CountIterator(10)
for c in countiter01:
print(c)
countiter02 = CountIterator(5)
listc = [c for c in countiter02]
print(listc) # [0, 1, 2, 3, 4]
countiter03 = CountIterator(3)
print(countiter03)
print(next(countiter03)) # 0
print(next(countiter03)) # 1
print(next(countiter03)) # 2
try:
print(next(countiter03))
except StopIteration:
print("You went too far")
fib_iterator01 = FibonaciIterator(7)
for number in fib_iterator01:
print(number)
fib_iterator02 = FibonaciIterator(8)
fib_list = [f for f in fib_iterator02 ]
print(fib_list) # [1, 1, 2, 3, 5, 8, 13, 21]
print("\n Generator:")
for x in count_generator(5):
print(x)
print("\n Fibonaci Generator function:")
for f in FibonaciGenerator(11):
print(f) # prints the fib numbers smaller than 11 : 1,1,2,3,5,8
|
4d34c27d91df4a865872dffb9920138cfa2e01e5 | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/final_exam_preparation/password_reset.py | 791 | 3.953125 | 4 | password = input()
word = input()
new_password = ''
while not word == "Done":
command = word.split()
if 'TakeOdd' in command:
for i in range(1, len(password), 2):
new_password += password[i]
password = new_password
print(password)
elif 'Cut' in command:
index = int(command[1])
length = int(command[2])
password = password[:index] + password[index + length:]
print(password)
elif 'Substitute' in command:
substring = command[1]
substitute = command[2]
if substring in password:
password = password.replace(substring, substitute)
print(password)
else:
print("Nothing to replace!")
word = input()
print(f"Your password is: {password}") |
5777a0a25c42be00629818a036b06dfd37f46b63 | rohegde7/competitive_programming_codes | /GoogCJ-Saving_The_Universe_Again.py | 6,225 | 3.5 | 4 | # Author of the code: Rohit Hegde - hegde.rohit7@gmail.com (https://www.github.com/rohegde7)
# solution: LINE 94
# https://codejam.withgoogle.com/2018/challenges/00000000000000cb/dashboard
# status: All test cases passed
'''
Problem
An alien robot is threatening the universe, using a beam that will destroy all algorithms knowledge. We have to stop it!
Fortunately, we understand how the robot works. It starts off with a beam with a strength of 1, and it will run a program that is a series of instructions, which will be executed one at a time, in left to right order. Each instruction is of one of the following two types:
C (for "charge"): Double the beam's strength.
S (for "shoot"): Shoot the beam, doing damage equal to the beam's current strength.
For example, if the robot's program is SCCSSC, the robot will do the following when the program runs:
Shoot the beam, doing 1 damage.
Charge the beam, doubling the beam's strength to 2.
Charge the beam, doubling the beam's strength to 4.
Shoot the beam, doing 4 damage.
Shoot the beam, doing 4 damage.
Charge the beam, increasing the beam's strength to 8.
In that case, the program would do a total of 9 damage.
The universe's top algorithmists have developed a shield that can withstand a maximum total of D damage. But the robot's current program might do more damage than that when it runs.
The President of the Universe has volunteered to fly into space to hack the robot's program before the robot runs it. The only way the President can hack (without the robot noticing) is by swapping two adjacent instructions. For example, the President could hack the above program once by swapping the third and fourth instructions to make it SCSCSC. This would reduce the total damage to 7. Then, for example, the president could hack the program again to make it SCSSCC, reducing the damage to 5, and so on.
To prevent the robot from getting too suspicious, the President does not want to hack too many times. What is this smallest possible number of hacks which will ensure that the program does no more than D total damage, if it is possible to do so?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line containing an integer D and a string P: the maximum total damage our shield can withstand, and the robot's program.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is either the minimum number of hacks needed to accomplish the goal, or IMPOSSIBLE if it is not possible.
Limits
1 ≤ T ≤ 100.
1 ≤ D ≤ 109.
2 ≤ length of P ≤ 30.
Every character in P is either C or S.
Time limit: 20 seconds per test set.
Memory limit: 1GB.
Test set 1 (Visible)
The robot's program contains either zero or one C characters.
Test set 2 (Hidden)
No additional restrictions to the Limits section.
Sample
Input
Output
6
1 CS
2 CS
1 SS
6 SCCSSC
2 CC
3 CSCSS
Case #1: 1
Case #2: 0
Case #3: IMPOSSIBLE
Case #4: 2
Case #5: 0
Case #6: 5
Note that the last three sample cases would not appear in test set 1.
In Sample Case #1, the President can swap the two instructions to reduce the total damage to 1, which the shield can withstand.
In Sample Case #2, the President does not need to hack the program at all, since the shield can already withstand the 2 total damage it will cause.
In Sample Case #3, the program will do more damage than the shield can withstand, and hacking will do nothing to change this. The universe is doomed.
Sample Case #4 uses the program described in the problem statement. The statement demonstrates one way to reduce the total damage to 5 using two hacks. It is not possible to reduce the damage to 6 or less by using only one hack; remember that the President can only swap adjacent instructions.
In Sample Case #5, the robot will never shoot, and so it will never do any damage. No hacking is required.
In Sample Case #6, five hacks are required. Notice that even if two hacks swap the instructions at the same two positions, they still count as separate hacks.
'''
no_tests = int(input()) #testcases
for i in range(no_tests):
#print("Test case:", i+1)
withstand_capacity_D, robot_prog = list(input().split())
withstand_capacity_D = int(withstand_capacity_D)
robot_prog = list(robot_prog)
beam_strength = 1
changes_req = 0
total_damage = 0
total_damage_test = 0
withstand_capacity_test = withstand_capacity_D
break_test = False
#print(withstand_capacity_D, robot_prog) #working
for action in robot_prog: #checking whether the default prog's total damage is < the withstand capacity
if action is 'S':
total_damage_test += beam_strength
else:
beam_strength *= 2
total_damage = total_damage_test
if total_damage < withstand_capacity_D:
print("Case #%s:"%(i+1), changes_req) #zero changes required
continue
while(total_damage > withstand_capacity_D):
try:
index_C = robot_prog.index('C') #finding the 1st occurance of 'C' in the prog
#now we need to find the 1st occurance of 'S' after index_C in order to swap with it
index_S = robot_prog[index_C+1:].index('S') + index_C+1
except ValueError:
print("Case #%s:"%(i+1), "IMPOSSIBLE")
break_test = True
if break_test == True:
break
#for situations where it is like: 'CCS'
#we need to swap 2 'adjacent' commands
if (index_S - index_C) != 1:
index_C = index_S -1
robot_prog[index_C], robot_prog[index_S] = robot_prog[index_S], robot_prog[index_C]
changes_req += 1
beam_strength = 1
total_damage = 0
for action in robot_prog: #checking for total damage is < the withstand capacity
if action is 'S':
total_damage += beam_strength
else:
beam_strength *= 2
if(total_damage < withstand_capacity_D):
break
#print(index_C, index_S)
if break_test == True:
continue
print("Case #%s:"%(i+1), changes_req) |
9ae550a7b9a00a955e9adec4e7986b9e2fcf23bb | diunko/awesome-algorithms-course | /02-cf-448c/take1.py | 516 | 3.546875 | 4 |
import sys
def merge(A,B,n):
if A.horizontal and B.horizontal:
return A+B
elif A.horizontal:
B1 = solve(B.cut(n))
if B1 < B:
return A+B1
else:
return A+B
elif B.horizonal:
A1 = solve(A.cut(n))
if A1 < A:
return A1+B
else:
return A+B
else:
# A.vertical and B.vertical
A1 = solve(A.cut(n))
B1 = solve(B.cut(n))
d = A+B - (A1+B1)
R = solve(n-d, m)
if R < A+B+m:
return R
else:
return R
def main():
pass
|
95f2e46536c7c7bba78f905f5989d225bfb828db | EricSeokgon/pythonRun | /chapter9/sec01.py | 363 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
n = input("정수 입력 : ")
if (n < 0):
print("입력 값은 0보다 작다.")
elif (n > 0):
print("입력 값은 0보다 크다.")
else:
print("입력 값은 0이다.")
money = 2000
card = -9999999
if(money>=6000 or card):
print("택시를 타라")
else:
print("걸어가라")
|
18c12566c56db74be0ffcab07bc0a51d7a532651 | inigodm/python01 | /TierraPrueba.py | 1,190 | 3.546875 | 4 | # mensaje = (90, 180, 135, 337, 135, 270, 135, 22.5)
base16 = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")
angulo = 360/16
listaHex = []
def obtenerMensaje():
mensajeRecibido = []
angulosRecibidos = input("Introduzca los ángulos recibidos separados por comas: ")
angulosSeparados = angulosRecibidos.split(",")
for angulo in angulosSeparados:
mensajeRecibido.append(float(angulo))
return mensajeRecibido
def tierra(angulos):
for caracter in angulos:
indiceBase16 = int(round(caracter / angulo, 1))
valorHexadecimal = base16[indiceBase16]
listaHex.append(valorHexadecimal)
mensajeDecodificado = ""
if len(listaHex) %2 != 0:
listaHex.append("0")
while listaHex != []:
elemento1 = listaHex.pop(0)
elemento2 = listaHex.pop(0)
caracHex = elemento1 + elemento2
mensajeDecodificado += chr(int(caracHex, 16))
print(mensajeDecodificado)
mensaje = obtenerMensaje()
if len(mensaje) % 2 != 0:
print("Número de ángulos introducido incorrecto. Tenga en cuenta que el mensaje puede ser erróneo.")
tierra(mensaje)
|
9d0a84bd06cdbdad32f536067ad74d08332b48a2 | almirgon/LabP1 | /Unidade-3/login.py | 425 | 3.59375 | 4 | #coding: utf-8
#Crispiniano
#Unidade 3: Verifica Login
email = raw_input()
senha = raw_input()
if email == 'admin@tst.ufcg.edu.br' and senha == 'TstAdminProg1':
print 'Login efetuado com sucesso!'
if email == 'admin@tst.ufcg.edu.br' and senha != 'TstAdminProg1':
print 'Senha inválida. Tente novamente.'
if email != 'admin@tst.ufcg.edu.br' and senha == 'TstAdminProg1':
print 'Email inválido.'
if email != 'admin@tst.ufcg.edu.br' and senha != 'TstAdminProg1':
print 'Login inválido.'
|
7f91ab1b4c043c8fdb949c3b843034fb71faabcd | dsoh003/date_formatter | /src/handlers/dateformat_handler.py | 3,326 | 3.59375 | 4 | import datetime
from src.handlers.code_handler import *
months = {
"jan": 1, "feb": 2, "mar": 3, "apr": 4,
"may": 5, "jun": 6, "jul": 7, "aug": 8,
"sep": 9, "oct": 10, "nov": 11, "dec": 12,
"january": 1, "february": 2, "march": 3,
"april": 4, "june": 6, "july": 5,
"august": 8, "september": 9, "october": 10,
"november": 11, "december": 12
}
def get_year(year_str: str) -> int:
sys_year = datetime.datetime.today().year
# return if year valid, if not return ridiculous time
if year_str.isnumeric():
if len(year_str) == 2:
if int(str(sys_year)[2:]) <= int(year_str):
year_str = '20' + year_str
else:
year_str = '19' + year_str
year = int(year_str)
else:
year = 9999
return year
def get_month(month_str: str) -> int:
sys_month = datetime.datetime.today().month
# return if month valid, if not return ridiculous time
if month_str.isnumeric():
month = int(month_str) if int(month_str) <= 12 else 12
else:
month = months[month_str.lower()] \
if month_str.lower() in months else 12
return month
def get_date(date_str: str) -> int:
sys_month = datetime.datetime.today().month
# return if month valid, if not return ridiculous time
if date_str.isnumeric():
date = int(date_str) if int(date_str) <= 31 else 31
else:
date = 31
return date
def date_formatter(date_str, date_format):
code = ''
req_code = date_format
req_format = '%d-%d-%d'
str_list = []
specials = '/.-_, '
start = -1
# Ensure date_str is string
date_str = str(date_str)
for i in range(len(date_str)):
if start == -1:
start = i
if date_str[i] in specials or i == len(date_str)-1:
if i == len(date_str)-1:
str_list.append(date_str[start:i+1])
else:
str_list.append(date_str[start:i])
start = -1
for i in range(len(str_list)):
code += str(len(str_list[i]))
if str_list[i].isnumeric():
code += 'N'
else:
code += 'S'
if code == req_code:
date = code_handler(
req_code,
get_date(str_list[2]),
get_month(str_list[1]),
get_year(str_list[0])
)
elif code == '2N2N4N':
if int(str_list[1]) > 12:
date = code_handler(
req_code,
get_date(str_list[1]),
get_month(str_list[0]),
get_year(str_list[2])
)
else:
date = code_handler(
req_code,
get_date(str_list[0]),
get_month(str_list[1]),
get_year(str_list[2])
)
elif code == '4N2N2N':
if int(str_list[2]) > 12:
date = code_handler(
req_code,
get_date(str_list[2]),
get_month(str_list[1]),
get_year(str_list[0])
)
else:
date = code_handler(
req_code,
get_date(str_list[1]),
get_month(str_list[2]),
get_year(str_list[0])
)
else:
date = date_str
return date
|
b5d0550ce0b3d7d84d3b3be1cd92086b2bcd28fa | tutanck/Learning | /py/step3/Personne.py | 3,351 | 3.984375 | 4 | # -*-coding:Utf-8 -*
class Personne:
"""Classe définissant une personne caractérisée par :
- son nom
- son prénom
- son âge
- son lieu de résidence"""
def __init__(self, nom, prenom):
"""Constructeur de notre classe"""
self.nom = nom
self.prenom = prenom
self.age = 33
self.lieu_residence = "Paris"
bernard = Personne("Micado", "Bernard")
print(bernard.nom, bernard.prenom, bernard.age)
class Compteur:
"""Cette classe possède un attribut de classe qui s'incrémente à chaque
fois que l'on crée un objet de ce type"""
objets_crees = 0 # Le compteur vaut 0 au départ
def __init__(self):
"""À chaque fois qu'on crée un objet, on incrémente le compteur"""
Compteur.objets_crees += 1
def combien(cls):
"""Méthode de classe affichant combien d'objets ont été créés"""
print("Jusqu'à présent, {} objets ont été créés.".format(
cls.objets_crees))
combien = classmethod(combien)
print(Compteur.objets_crees)
a = Compteur() # On crée un premier objet
print(Compteur.objets_crees)
b = Compteur()
print(Compteur.objets_crees)
Compteur.combien()
a = Compteur()
Compteur.combien()
b = Compteur()
Compteur.combien()
class TableauNoir:
"""Classe définissant une surface sur laquelle on peut écrire,
que l'on peut lire et effacer, par jeu de méthodes. L'attribut modifié
est 'surface'"""
def __init__(self):
"""Par défaut, notre surface est vide"""
self.surface = ""
def ecrire(self, message_a_ecrire):
"""Méthode permettant d'écrire sur la surface du tableau.
Si la surface n'est pas vide, on saute une ligne avant de rajouter
le message à écrire"""
if self.surface != "":
self.surface += "\n"
self.surface += message_a_ecrire
def lire(self):
"""Cette méthode se charge d'afficher, grâce à print,
la surface du tableau"""
print(self.surface)
def effacer(self):
"""Cette méthode permet d'effacer la surface du tableau"""
self.surface = ""
tab = TableauNoir()
print(tab.surface)
tab.ecrire("Coooool ! Ce sont les vacances !")
print(tab.surface)
tab.ecrire("Joyeux Noël !")
print(tab.surface)
print(tab.ecrire)
print(TableauNoir.ecrire)
print(help(TableauNoir.ecrire))
TableauNoir.ecrire(tab, "essai")
print(tab.surface)
tab = TableauNoir()
tab.lire()
tab.ecrire("Salut tout le monde.")
tab.ecrire("La forme ?")
tab.lire()
tab.effacer()
tab.lire()
class Test:
"""Une classe de test tout simplement"""
def afficher():
"""Fonction chargée d'afficher quelque chose"""
print("On affiche la même chose.")
print("peu importe les données de l'objet ou de la classe.")
afficher = staticmethod(afficher)
def __init__(self):
"""On définit dans le constructeur un unique attribut"""
self.mon_attribut = "ok"
def afficher_attribut(self):
"""Méthode affichant l'attribut 'mon_attribut'"""
print("Mon attribut est {0}.".format(self.mon_attribut))
# Créons un objet de la classe Test
un_test = Test()
un_test.afficher_attribut()
print(dir(un_test))
un_test = Test()
print(un_test.__dict__)
un_test.__dict__["mon_attribut"] = "ko"
un_test.afficher_attribut()
|
391a6ef01fecb68639427530293fdb824ef26971 | adison330/testdemo | /test024.py | 145 | 3.953125 | 4 | #! /usr/bin/env python
def sum_numbers(*args):
num = 0
for n in args:
num += n
#return num
print(sum_numbers(1,2,3,4,5,6)) |
1cb0c82b2924b3fc7e830a39c2d8e74a4c8c06bf | masaimahapa/bank-accounts | /bank.py | 2,350 | 4 | 4 | import os
class Bank:
def __init__(self, bank_name='absa'):
self.bank_name= bank_name
self.bank_accounts= {
'1':{'balance':1000, 'password': 'secret1', 'id_number':'01', 'type':'savings'},
'2':{'balance': 2000, 'password': 'secret2', 'id_number':'02', 'type':'savings'},
'3':{'balance':3000, 'password': 'secret3', 'id_number':'03', 'type':'cheque'},
'4':{'balance':4000, 'password': 'secret3', 'id_number':'03', 'type':'savings'},
}
def withdraw(self, bank_account_number, amount, secret_password):
#if the account exists, withdraw
if self.check_account(bank_account_number):
self.bank_accounts[bank_account_number]['balance']-=amount
print('Your remaining balance : ')
print(self.bank_accounts[bank_account_number].get('balance'))
def deposit(self, bank_account_number, amount):
#if account exists, deposit
if self.check_account(bank_account_number):
self.bank_accounts[bank_account_number]['balance']+=amount
print('new balance is:')
print(self.bank_accounts[bank_account_number]['balance'])
#print(self.bank_accounts)
def transfer(self, from_bank_account_number,to_bank_account_number, amount, secret_password):
#if both bank accounts exist
if self.check_account(from_bank_account_number) and self.check_account(to_bank_account_number):
if self.bank_accounts[from_bank_account_number]['balance'] >= amount:
self.bank_accounts[from_bank_account_number]['balance']-= amount
self.bank_accounts[to_bank_account_number]['balance']+= amount
print(f'sent R{amount} from account number {from_bank_account_number} to account number {to_bank_account_number}')
print(f"sender now has {self.bank_accounts[from_bank_account_number]['balance']}")
print(f"reciepient now has {self.bank_accounts[to_bank_account_number]['balance']}")
def check_account(self, acc_number):
#check if the account actually exists
if acc_number in self.bank_accounts.keys():
return True
else:
return False
|
375abdb1a7a37aaf0f81a9f6b63b359fa60bedec | dwisniewski/algorithms_implementations | /Sorting/main.py | 1,030 | 3.828125 | 4 | import argparse
from SelectionSort import SelectionSort
class AlgorithmException(Exception):
pass
def main(algorithm, input_array):
if algorithm == 'selection':
selection_sort = SelectionSort(input_array)
print(selection_sort.sort())
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(description='Implementation of sorting algotihms')
arg_parser.add_argument('-a', '--algorithm', help='Algorithm to be used. Can be: selection/', required=True)
arg_parser.add_argument('-i', '--input', help='Input array separated by single space (ex. 1 2 3 5)', required=True)
args_parsed = arg_parser.parse_args()
input_array = None
algorithm = None
try:
input_array = [int(x) for x in args_parsed.input.split(" ")]
if args_parsed.algorithm not in ['selection']:
raise AlgorithmException
main(args_parsed.algorithm, input_array)
except ValueError:
print("Wrong array. Input array should consist of integers separated by single space.")
except AlgorithmException:
print("Unsupported algorithm.")
|
8e3e66b14a08929ba71572d7b614f50a4f49ca8d | mehdi-ahmed/uni-michigan-intro-python | /week5/solution2.py | 274 | 4.125 | 4 | score = float(input("Enter Score: "))
grade = ''
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
elif score < 0.6:
grade = 'F'
else:
print('Score out of range')
print(grade)
|
385a27c03cf7b5742a9a5d1cbec167cbde76c3cc | KimTaeHyeong17/MyRepo | /Python/6_a_170602/EX94_201724447_김태형.py | 299 | 3.546875 | 4 |
def line(n1,n2,n3):
i=0
while i<n1:
print '.',
i=i+1
i=0
while i<n2:
print '*',
i=i+1
i=0
while i<n3:
print '.',
i=i+1
print
return
j=0
while j<10:
n1=9-j
n2=1+2*j
n3=9-j
line(n1,n2,n3)
j=j+1
|
d202776c61901adead6f942684c2990b579c97b6 | zhaoxinlu/leetcode-algorithms | /lintcode/02IntArray/056TwoSum.py | 653 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-03-03
算法思想: 俩数之和
"""
class Solution:
"""
@param numbers: An array of Integer
@param target: target = numbers[index1] + numbers[index2]
@return: [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, numbers, target):
# write your code here
numDict = {}
for i in range(len(numbers)):
if numbers[i] in numDict:
return [numDict[numbers[i]], i]
else:
numDict[target - numbers[i]] = i
if __name__ == '__main__':
print Solution().twoSum([2, 7, 11, 15], 18) |
9da3ca85150dac38b6531b06a875744a359917d4 | christophermoutin/MITx-6.00.1x | /Problem2/payingDebtOffInAYear.py | 1,318 | 4.34375 | 4 | """
Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card
balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month,
but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to the balance at the end of the month
(after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months.
"""
#initial definition
monthlyInterestRate = annualInterestRate/12.0
totalPaid = 0
lowestPay = 0
bal = balance
#calculation
while bal > 0:
bal = balance
lowestPay += 10
for i in range(1,13):
monthlyUnpaidBalance = bal - lowestPay
bal = monthlyUnpaidBalance + monthlyUnpaidBalance * monthlyInterestRate
print ('Lowest Payment: '+str(lowestPay))
|
2c00b4f87360a4e1655309f29ded1b3905bcf8b6 | Viiic98/holbertonschool-machine_learning | /supervised_learning/0x08-deep_cnns/2-identity_block.py | 1,619 | 3.671875 | 4 | #!/usr/bin/env python3
""" Identity block with Keras """
import tensorflow.keras as K
def identity_block(A_prev, filters):
""" builds an identity block
@A_prev: is the output from the previous layer
@filters: is a tuple or list containing F11, F3, F12, respectively:
- F11: is the number of filters in the first 1x1 convolution
- F3: is the number of filters in the 3x3 convolution
- F12: is the number of filters in the second 1x1 convolution
- All convolutions inside the block should be followed by batch
normalization along the channels axis and a rectified linear
activation (ReLU), respectively.
- All weights should use he normal initialization
Returns: the activated output of the identity block
"""
F11, F3, F12 = filters
init = K.initializers.he_normal()
layer_0 = K.layers.Conv2D(F11, (1, 1), padding='same',
kernel_initializer=init)(A_prev)
batch = K.layers.BatchNormalization()(layer_0)
act = K.layers.Activation(K.activations.relu)(batch)
layer_1 = K.layers.Conv2D(F3, (3, 3), padding='same',
kernel_initializer=init)(act)
batch = K.layers.BatchNormalization()(layer_1)
act = K.layers.Activation(K.activations.relu)(batch)
layer_2 = K.layers.Conv2D(F12, (1, 1), padding='same',
kernel_initializer=init)(act)
batch = K.layers.BatchNormalization()(layer_2)
add = K.layers.Add()([batch, A_prev])
act = K.layers.Activation(K.activations.relu)(add)
return act
|
7376ee17df40bc0f3a732d80107c5fafecaebddc | lujiaxuan0520/Python-exercise | /python课后习题/5.9.py | 361 | 3.546875 | 4 | #5.9
#!/usr/bin/python
#encoding=utf-8
def f(lst):
print('max:',max(lst))
print('sum:',sum(lst))
if __name__=='__main__':
lst=[]
while True:
x=input("Please input number(q for quit):")
if x=="q":
break
elif isinstance(eval(x),int):
lst.append(eval(x))
else:
break
f(lst)
|
2102d10de440b4a81cfb1c8f86f0b796f2af014b | zepedac6581/cti110 | /P4HW3_SumNumbers_ClaytonZepeda.py | 1,483 | 4.46875 | 4 | # A program that asks a user to input a series of positive numbers and displays
# the sum of the positive numbers. The program will terminate the series when
# the user inputs a negative number.
# 3-8-2019
# CTI-110-0003 P4HW3 - Sum of Numbers
# Clayton Zepeda
#
# set the accumulator to 0
# input = Prompt user to input a number positive number to start the sum process
# or enter a negative number to terminate the loop and display the sum.
# process = Calculate the sum of all positive numbers.
# output = Display sum of all positive numbers.
def main():
# Prompt user for a number to start accumulation loop or a negative number to
# terminate the loop.
print('Enter a positive number to add to a sum of numbers.')
print('Enter a negative number to quit and display the total sum.')
# Set the accumulator value to 0.
total = 0
# Create loop to continue until a negative number is entered. The loop will
# continue to add numbers to a total sum until a number entered is less than 0.
number = float(input('Enter a number: '))
while number > -1:
# process = Calculate the sum of all positive numbers.
total = total + number
print('\nEnter a positive number to continue ' \
'or a negative number to quit.')
number = float(input('Enter the next number: '))
# output = Display sum of all positive numbers.
print('\nThe sum of all numbers is',format(total,".2f"))
main()
|
4ec8813146cd9d76de18f9772616b8712f989409 | zzzj1233/fluent-python | /chapter2/2.1-2.2/01-列表推导式.py | 285 | 3.59375 | 4 | symbols = '$¢£¥€¤a'
# ord函数用于将一个字符串转为为unicode编码
print(ord(symbols[-1]))
unicode_list = []
for symbol in symbols:
unicode_list.append(ord(symbol))
print(unicode_list)
unicode_list2 = [ord(symbol) for symbol in symbols]
print(unicode_list2)
|
3fb6524686afedc388f8c32be4160339d226c7b6 | MateiSR/Python-Projects | /Hangman/hangman.py | 1,649 | 3.65625 | 4 | import random
def cls():
print("\n" * 100)
words = ['red', 'black', 'blue', 'violet', 'white', 'orange', 'yellow']
x = random.randint(0, 6)
chosen_word = words[x]
blanks = []
global drawings
drawings = ['''
-----
| |
|
|
|
|
*********''', '''
-----
| |
O |
|
|
|
*********''', '''
-----
| |
O |
| |
| |
|
|
*********''', '''
-----
| |
O |
/| |
| |
|
|
*********''', '''
-----
| |
O |
/|\ |
| |
|
|
*********''', '''
-----
| |
O |
/|\ |
| |
/ |
|
*********''', '''
-----
| |
O |
/|\ |
| |
/ \ |
|
*********''']
for i in range(len(chosen_word)):
blanks.append('_')
turns = 6
wrong = 0
while turns > 0:
cls()
print('DEBUG: Chosen word: ' + chosen_word)
print(str(turns) + ' turns left')
print(drawings[wrong])
print(' '.join(blanks))
correct = False
guess = input('Guess a character: ')
while len(guess) != 1:
guess = input('Guess a character: ')
for j in range(len(chosen_word)):
if chosen_word[j] == guess:
blanks[j] = guess
correct = True
else:
pass
if correct == False:
turns -= 1
wrong += 1
if turns > 0:
pass
elif turns == 0:
print(drawings[6])
print('You didn\'t guess the word: ' + chosen_word)
blanks_string = ''.join(blanks)
if blanks_string == chosen_word:
print('You found the word: ' + chosen_word)
break
|
65aad559816a6ea893ad98e339e5f078183b8578 | arunshankarsam22/Python | /equalindexstringssorted.py | 450 | 3.71875 | 4 | '''Given a number n followed by n numbers. Find the numbers which are equal to their index value and print them in sorted order. If no such numbers are present print '-1' without quotes.
Input Size : 1 <= n <= 100000
Sample Testcases :
INPUT
6
6 7 3 3 4 5
OUTPUT
3 4 5'''
a=int(input())
b=input()
c=b.split()
d=[]
for i in range(0,a):
if(str(i)==c[i]):
d.append(c[i])
if(len(d)!=0):
print(' '.join(sorted(d)))
else:
print (-1)
|
10ddf4036d154927c50ce0b2643f207224522c97 | romulo24/Lenguaje-Python | /booleanos.py | 748 | 4.125 | 4 | # Programacion con Python
# Autor: Estudiante Torres LLivipuma Romulo Jesus <rtorresll@est.ups.edu.ec>
# Universidad Politecnica Salesiana
#Operaciones logicas
#Booleano
#Relacionales
print(10 >= 9)
print("otras palabras" != "otras palabras")
print("test" in "testing")
a = 'testing'
print('test' in a)
#EJERCICIO
a=5
b=7
c=8
print(a>b)
print(a<b)
print(a+b<c)
x= (a + b > c) | (a + b < c)
y=(a + b > c) & (a + b < c)
print(x,y)
#Comparaciones
#Mayor que; < Menor que
3 > 2
#True
3 < 2
#False
#>= Mayor o igual que; <= Menor o igual que
2 >= 1 + 1
#True
4 - 2 <= 1
#False
#== Igual que; != Distinto de
2 == 1 + 1
#Tue
6 / 2 != 3
#False
4 == 3 + 1 > 2
#True
2 != 1 + 1 > 0
#False
4 == 3 + 1 > 2
#True
2 != 1 + 1 > 0
#False
|
74c58ec7f94bba57dfd65304602c3588f35536c7 | sunilkum84/golang-practice-2 | /revisiting_ctci/chapter1/StringRotation_1_9.py | 593 | 4.15625 | 4 | import unittest
def IsRotation(a,b):
""" take strings a and b as an input and see if they are rotations
of one another, returns boolean """
rotation = 0
rotate_max = len(a)
while rotation < rotate_max:
rotation += 1
if a == b:
return True
a = a[-1] + a[:-1]
return False
class TestRotate(unittest.TestCase):
def test_IsRotation(self):
self.assertTrue(IsRotation('test','ttes'))
self.assertTrue(IsRotation('test','estt'))
self.assertFalse(IsRotation('test','sett'))
self.assertFalse(IsRotation('test','nottest'))
if __name__ == '__main__':
unittest.main() |
7f05a492358dc2e59dcfb27ecdadcd4e165b7551 | alkaitz/general-programming | /tunnel/tunnel.py | 2,939 | 3.59375 | 4 | '''
Created on Aug 1, 2017
@author: alkaitz
'''
import math
'''
There is a 2D tunnel with width w and a set of radars (x, y, radius) placed inside of it.
Check if it is possible to cross from one side to the other without raising any alarm
'''
def distance(position1, position2):
origX, origY = position1
destX, destY = position2
return math.sqrt(abs(origX - destX)**2 + abs(origY - destY)**2)
def triggersRadar(position, radar):
radarPosition, radiusSensor = radar
return distance(position, radarPosition) <= radiusSensor
def doRadarsCollide(radar1, radar2):
radarPosition1, radiusSensor1 = radar1
radarPosition2, radiusSensor2 = radar2
return distance(radarPosition1, radarPosition2) < radiusSensor1 + radiusSensor2
def doesRadarTouchBorder(radar, width):
radarPosition, radiusSensor = radar
radarX, _ = radarPosition
borderPosition = (radarX, width)
return distance(radarPosition, borderPosition) < radiusSensor
def createContiguousGroups(radars):
def doGroupsCollide(group1, group2):
return any(True for r1 in group1 for r2 in group2 if doRadarsCollide(r1, r2))
groups = map(lambda x: {x}, radars)
result = []
while groups:
group = groups.pop()
for other in groups:
if doGroupsCollide(group, other):
groups.remove(other)
group = group.union(other)
result.append(group)
return result
def canCrossTunnel(width, radars):
groups = createContiguousGroups(radars)
for group in groups:
# Verify if the group crosses both borders
crossesUpper, crossesDown = False, False
for radar in group:
if doesRadarTouchBorder(radar, 0):
crossesDown = True
if doesRadarTouchBorder(radar, width):
crossesUpper = True
if crossesUpper and crossesDown:
return False
return True
if __name__ == '__main__':
def testRadar():
assert(not triggersRadar((0,0), ((1,1),1)))
assert(triggersRadar((0,0), ((2,0),2)))
def testGroups():
collidingGroup = [
((0,0), 2),
((0,2), 1)
]
apartGroup = [
((0,0), 1),
((0,3), 1)
]
mixedGroup = [
((0,0), 3),
((2,2), 1),
((10,0), 2)
]
assert(len(createContiguousGroups(collidingGroup)) == 1)
assert(len(createContiguousGroups(apartGroup)) == 2)
assert(len(createContiguousGroups(mixedGroup)) == 2)
def testTunnel():
assert(canCrossTunnel(10, [((1,1), 5)]))
assert(not canCrossTunnel(2, [((1,1), 5)]))
assert(canCrossTunnel(100, [((1,1), 5), ((3,5), 20), ((50,50), 5)]))
testRadar()
testGroups()
testTunnel()
print "Successful" |
3c9803305180de073fa7874adf3f2f885df57ebf | lalapapauhuh/Python | /CursoEmVideo/pythonProject/ex039.py | 491 | 4.125 | 4 | #alistamento
from datetime import date
ano = int(input('Digite o ano do seu nascimento: '))
atual = date.today().year
idade = atual - ano
if idade > 18:
print('Já passaram {} anos da data do seu alistamento'.format(idade - 18))
print('Seu alistamento foi em {}'.format(ano + 18))
elif idade < 18:
print('Ainda faltam {} anos para você se alistar'.format(18 - idade))
print('Seu alistamento sera em {}'.format(ano + 18))
else:
print('Você deve se alistar este ano!')
|
dbad83e4776b51055e4f634dccb2953823bbcad9 | mohanalearncoding/Leetcodepython | /validpalindrome.py | 198 | 3.828125 | 4 | def isPalindrome( s:str):
s=s.lower()
st=""
for i in s:
if i.isalnum():
st+=i
print(st,st[::-1])
return st==st[::-1]
print(isPalindrome("race a car")) |
b3a9a4c0a03b7b7b3986d099e03909e08309e47d | JoaoMisutaniAlves/URI_problems | /beginner/1017.py | 118 | 3.734375 | 4 | # -*- coding: utf-8 -*-
time = int(input())
speed = int(input())
liters = ( time * speed ) / 12
print ("%.3f"%liters) |
1a0f871362748f146e2e52a09252b93c73931a4d | prakhar154/face_recognition | /faceDetectiom.py | 1,838 | 3.625 | 4 | # 1. Read and show video stream, capture images
# 2. Detect faces and show bounding box
# 3. Flatten the largest face image and store in numpy array
# 4. Repeat the above for multile people to generate trainig data
import numpy as np
import cv2
#init camera
cap = cv2.VideoCapture(0)
#face detection
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
eyes_cascade = cv2.CascadeClassifier("frontalEyes35x16.xml")
skip = 0
face_data = []
dataset_path = './data/'
file_name = input("enter name ")
while True:
ret, frame = cap.read()
if ret==False:
continue
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
faces = sorted(faces, key = lambda f:f[2]*f[3] )
#pick last face because it the largest face acc to f[2]*f[3]
for face in faces[-1:]:
x, w, y, h = face
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
#eyes detection
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eyes_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+eh,ey+ew),(0,255,0),2)
# Extrat region of interest
offset = 10
face_section = frame[y-offset: y+h+offset, x-offset:x+w+offset]
face_section = cv2.resize(face_section, (100, 100))
skip+=1
if skip%10==0:
face_data.append(face_section)
print(len(face_data))
cv2.imshow("video frame", frame)
key_pressed = cv2.waitKey(1)&0xFF
if key_pressed==ord('q'):
break
#Convert face list array into numpy array
face_data = np.asarray(face_data)
face_data = face_data.reshape((face_data.shape[0], -1))
print(face_data.shape)
#save data into file system
np.save(dataset_path+file_name+'.npy',face_data)
print("data sucessfully save at" + dataset_path+file_name+'.npy')
cap.release()
cv2.destroyAllWindows() |
5c9171b965eef696543a928226ca8626aa3c6a01 | andreifortunato/pythonTest | /numerosAleatorios.py | 223 | 3.796875 | 4 | import random
random.seed(1)
#força o python a selecionar o numero escolhido
numero = random.randint(0,10)
#escolhe um numero aleatorio entre 0 e 10
numero = random.choice()
#escolhe um dos valores
print(numero) |
2142aa70260c8d78210a9e26b2142b62a9153b47 | YQ-7/code-interview-guide | /c2_linked_list/get_intersect_node.py | 5,518 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
题目:
判断两个链表是否相交,若相交则并返回第一个相交的节点
"""
import unittest
from utils.linked_list import Node
def get_loop_node(head):
"""
判断一个链表是否有环,如果有,则返回第一个进入环的节点,没有则返回null。
"""
if head is None or head.next is None or head.next.next is None:
return None
# 设置一个慢指针slow(每次移动1步)和一个快指针fast(每次移动2步)
# 如果链表没有环,fast指针一定先移动到Node
slow = head.next
fast = head.next.next
while slow != fast:
if fast.next is None or fast.next.next is None:
return None
slow = slow.next
fast = fast.next.next
# 如果有环,fast和slow会在某个位置相遇
# 相遇后,调制移动方式:fast指向链表头,fast和slow每次移动1步
# fast指针和slow指针一定会再次相遇,并且在第一个入环的节点处相遇
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return fast
def get_cross_no_loop(head1, head2):
"""
判断两个无环链表是否相交,相交则返回第一个相交节点,不相交则返回null。
"""
# 分别遍历到链表尾节点,记录链表长度
if head1 is None or head2 is None:
return None
len_1 = 1
cur1 = head1
while cur1.next is not None:
len_1 += 1
cur1 = cur1.next
len_2 = 1
cur2 = head2
while cur2.next is not None:
len_2 += 1
cur2 = cur2.next
# 尾节点是同一个节点,则两链表相交
if cur1 != cur2:
return None
# 先将较长的链表移动|len1 - len2|的长度
len_sub = len_1 - len_2
long_cur = head1 if len_sub > 0 else head2
short_cur = head2 if long_cur == head1 else head1
len_sub = abs(len_sub)
while len_sub > 0:
len_sub -= 1
long_cur = long_cur.next
# 两链表开始同时遍历,第一个相同的节点即第一个交点
while long_cur != short_cur:
long_cur = long_cur.next
short_cur = short_cur.next
return long_cur
def both_loop(head1, loop1, head2, loop2):
"""
判断两个有环链表是否相交,相交则返回第一个相交节点,不相交则返回null。
"""
if loop1 == loop2:
len_1 = 0
cur1 = head1
while cur1 != loop1:
len_1 += 1
cur1 = cur1.next
len_2 = 0
cur2 = head2
while cur2 != loop2:
len_2 += 1
cur2 = cur2.next
# 尾节点是同一个节点,则两链表相交
if cur1 != cur2:
return None
# 先将较长的链表移动|len1 - len2|的长度
len_sub = len_1 - len_2
long_cur = head1 if len_sub > 0 else head2
short_cur = head2 if long_cur == head1 else head1
len_sub = abs(len_sub)
while len_sub > 0:
len_sub -= 1
long_cur = long_cur.next
# 两链表开始同时遍历,第一个相同的节点即第一个交点
while long_cur != short_cur:
long_cur = long_cur.next
short_cur = short_cur.next
return long_cur
else:
cur_1 = loop1.next
while cur_1 != loop1:
if cur_1 == loop2:
return loop1
cur_1 = cur_1.next
return None
def get_intersect_node(head1, head2):
if head1 is None or head2 is None:
return None
loop1 = get_loop_node(head1)
loop2 = get_loop_node(head2)
if loop1 is None and loop2 is None:
return get_cross_no_loop(head1, head2)
if loop1 is not None and loop2 is not None:
return both_loop(head1, head2, loop1, loop2)
return None
class MyTestCase(unittest.TestCase):
def test_get_loop_node(self):
head = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
head.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
self.assertIsNone(get_loop_node(head))
node_5.next = node_3
self.assertTrue(3, get_loop_node(head).data)
def test_get_cross_no_loop(self):
head1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
head1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
head2 = Node(11)
node2_2 = Node(12)
head2.next = node2_2
self.assertIsNone(get_cross_no_loop(head1, head2))
self.assertIsNone(get_intersect_node(head1, head2))
node2_2.next = node_3
self.assertEqual(3, get_cross_no_loop(head1, head2).data)
self.assertEqual(3, get_intersect_node(head1, head2).data)
def test_get_cross_no_loop(self):
head1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
head1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
node_5.next = node_3
head2 = Node(11)
node2_2 = Node(12)
node2_3 = Node(13)
head2.next = node2_2
node2_2.next = node2_3
node2_3.next = node_2
self.assertTrue(2, get_intersect_node(head1, head2).data)
if __name__ == '__main__':
unittest.main()
|
5da5aeac0c21716b7111ed507601e2701cab07d8 | ray-abel12/python | /bmiCaculator.py | 196 | 4.0625 | 4 | weight = input('Enter weight in kilograms ')
height = input('Enter height in meters ')
weight = int(weight)
height = int(height)
bmi = weight/height * height
print(f'the body mass index is {bmi}') |
899fe29a2b4f4de977f2ea90ba619fa8c00dad62 | zjswhhh/leetcode_python | /307_sqrt_decomposition.py | 1,363 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
class NumArray(object):
def __init__(self, nums):
"""
l: size of each block
n: number of block
s: block sum
"""
size = len(nums)
self.item = nums
if not size == 0:
self.l = int(math.sqrt(size))
n = int(math.ceil(size/self.l))
self.s = [0 for i in range(n+1)]
for i in range(size):
self.s[i//self.l] += nums[i]
def update(self, i, val):
self.s[i//self.l] = self.s[i//self.l] - self.item[i] + val
self.item[i] = val
def sumRange(self, i, j):
sum = 0
start = i//self.l
end = j//self.l
if start == end:
for k in range(i, j+1):
sum += self.item[k]
else:
for k in range(i, (start+1)*self.l):
sum += self.item[k]
print(self.item[k], 1)
for k in range(end*self.l, j+1):
sum += self.item[k]
print(self.item[k], 2)
for k in range(start+1, end):
sum += self.s[k]
print(self.s[k], 3)
return sum
"""
test case:
te = NumArray([9, -8])
te.update(0,3)
print(te.sumRange(1, 1))
print(te.sumRange(0, 1))
te.update(1, -3)
print(te.sumRange(0, 1))
"""
|
da3e849ccd46b973615acedb745cb4cf5694ea00 | liamcarroll/python-programming-2 | /Lab_2.2/readnum_022.py | 308 | 3.5625 | 4 | #!/usr/bin/env python3
import sys
def main():
for line in sys.stdin:
try:
n = int(line.strip())
break
except ValueError:
print('{} is not a number'.format(line.strip()))
print('Thank you for {}'.format(n))
if __name__ == '__main__':
main()
|
41a150d93a1496a935256ae2afe84c054ff0c59f | kamyu104/LeetCode-Solutions | /Python/strobogrammatic-number-ii.py | 1,153 | 3.5 | 4 | # Time: O(n * 5^(n/2))
# Space: O(n)
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
result = ['0', '1', '8'] if n%2 else ['']
for i in xrange(n%2, n, 2):
result = [a + num + b for a, b in lookup.iteritems() if i != n-2 or a != '0' for num in result]
return result
# Time: O(n * 5^(n/2))
# Space: O(n)
class Solution2(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
def findStrobogrammaticRecu(n, k):
if k == 0:
return ['']
elif k == 1:
return ['0', '1', '8']
result = []
for num in findStrobogrammaticRecu(n, k - 2):
for key, val in lookup.iteritems():
if n != k or key != '0':
result.append(key + num + val)
return result
return findStrobogrammaticRecu(n, n)
|
47d37d54cf8ce020c3b7ab285a6415423f618903 | Jainam-Dharod/Open-Source-Workshop | /length.py | 730 | 3.59375 | 4 | import argparse
##fork request
parser = argparse.ArgumentParser()
parser.add_argument('--inch-to-cm', type=float, dest="inch_to_cm")
parser.add_argument('--cm-to-inch', type=float, dest="cm_to_inch")
args = parser.parse_args()
def main():
inch_to_cm_helper()
cm_to_inch_helper()
# Helper functions to check if the arg exists or not
def inch_to_cm_helper():
inch = args.inch_to_cm
if inch:
inch_to_cm(inch)
def cm_to_inch_helper():
cm = args.cm_to_inch
if cm:
cm_to_inch(cm)
# Converter functions
def inch_to_cm(inch):
print(f'{inch} inch in cm is: {inch*2.54} cm')
def cm_to_inch(cm):
print(f'{cm} cm in inch is: {cm/2.54} inch')
if __name__ == "__main__":
main()
|
285f5429bc9d8ce3beb4064b9cfbdb7cbcdae9dc | naffi192123/Python_Programming_CDAC | /Day1/6-type_conversion.py | 212 | 3.671875 | 4 | # print type of numbers
num = 2
floatt = 2.76
exp = 2e5
char = "r"
string = "my name"
he = 34
print(str(num))
print(int(floatt))
print(int(exp))
print(ord(char))
print(hex(he))
print(oct(he))
print(complex(num))
|
caa843f399e7ae3115fa5517e054f9b1d6685b40 | von/scripts | /fileurl.py | 1,058 | 3.53125 | 4 | #!/usr/bin/env python3
"""Given a path to a file, return a URL for that file."""
import argparse
import os.path
import sys
import urllib.request, urllib.parse, urllib.error, urllib.parse
def main(argv=None):
# Do argv default this way, as doing it in the functional
# declaration sets it at compile time.
if argv is None:
argv = sys.argv
# Argument parsing
parser = argparse.ArgumentParser(
description=__doc__, # printed with -h/--help
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
# To have --help print defaults with trade-off it changes
# formatting, use: ArgumentDefaultsHelpFormatter
)
parser.add_argument('path', metavar='path', type=str, nargs=1,
help='path for file')
args = parser.parse_args()
path = os.path.abspath(args.path[0])
print(urllib.parse.urlunsplit(("file", "", urllib.request.pathname2url(path), "", "")))
return(0)
if __name__ == "__main__":
sys.exit(main())
|
665c4b0216c736c075f43cb5ada82d381b58d9e6 | ChiragVaghela10/programming_practice | /Practice_in_Python/Hacker_Earth/tom_jerry.py | 1,386 | 3.53125 | 4 | # Tom and Jerry are wonderful characters. They are always running and make us laugh.
#
# Right now, they are in a grid of houses and Jerry is running away from Tom. The grid of houses is represented as 0 and 1, where 0 # means that Jerry can enter the house, and 1 means Jerry can't. Jerry can only move horizontally or vertically. Also, Jerry # doesn't enter the same house more than once.
# Jerry started running from the house at () which is the top-left house in the grid and have to reach () which the bottom-right # house in the grid. You have find the number of ways in which Jerry can reach the destination house where he can be safe.
# Input Format
# First line is an integer N ( ), which is the size of the grid. N lines follow, each containing N space separated numbers which # are either '0' or '1'.
# Output format
# Print a single line showing the number of ways in which Jerry can reach from () to ().
# SAMPLE INPUT SAMPLE OUTPUT
# 9 8512
#0 0 0 0 0 0 0 0 0
#0 1 0 1 0 1 0 1 0
#0 0 0 0 0 0 0 0 0
#0 1 0 1 0 1 0 1 0
#0 0 0 0 0 0 0 0 0
#0 1 0 1 0 1 0 1 0
#0 0 0 0 0 0 0 0 0
#0 1 0 1 0 1 0 1 0
#0 0 0 0 0 0 0 0 0
n = int(input())
g = [list(map(int, input().split())) for i in range(n)]
arr = [[0] * n]* n
for i in arr:
i[0] = 1
arr[0] = [1] * n
# print('g:', g, '\n', 'arr:', arr)
|
35fcbc6c1740c4ff9775ab729875820ef2068f35 | Elbadri0/mundiapolis-ml | /0x06-keras/7-train.py | 2,408 | 3.640625 | 4 | #!/usr/bin/env python3
"""Script to train a model using keras"""
import tensorflow.keras as K
def train_model(network, data, labels, batch_size, epochs,
validation_data=None, early_stopping=False,
patience=0, learning_rate_decay=False,
alpha=0.1, decay_rate=1,
verbose=True, shuffle=False):
"""
Function to train a model using keras and LRD
Args:
network: model to train
data: numpy.ndarray of shape (m, nx) containing the input data
labels: one-hot numpy.ndarray of shape (m, classes) containing
the labels of data
batch_size: size of the batch used for mini-batch gradient descent
epochs: number of passes through data for mini-batch gradient descent
validation_data: data to validate the model with, if not None
early_stopping: boolean that indicates whether early stopping
should be used
patience: patience used for early stopping
learning_rate_decay: boolean that indicates whether learning rate decay
should be used
alpha: initial learning rate
decay_rate: decay rate
verbose: boolean that determines if output should be printed during
training
shuffle: boolean that determines whether to shuffle the batches every
epoch.
Returns: History object generated after training the model
"""
def scheduler(epoch):
"""
Function o get the learning reate of each epoch
Args:
epoch: umber of passes through data for mini-batch gradient descent
Returns:
"""
return alpha / (1 + decay_rate * epoch)
custom_callbacks = []
ES = K.callbacks.EarlyStopping(monitor='val_loss', mode='min',
patience=patience)
LRD = K.callbacks.LearningRateScheduler(scheduler, verbose=1)
if validation_data and early_stopping:
custom_callbacks.append(ES)
if validation_data and learning_rate_decay:
custom_callbacks.append(LRD)
history = network.fit(x=data, y=labels, batch_size=batch_size,
epochs=epochs, validation_data=validation_data,
callbacks=custom_callbacks,
verbose=verbose, shuffle=shuffle)
return history
|
05de75c320a3dccce2596bdce9776e69db1f7bd8 | AnushreeBagchi/Learning-Data-Structures-and-Algorithm-Python | /staircase.py | 1,024 | 4.125 | 4 | def staircase(num):
if num<=0:
return
if num ==1:
return 1
elif num == 2:
return 2
elif num == 3:
return 4
return staircase(num-1)+staircase(num-2)+staircase(num-3)
# caching the output to get faster implementation of the function
def staircase_with_caching(num):
num_dict = dict({})
return staircase_faster(num,num_dict)
def staircase_faster(num,num_dict ):
if num<=0:
return
if num ==1:
output = 1
elif num == 2:
output = 2
elif num == 3:
output = 4
else:
if (num-1) in num_dict:
n1 = num_dict[num-1]
else:
n1 = staircase(num-1)
if (num-2) in num_dict:
n2 = num_dict[num-2]
else:
n2 = staircase(num-2)
if (num-3) in num_dict:
n3 = num_dict[num-3]
else:
n3 = staircase(num-3)
output = n1+n2+n3
num_dict[num] = output
return output
print(staircase_with_caching(3))
|
8975d257bd0cad04307c83257f14f7c869e7c886 | Ursinus-IDS301-S2020/HW4b_EpidemicSpreading | /COVID19.py | 6,351 | 3.90625 | 4 | """
Programmer: Chris Tralie
Purpose: To create a simple Monte Carlo simulation of a
spreading epidemic, using only arrays, methods, and loops. A bunch
of people are placed uniformly at random on a square grid, and a single
one of them starts off infected. Points that are moving then take
a random walk
"""
from vpython import *
import numpy as np
import matplotlib.pyplot as plt
import time
INFECTED = 0
UNINFECTED = 1
RECOVERED = 2
STATE_COLORS = [vector(1, 0, 0), vector(0, 0.5, 1), vector(1, 0, 1)]
def update_infections(X, states, time_sick, recovery_time, dist):
"""
Parameters
----------
X: ndarray(num_people, 2)
An array of the positions of each person, with the x coordinate in the
first column and the coordinate in the second column
states: ndarray(num_people)
A 1D array of all of the states
time_sick: ndarray(num_people)
The number of hours each person has been sick
recovery_time: int
The number of hours it takes an infected person to recover
dist: float
The distance an uninfected person has to be to an infected
person in both the x and y coordinate to infect them
"""
num_people = X.shape[0]
## TODO: Fill this in
# Loop through the people, and apply the following rules:
# 1) If a person is UNINFECTED but is within "dist" in its x coordinate
# and its y coordinate of an INFECTED person, their state changes to
# INFECTED
# 2) If a person is INFECTED, add one hour to the amount of time
# that they have been infected in the timeSick array. If they
# have been infected for recovery_time amount of time, then change
# their state to RECOVERED
def draw_points(cylinders, T, X, states, hour, res):
"""
Parameters
----------
cylinders: list of vpython clinder
Cylinder markers for each person
T: vpython text
Text that's used to display the day
X: ndarray(num_people, 2)
An array of the positions of each person, with the x coordinate in the
first column and the coordinate in the second column
states: ndarray(num_people)
A 1D array of all of the states
hour: int
The hour it is in the simulation
res: int
The size of the grid
"""
for i in range(X.shape[0]):
cylinders[i].pos = vector(X[i, 0]-res/2, 0, X[i, 1]-res/2)
cylinders[i].color = STATE_COLORS[states[i]]
T.text = "\n\nDay %i"%(hour/24)
def do_random_walks(X, is_moving, res):
"""
Do a random walk on each point that's moving
Parameters
----------
X: ndarray(N, 2)
An array of locations
is_moving: ndarray(N)
An array of booleans indicating whether each person is moving or not
res: int
The size of the grid
"""
choices = np.random.randint(0, 4, X.shape[0])
X[(choices == 0)*(is_moving == 1), 0] += 1 # Right
X[(choices == 1)*(is_moving == 1), 0] -= 1 # Left
X[(choices == 2)*(is_moving == 1), 1] += 1 # Up
X[(choices == 3)*(is_moving == 1), 1] -= 1 # Down
# Keep things in the square
X[X < 0] = 0
X[X >= res] = res
def simulate_pandemic(num_people, num_moving, num_hours, res, recovery_time, draw):
"""
Parameters
----------
num_people: int
The number of people in the simulation
num_moving: int
The number of people who are moving
num_hours: int
The total number of hours in the simulation
res: int
The size of the grid
recovery_time: int
The number of hours it takes an infected person to recover
draw: boolean
If true, show the animation in vpython. If false, simply
run the animation and display plots of the people in different
states over time
"""
# Step 1: Setup initial positions of all people, initialize
# the amount of time they've all been sick to zero, and set
# them all to not be sick by default
# Also set the first "num_moving" people to be moving, and the
# rest to be stationary
X = np.random.randint(0, res, (num_people, 2))
states = np.ones(num_people, dtype=int)*UNINFECTED
states[0] = INFECTED # Setup the first infection
time_sick = np.zeros(num_people) # The time a person has been sick
is_moving = np.ones(num_people)
if num_moving < num_people:
is_moving[num_moving::] = 0
#Arrays for holding the results
infected_count = np.zeros(num_hours)
uninfected_count = np.zeros(num_hours)
recovered_count = np.zeros(num_hours)
# Step 2: Setup vpython for drawing
cylinders = []
T = None
if draw:
scene = canvas(title='Epidemic Simulation %i People %i Moving'%(num_people, num_moving),
width=600, height=600)
for i in range(num_people):
c = cylinder(pos=vector(X[i, 0]-res/2, 0, X[i, 1]-res/2), axis=vector(0, 8, 0), radius=0.5, color=STATE_COLORS[states[i]])
cylinders.append(c)
scene.camera.pos = vector(-res*0.07, res*0.84, res*0.54)
scene.camera.axis = -scene.camera.pos
# This text will store the elapsed time
T = wtext(text='')
# Step 3: Run the Monte Carlo Simulation
for hour in range(num_hours):
if draw:
draw_points(cylinders, T, X, states, hour, res)
time.sleep(1.0/24)
do_random_walks(X, is_moving, res)
update_infections(X, states, time_sick, recovery_time, 2)
# Update counts for this hour
infected_count[hour] = np.sum(states == INFECTED)
uninfected_count[hour] = np.sum(states == UNINFECTED)
recovered_count[hour] = np.sum(states == RECOVERED)
# Plot the results
plt.figure(figsize=(8, 5))
days = np.arange(num_hours)/24
plt.plot(days, uninfected_count)
plt.plot(days, infected_count)
plt.plot(days, recovered_count)
plt.legend(["Uninfected", "Infected", "Recovered"])
plt.xlabel("Day")
plt.ylabel("Number of People")
plt.title("Epidemic Simulation %i People, %.3g%s Moving, %i x %i Grid"%(num_people, num_moving*100.0/num_people, "%", res, res))
plt.show()
num_people = 1000
num_moving = num_people
num_hours = 24*120
res = 200
recovery_time = 24*14
draw = True
simulate_pandemic(num_people, num_moving, num_hours, res, recovery_time, draw) |
c280a6249447123882ec53a0a0fbf859595c92a9 | ddh/leetcode | /python3/299-bulls-and-cows.py | 2,584 | 3.859375 | 4 | #
# @lc app=leetcode id=299 lang=python3
#
# [299] Bulls and Cows
#
# https://leetcode.com/problems/bulls-and-cows/description/
#
# algorithms
# Easy (42.14%)
# Likes: 671
# Dislikes: 810
# Total Accepted: 159.7K
# Total Submissions: 376.6K
# Testcase Example: '"1807"\n"7810"'
#
# You are playing the following Bulls and Cows game with your friend: You write
# down a number and ask your friend to guess what the number is. Each time your
# friend makes a guess, you provide a hint that indicates how many digits in
# said guess match your secret number exactly in both digit and position
# (called "bulls") and how many digits match the secret number but locate in
# the wrong position (called "cows"). Your friend will use successive guesses
# and hints to eventually derive the secret number.
#
# Write a function to return a hint according to the secret number and friend's
# guess, use A to indicate the bulls and B to indicate the cows.
#
# Please note that both secret number and friend's guess may contain duplicate
# digits.
#
# Example 1:
#
#
# Input: secret = "1807", guess = "7810"
#
# Output: "1A3B"
#
# Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
#
# Example 2:
#
#
# Input: secret = "1123", guess = "0111"
#
# Output: "1A1B"
#
# Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a
# cow.
#
# Note: You may assume that the secret number and your friend's guess only
# contain digits, and their lengths are always equal.
#
# Idea: We'll count the frequency of letters first from the secret.
# We then keep track of num bulls, cows. We iterate through the guessed number.
# Each time we
# @lc code=start
from collections import Counter
class Solution:
def getHint(self, secret: str, guess: str) -> str:
secret = str(secret)
guess = str(guess)
bulls, cows = 0, 0
letter_frequency = Counter(secret)
for i, num in enumerate(guess):
if num in letter_frequency:
if num == secret[i]:
bulls += 1
if letter_frequency[num] <= 0: cows -= 1 # This conditional is tricky unless you work out an example
else:
if letter_frequency[num] > 0: cows += 1 # This conditional is tricky unless you work out an example
letter_frequency[num] -= 1
return str(bulls) + "A" + str(cows) + "B"
# @lc code=end
print(Solution().getHint("1807", "7810")) # 1A3B
print(Solution().getHint("1123", "0111")) # 1A1B
print(Solution().getHint("1122", "1222")) # 3A0B
print(Solution().getHint("6244988279", "3819888600")) # 2A2B |
a87bc01148e81e0c4bebfb38507cc1f2782f6e61 | KacperLech/lechanski | /1_podstaw.py | 1,312 | 3.921875 | 4 | print("cdv")
print (2)
print ('test')
#potęga
pow=2**10
print(pow)
text="CDV"
print(text * 2)
#pobieranie danych z klawiatury
name=input()
print(name)
print("Twoje imię:"+name)
surname=input("Podaj swoje nazwisko: ")
print("Imie: " + name + ", nazwisko: " + surname)
lengthSurname=len(surname) #<class 'str'>
print(type(surname)) #<class 'int'>
print(type(lengthSurname))
lengthSurname = str(lengthSurname) #rzutowanie
print("Długość nazwiska: " + lengthSurname)
'''
Użytkownik podaje z klawiatury
imiona i nazwiska oraz wiek
wyświetl w formacie:
Imię i nazwisko:.........., wiek:.....
'''
print("ZADANIE")
imie=input("Podaj imie: ")
nazwisko=input("Podaj nazwisko: ")
wiek=input("Podaj wiek: ")
print("Imię i nazwisko: " + imie + " " + nazwisko + ", wiek: " + wiek)
print("\nPodaj swój wiek: ", end="")
age=input()
surname="Kowalski"
firstLetter=surname[0]
print(firstLetter)
lastLetter = surname[len(surname) - 1 ]
print(lastLetter)
#konwersja
x="5"
print(type(x)) #str
x=int(x)
print(type(x)) #int
y=5
print(type(y))
#y = y / 2
y /= 2 #y=y / 2
print(type(y)) #float
print(y)
surname="Kowalski"
print(surname[0]) #K
print(surname[0:3]) #Kow
print(surname[-2]) #k
print(surname[-2:]) #ki
print(surname[:]) #Kowalski
print(surname[:-2]) #Kowals
print(surname[:-2:2]) #kwl
#komentarz
|
a6f4620f2a97302fa271dfe3536487f0bfc12d76 | aileentran/practice | /productexceptself3.py | 649 | 3.703125 | 4 | """
Leetcode - 238. Product of Array Except Self
input: list of nums
output: list of nums - product of all other eles except @ that index
Thoughts - solving w/ 1 result array = O(1) time
make an empty result array
set right variable to keep track of products
loop using forward range
append left * right into results
"""
def productExceptSelf(nums):
res = [1] * len(nums)
for i in range(1, len(nums)):
res[i] = res[i - 1] * nums[i - 1]
right = 1
for i in reversed(range(len(nums))):
res[i] = res[i] * right
right *= nums[i]
return res
nums = [1,2,3,4]
# [24,12,8,6]
print(productExceptSelf(nums))
|
e3497579f61e0a0674e2e496259f60217f7494d6 | zHigor33/ListasDeExerciciosPython202 | /Estrutura de Repetição/L3E19.py | 772 | 3.96875 | 4 | numberOfNumbers = int(input("Quantos numeros deseja informar: "))
lowestNumber = 0
higherNumber = 0
total = 0
for i in range(numberOfNumbers):
loop = True
while loop:
numbers = float(input("Informe o número: "))
if numbers >= 0 and numbers <= 1000:
loop = False
else:
print("O número informado passa de 1000 ou é menor que 0")
if i == 0:
lowestNumber = numbers
higherNumber = numbers
if lowestNumber > numbers:
lowestNumber = numbers
if higherNumber < numbers:
higherNumber = numbers
total = total + numbers
print("O menor número é "+str(lowestNumber)+"\nO maior número é "+str(higherNumber)+"\nA soma dos números é "+str(total))
|
ba27e27bfc2a65404407fa166fb8e7c214218627 | sidv/Assignments | /Abhinav_Karthik_R/Aug9/calc/addition.py | 173 | 4.125 | 4 | print("________________Addition________________")
n1= int(input("Enter First Number "))
n2= int(input("Enter Second Number "))
result= n1+n2
print("The result is: ",result)
|
40e21b5654a41dc7a18c44e7c821c14932a252f4 | changeworld/nlp100 | /python/01/05.py | 492 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# 05. n-gram
# 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ.
sentence = 'I am an NLPer'
def ngram(input, n):
l = len(input) - n + 1
list = []
for i in range(0, l):
list.append(input[i:i+n])
return list
print (ngram(sentence.split(), 2))
print (ngram(sentence.replace(' ', ''), 2))
|
56321052d932ff1321f0d29a850df143d73614e3 | robguderian/comp1030-2017 | /13_strings/A3Q1.py | 1,259 | 4.09375 | 4 | def right_side_triangle():
heightStr = raw_input("How tall?")
height = int(heightStr)
for i in range(0, height):
for j in range(0, height):
if j < height - i - 1:
print " ",
else:
print '*',
# print nothing, then a new line
print
def left_side_triange():
strSize = raw_input("what size? > ")
intSize = int(strSize)
for i in range(0, intSize):
for j in range(0, intSize):
print "*",
# print nothing, then a new line
print
def rectangle():
strSizeX = raw_input("what size for x? > ")
intSizeX = int(strSizeX)
strSizeY = raw_input("what size for y? > ")
intSizeY = int(strSizeY)
for i in range(0, intSizeX):
for j in range(0, intSizeY):
print "*",
# print nothing, then a new line
print
userInput = raw_input("What would you like to do? Options: rst, lst, rect > ")
while userInput != "quit":
if userInput == 'rst':
right_side_triangle()
elif userInput == 'lst':
left_side_triange()
elif userInput == 'rect':
rect()
userInput = raw_input("What would you like to do? Options: rst, lst, rect > ") |
141d70c4867597f4ca0741917d86d6c2f901b7d9 | HLNN/leetcode | /src/1739-split-two-strings-to-make-palindrome/split-two-strings-to-make-palindrome.py | 1,900 | 4.0625 | 4 | # You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.
#
# When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits.
#
# Return true if it is possible to form a palindrome string, otherwise return false.
#
# Notice that x + y denotes the concatenation of strings x and y.
#
#
# Example 1:
#
#
# Input: a = "x", b = "y"
# Output: true
# Explaination: If either a or b are palindromes the answer is true since you can split in the following way:
# aprefix = "", asuffix = "x"
# bprefix = "", bsuffix = "y"
# Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.
#
#
# Example 2:
#
#
# Input: a = "xbdef", b = "xecab"
# Output: false
#
#
# Example 3:
#
#
# Input: a = "ulacfd", b = "jizalu"
# Output: true
# Explaination: Split them at index 3:
# aprefix = "ula", asuffix = "cfd"
# bprefix = "jiz", bsuffix = "alu"
# Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.
#
#
#
# Constraints:
#
#
# 1 <= a.length, b.length <= 105
# a.length == b.length
# a and b consist of lowercase English letters
#
#
class Solution:
def checkPalindromeFormation(self, a: str, b: str) -> bool:
i, j = 0, len(a) - 1
while i < j and a[i] == b[j]:
i, j = i + 1, j - 1
s1, s2 = a[i:j + 1], b[i:j + 1]
i, j = 0, len(a) - 1
while i < j and b[i] == a[j]:
i, j = i + 1, j - 1
s3, s4 = a[i:j + 1], b[i:j + 1]
return any(s == s[::-1] for s in (s1,s2,s3,s4))
|
e6d4e3b8bf052425f8b431b55b65abac351f5a77 | eechoo/Algorithms | /LeetCode/BinaryTreePostorderTraversal.py | 897 | 4.0625 | 4 | #!/usr/bin/python
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
A=[]
if(root == None):
return A
if(root.left != None):
A=self.postorderTraversal(root.left)
if(root.right != None):
A+=self.postorderTraversal(root.right)
A.append(root.val)
return A
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
def main():
root=TreeNode(7)
Tleft=TreeNode(3)
Tright=TreeNode(4)
root.left=Tleft
root.right=Tright
test(root.postorderTraversal(root),[3,4,7])
if __name__ == '__main__':
main() |
e807063ef5fe15baf454cb9a2fb4c022bfebddba | RickyLiTHU/codePractice | /70.py | 311 | 3.546875 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return n
prev, current = 1, 2
for i in range(3, n):
prev, current = current, prev + current
return current + prev |
3c4bb86f122809366b6baebc7d80e967d14b12e0 | Jenko-gpu/Jenko-gpu | /TimeFinder.py | 2,207 | 3.765625 | 4 | class Time:
def __init__(self,hours=0,mins='00'):
self.__hours = str(hours)
if mins==0:
mins="00"
self.__mins = str(mins)
def __str__(self):
return self.__hours+":"+self.__mins
class Date:
def __init__(self,day,month):
self._day=str(day)
self._month=str(month)
def __str__(self):
return self._day+'.'+self._month
class TimeFinder:
SEPARATOR_COLON= ':'
SEPARATOR_DOT='.'
PARTS_OF_DAY={"утра":0,"ночи":0,"дня":12,"вечера":12}
SEASONS={"января":1,"февраля":2,"марта":3,"апреля":4,
"мая":5,"июня":6,"июля":7,"августа":8,
"сентября":9,"октября":10,"ноября":11,"декабря":12}
def __init__(self,string):
_words=string.split()
for ind in range(len(_words)):
if '0' <= _words[ind][0] and _words[ind][0] <= '9': # Main case
if self.SEPARATOR_COLON in _words[ind]: # If time
_nums=list(map(int, _words[ind].split(self.SEPARATOR_COLON)))
if _nums[0]<=24 and _nums[1]<=60:
print(Time(_nums[0], _nums[1]))
else:
print("-")
elif self.SEPARATOR_DOT in _words[ind]: # If date
_nums=list(map(int,_words[ind].split(self.SEPARATOR_DOT)))
if _nums[0]<32 and _nums[1]<13:
print(Date(_nums[0],_nums[1]))
else:
if ind+1<len(_words):
if _words[ind+1] in self.PARTS_OF_DAY.keys():
_hours=int(_words[ind])+self.PARTS_OF_DAY[_words[ind+1]]
if _hours>24:
print("-")
else:
print(Time(_hours))
elif _words[ind+1] in self.SEASONS.keys():
print(Date(_words[ind],self.SEASONS[_words[ind+1]]))
else:
print("-")
TimeFinder(input())
# Проверка коммитов
|
8a9b5a709735749edd5f969ac5ccfc89059f4e6f | snang-e/masanai | /root_ex.py | 605 | 3.625 | 4 | # m = int(input('m : '))
# n = int(input('n : '))
# l = int(input('l : '))
# def root_ex(a, b, c):
# x1 = (-b + (b**2-4*a*c)**0.5) / 2 * a
# x2 = (-b - (b**2-4*a*c)**0.5) / 2 * a
# print('해는 ', x1, '또는 ', x2)
# root_ex(m, n, l)
def get_sum(a, b):
return a+b
def get_sum_1(a=1, b=2):
return a+b
def get_sum_2(a, b, c=3, d=4):
result_1 = a + b
result_2 = c - d
return result_1, result_2
n1 = get_sum(10, 20)
print('10과 20의 합 : ', n1)
n2 = get_sum(100, 200)
print('100과 200의 합 : ', n2)
n3 = get_sum_1()
print(n3)
n4 = get_sum_2(3, 4)
print(n4)
|
47d44ac502e33b0eaefad159469ed8d40eb48c4f | PawelDabala/KATA | /exercise17.py | 742 | 3.671875 | 4 | """
Classy Classes
Basic Classes, this kata is mainly aimed at the new JS ES6 Update introducing classes
Task
Your task is to complete this Class, the Person class has been created.
You must fill in the Constructor method to accept a name as string and an age as number,
complete the get Info property and getInfo method/Info getter which should return
johns age is 34
"""
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
@property
def info(self):
return "{} age is {}".format(self.name, self.age)
@info.setter
def info(self, value):
self.name, self.age = value
p = Person("pawel","34")
p.info = ("Pawel", 56)
print(p.info) |
72da4299506ba66bb7de40c07a9b75635986e1bc | aadityarajkumawat/glowing-parakeet | /vendingmachine.py | 11,102 | 3.546875 | 4 | from statemachine import StateMachine, State
import tkinter as tk
class VendingMachine(StateMachine):
coke = State("CocaCola", initial=True)
sprite = State("Sprite")
fanta = State("Fanta")
pepsi = State("Pepsi")
select_sprite = coke.to(sprite)
select_fanta = coke.to(fanta)
select_pepsi = coke.to(pepsi)
select_coke_sprite = sprite.to(coke)
select_coke_fanta = fanta.to(coke)
select_coke_pepsi = pepsi.to(coke)
def reset_state(self):
if(VendingMachine.sprite == self.current_state):
self.select_coke_sprite()
elif(VendingMachine.fanta == self.current_state):
self.select_coke_fanta()
elif(VendingMachine.pepsi == self.current_state):
self.select_coke_pepsi()
def vendCurrentDrink(drink_name):
for i in (drinks):
if(i == drink_name):
drinks[i]["qty"] = drinks[i]["qty"] - 1
drinks = {"coke": {"qty": 5, "price": 35},
"sprite": {"qty": 5, "price": 30},
"fanta": {"qty": 5, "price": 40},
"pepsi": {"qty": 5, "price": 45}}
vending_machine = VendingMachine()
wallet = 1000
enteredAmout = 10
changeAmount = 0
if(drinks[vending_machine.current_state.identifier]["qty"] > 0):
if(drinks[vending_machine.current_state.identifier]["price"] <= enteredAmout):
wallet = wallet - enteredAmout
vendCurrentDrink(vending_machine.current_state.identifier)
changeAmount = enteredAmout - drinks[vending_machine.current_state.identifier]["price"]
else:
drink_name = vending_machine.current_state.identifier
drink_price = drinks[drink_name]["price"]
vending_machine.reset_state()
else:
drink_name = vending_machine.current_state.identifier
vending_machine.reset_state()
# GUI
root = tk.Tk()
root.title("Vending Machine")
root.configure(background='#212121')
root.geometry('1200x800')
top_frame = tk.Frame(root)
top_frame.configure(background='#212121')
top_frame.pack(fill=tk.X)
wallet_btn = tk.Label(top_frame, text='Wallet: 1000', fg='#fff', height='2', width='14')
wallet_btn["bg"] = "#727272"
wallet_btn["border"] = 0
wallet_btn.pack(side=tk.LEFT, padx=20, pady=20)
title = tk.Label(top_frame, text='Vending Machine', fg='#ffffff', font=20)
title.configure(background='#212121')
title.pack(pady=20, padx=100)
# Client wallet
wallet_amt = 1000
# Function
price_color_coke='#fff'
price_color_sprite='#fff'
price_color_fanta='#fff'
price_color_pepsi='#fff'
def got30():
givencost = 30
if(vending_machine.current_state.value == 'coke'):
changeAmount = givencost - 35
elif(vending_machine.current_state.value == 'sprite'):
changeAmount = givencost - 30
elif(vending_machine.current_state.value == 'fanta'):
changeAmount = givencost - 40
elif(vending_machine.current_state.value == 'pepsi'):
changeAmount = givencost - 45
if(changeAmount < 0):
vending_machine.reset_state()
cc = 'Change: ' + str(changeAmount)
change_label.configure(text=cc)
def got40():
givencost = 40
if(vending_machine.current_state.value == 'coke'):
changeAmount = givencost - 35
elif(vending_machine.current_state.value == 'sprite'):
changeAmount = givencost - 30
elif(vending_machine.current_state.value == 'fanta'):
changeAmount = givencost - 40
elif(vending_machine.current_state.value == 'pepsi'):
changeAmount = givencost - 45
if(changeAmount < 0):
vending_machine.reset_state()
cc = 'Change: ' + str(changeAmount)
change_label.configure(text=cc)
def got50():
givencost = 50
if(vending_machine.current_state.value == 'coke'):
changeAmount = givencost - 35
elif(vending_machine.current_state.value == 'sprite'):
changeAmount = givencost - 30
elif(vending_machine.current_state.value == 'fanta'):
changeAmount = givencost - 40
elif(vending_machine.current_state.value == 'pepsi'):
changeAmount = givencost - 45
if(changeAmount < 0):
vending_machine.reset_state()
cc = 'Change: ' + str(changeAmount)
change_label.configure(text=cc)
def selectCoke():
vending_machine.reset_state()
coke_price_label.configure(fg='red')
sprite_price_label.configure(fg='#fff')
fanta_price_label.configure(fg='#fff')
pepsi_price_label.configure(fg='#fff')
curr_drink.configure(file='./assets/coke.png')
thiscost = 35
cc = 'Cost:' + str(thiscost)
cost_label.configure(text=cc)
def selectSprite():
vending_machine.reset_state()
vending_machine.select_sprite()
coke_price_label.configure(fg='#fff')
sprite_price_label.configure(fg='lightgreen')
fanta_price_label.configure(fg='#fff')
pepsi_price_label.configure(fg='#fff')
curr_drink.configure(file='./assets/sprite.png')
thiscost = 30
cc = 'Cost:' + str(thiscost)
cost_label.configure(text=cc)
def selectFanta():
vending_machine.reset_state()
vending_machine.select_fanta()
coke_price_label.configure(fg='#fff')
sprite_price_label.configure(fg='#fff')
fanta_price_label.configure(fg='orange')
pepsi_price_label.configure(fg='#fff')
curr_drink.configure(file='./assets/fanta.png')
thiscost = 40
cc = 'Cost:' + str(thiscost)
cost_label.configure(text=cc)
def selectPepsi():
vending_machine.reset_state()
vending_machine.select_pepsi()
coke_price_label.configure(fg='#fff')
sprite_price_label.configure(fg='#fff')
fanta_price_label.configure(fg='#fff')
pepsi_price_label.configure(fg='#0066ff')
curr_drink.configure(file='./assets/pepsi.png')
thiscost = 45
cc = 'Cost:' + str(thiscost)
cost_label.configure(text=cc)
def pay():
global wallet_amt
if(vending_machine.current_state.value == 'coke'):
wallet_amt = wallet_amt - 35
elif(vending_machine.current_state.value == 'sprite'):
wallet_amt = wallet_amt - 30
elif(vending_machine.current_state.value == 'fanta'):
wallet_amt = wallet_amt - 40
elif(vending_machine.current_state.value == 'pepsi'):
wallet_amt = wallet_amt - 45
ww = "Wallet: " + str(wallet_amt)
wallet_btn.configure(text=ww)
def clean_reset():
global wallet_amt
vending_machine.reset_state()
vending_machine.select_pepsi()
coke_price_label.configure(fg='#fff')
sprite_price_label.configure(fg='#fff')
fanta_price_label.configure(fg='#fff')
pepsi_price_label.configure(fg='#fff')
curr_drink.configure(file='./assets/fil.png')
cost_label.configure(text='Cost: ...')
change_label.configure(text='Change: ...')
wallet_btn.configure(text='Wallet: 1000')
wallet_amt = 1000
wallet = 1000
# Drinks Frame
drinks_frame = tk.Frame(root)
drinks_frame.configure(background='#989898', width='800', height='200')
drinks_frame.pack(pady=20)
# Drinks
drink_coke = tk.Frame(drinks_frame)
drink_coke.configure(background='#4a4a4a', width='200', height='200')
drink_coke.grid(column=0, row=0, padx=2, pady=2)
coke_img = tk.PhotoImage(file='./assets/coke.png')
coke_label = tk.Button(drink_coke, image=coke_img, bg='#4a4a4a', height='200', width='200', borderwidth=1, command=selectCoke)
coke_label.pack()
drink_sprite = tk.Frame(drinks_frame)
drink_sprite.configure(background='#4a4a4a', width='200', height='200')
drink_sprite.grid(column=1, row=0, padx=2, pady=2)
sprite_img = tk.PhotoImage(file='./assets/sprite.png')
sprite_label = tk.Button(drink_sprite, image=sprite_img, bg='#4a4a4a', height='200', width='200', borderwidth=1, command=selectSprite)
sprite_label.pack()
drink_fanta = tk.Frame(drinks_frame)
drink_fanta.configure(background='#4a4a4a', width='200', height='200')
drink_fanta.grid(column=2, row=0, padx=2, pady=2)
fanta_img = tk.PhotoImage(file='./assets/fanta.png')
fanta_label = tk.Button(drink_fanta, image=fanta_img, bg='#4a4a4a', height='200', width='200', borderwidth=1, command=selectFanta)
fanta_label.pack()
drink_pepsi = tk.Frame(drinks_frame)
drink_pepsi.configure(background='#4a4a4a', width='200', height='200')
drink_pepsi.grid(column=3, row=0, padx=2, pady=2)
pepsi_img = tk.PhotoImage(file='./assets/pepsi.png')
pepsi_label = tk.Button(drink_pepsi, image=pepsi_img, bg='#4a4a4a', height='200', width='200', borderwidth=1, command=selectPepsi)
pepsi_label.pack()
# Drink price labels
price_labels_frame = tk.Frame(root)
price_labels_frame.configure(background='#989898', width='825', height='40')
price_labels_frame.pack()
k = '29'
coke_price_label = tk.Label(price_labels_frame, text='35', bg='#4a4a4a', fg=price_color_coke, height='2', width=k, borderwidth=1)
coke_price_label.grid(column=0, row=0)
sprite_price_label = tk.Label(price_labels_frame, text='30', bg='#4a4a4a', fg=price_color_sprite, height='2', width=k, borderwidth=1)
sprite_price_label.grid(column=1, row=0)
fanta_price_label = tk.Label(price_labels_frame, text='40', bg='#4a4a4a', fg=price_color_fanta, height='2', width=k, borderwidth=1)
fanta_price_label.grid(column=2, row=0)
pepsi_price_label = tk.Label(price_labels_frame, text='45', bg='#4a4a4a', fg=price_color_pepsi, height='2', width=k, borderwidth=1)
pepsi_price_label.grid(column=3, row=0)
# Select coin
spec_frame = tk.Frame(root)
spec_frame.configure(width='825', height='300', background='#212121')
spec_frame.pack(pady=30)
# Insert coin frame
insert_coin = tk.Frame(spec_frame)
insert_coin.configure(width='300', height='300', background='#212121')
insert_coin.grid(column=0, row=0)
insert_c = tk.Label(insert_coin)
insert_c.configure(width='42', text='Insert Coin', background='#212121', fg='#fff', font=8)
insert_c.grid(column=0, row=0, pady=30)
list_frame = tk.Frame(insert_coin)
list_frame.configure(width='300', height='278', background='#212121')
list_frame.grid(column=0, row=1)
h = '1'
coin_color_30 = "#fff"
coin_color_40 = "#fff"
coin_color_50 = "#fff"
coin1 = tk.Button(list_frame, text='30', width='12', height=h, fg=coin_color_30, bg='#212121', font=8, command=got30)
coin1.grid(column=0, row=0, pady=2)
coin2 = tk.Button(list_frame, text='40', width='12', height=h, fg=coin_color_40, bg='#212121', font=8, command=got40)
coin2.grid(column=0, row=1, pady=2)
coin3 = tk.Button(list_frame, text='50', width='12', height=h, fg=coin_color_50, bg='#212121', font=8, command=got50)
coin3.grid(column=0, row=2, pady=2)
pay_btn = tk.Button(list_frame, text='Pay', background='#0066ff', fg='#fff', width='32', border='0', height='3', command=pay)
pay_btn.grid(pady=10)
reset_btn = tk.Button(list_frame, text='Reset', background='#0066ff', fg='#fff', width='32', border='0', height='3', command=clean_reset)
reset_btn.grid(pady=10)
dark='#212121'
light='#fff'
# Filler
filler = tk.Frame(spec_frame)
filler.configure(width='225', height='300', background='#212121')
filler.grid(column=1, row=0)
# Current product
insert_coin1 = tk.Frame(spec_frame)
insert_coin1.configure(width='300', height='300', background=dark)
insert_coin1.grid(column=2, row=0)
cost_label = tk.Label(insert_coin1, text='Cost: ...', width='42', background=dark, fg=light, font=8)
cost_label.grid(column=0, row=0, pady=3)
change_label = tk.Label(insert_coin1, text='Change: ...', width='42', background=dark, fg=light, font=8)
change_label.grid(column=0, row=1, pady=3)
curr_drink = tk.PhotoImage(file='./assets/fil.png')
curr_drink_label = tk.Label(insert_coin1, image=curr_drink, background='#3a3a3a')
curr_drink_label.grid()
root.mainloop()
|
4cd7a4ba3561c0c601b80debdbddbc9d5af9be87 | Varsha1230/python-programs | /ch10_oops.py/ch10_2_employee.py | 518 | 4.3125 | 4 | class Employee:
company = "Google" # class-attribute
harry = Employee() #creating employee class object
rajni = Employee() #creating employee class object
harry.salary =300 # instance-attribute
rajni.salary = 400 # instance-attribute
print(harry.company)
print(rajni.company)
Employee.company ="YouTube" #changing class-attribute using class name i.e. Employee,,, bcoz comapny is the class Employee's attribute
print(harry.company)
print(rajni.company)
print(harry.salary)
print(rajni.salary) |
b288fb71f75d74b9e2335de0e57adc3133bf4576 | dirtmerchant/coursera | /week3/module3.py | 3,338 | 4.65625 | 5 | print()
print("Fill in the blanks of this code to print out the numbers 1 through 7.")
print()
number = 1
while number < 8:
print(number, end=" ")
number = number + 1
print()
print("The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen.")
print()
def show_letters(word):
for i in word:
print(i)
show_letters("Hello")
# Should print one line per letter
print()
print("Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.")
print()
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n // 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
print()
print("This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:")
print()
def multiplication_table(start, stop):
for x in range(start, stop+1):
for y in range(start, stop+1):
print(str(x*y), end=" ")
print()
multiplication_table(1, 3)
# Should print the multiplication table shown above
print()
print("This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:")
print()
def counter(start, stop):
if start > stop:
return_string = "Counting down: "
while start >= stop:
return_string += str(start)
if start > stop:
return_string += ","
start = start - 1
else:
return_string = "Counting up: "
while start <= stop:
return_string += str(start)
if start < stop:
return_string += ","
start = start + 1
return return_string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
print()
print("The even_numbers function returns a space-separated string of all positive numbers that are divisible by 2, up to and including the maximum that's passed into the function. For example, even_numbers(6) returns “2 4 6”. Fill in the blank to make this work.")
print()
def even_numbers(maximum):
return_string = ""
for x in range(2, maximum + 1, 2):
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed
for x in range(1, 10, 3):
print(x)
for x in range(10):
for y in range(x):
print(y)
def votes(params):
for vote in params:
print("Possible option:" + vote)
print(votes("yes", "no", "maybe")) |
bc7f7cb6ceb794e609133b082ce7f9ce48840734 | rohitdhiman1/PythonIO | /ReadWrite.py | 307 | 3.5625 | 4 | #Basic python code for reading and writing a file
f = open("C:\\Users\Jack Sparrow\Input\Tesla.txt","r");
message = f.read()
list1 = message.split(".")
#Splitting can be implemented as required
print(list1)
f2 = open("C:\\Users\Jack Sparrow\\Kia.txt","w")
for i in list1:
f2.write(i)
f2.write("\n")
f2.close()
|
f87717bf16bf99dd67a5b635100a49949dd3aa31 | Juvikont/first-attempt | /Saloon/model.py | 4,545 | 3.625 | 4 | from datetime import date as d
from Saloon.database import get_services
print('Welcome to Saloon!')
class Journal(object):
def __init__(self, date, name, service, cash):
self.service = service
self.date = date
self.name = name
self.cash = cash
def info(self):
print(self.name, self.date, self.service, self.cash)
class Services(object):
def __init__(self, sex, service, price, name):
self.sex = sex
self.service = service
self.price = price
self.name = name
def info(self):
print(self.sex, self.service, self.price, self.name)
def add_journal():
name = input('Your name: ')
service = input('Type of service: ')
cash = input('Amount: ')
date = d.today()
customer = Journal(name, service, date, cash)
customer.info()
return customer
def output(services):
for services in services:
services.info()
def money(incomes):
_sum = 0
for income in incomes:
int(income.cash)
_sum = _sum = _sum + int(income.cash)
return print(_sum)
def search_service(services):
service = input('Please provide the service you want to find: ')
for __type in services:
if __type.service.lower() == service.lower():
__type.info()
def add_service():
sex = input('Gender: ')
service = input('Type of the service: ')
name = input('Name of the service: ')
price = input('Price: ')
value = Services(sex, service, name, price)
return value
Box_Haircut = Services(sex='Men\'s', service='Haircut', name='"Box"', price='50$')
Half_Box_Haircut = Services(sex='Men\'s', service='Haircut', name='"Half-Box"', price='45$')
Natural_Coloring = Services(sex='Female\'s', name='"Natural"', service='Coloring', price='75$')
Blond_Coloring = Services(sex='Female\'s', name='"Blond"', service='Coloring', price='30$')
Strong_Bob = Services(sex='Female\'s', service='Haircut', name='"Strong-Bob"', price='70$')
Honolulu = Services(sex='Female\'s', service='Haircut', name='"Honolulu"', price='60$')
Classic_Massage_30_minutes = Services(sex='Body', service='Massage', name='30 Minutes', price='30$')
Classic_Massage_60_minutes = Services(sex='Body', service='Massage', name='60 Minutes', price='55$')
Service_Names = [Box_Haircut, Half_Box_Haircut, Natural_Coloring, Blond_Coloring, Strong_Bob, Honolulu,
Classic_Massage_30_minutes, Classic_Massage_60_minutes]
# pricing = [Services(sex='Men\'s', service='Haircut', name='"Box"', price='50$'),
# Services(sex='Men\'s', service='Haircut', name='"Half-Box"', price='45$'),
# Services(sex='Female\'s', name='"Natural"', service='Coloring', price='75$'),
# Services(sex='Female\'s', name='"Blond"', service='Coloring', price='30$'),
# Services(sex='Female\'s', service='Haircut', name='"Strong-Bob"', price='70$'),
# Services(sex='Female\'s', service='Haircut', name='"Honolulu"', price='60$'),
# Services(sex='Body', service='Massage', name='30 Minutes', price='30$'),
# Services(sex='Body', service='Massage', name='60 Minutes', price='55$')]
Customers = []
# while True:
# print('Our service\'s ')
# print('1. Men\'s Haircut\'s ')
# print('2. Women\'s Haircut\'s ')
# print('3. Coloring ')
# print('4. Massage ')
# print('5. Search service')
# print('6. Add the service')
# print('7. Add customer ')
# print('8. Customers book')
# print('9. End of the day')
# choice = input("What you want to do?: ")
# if choice == '1':
# print('1.1 Box Haircut')
# Box_Haircut.info()
# print('1.1 Half-Box Haircut')
# Half_Box_Haircut.info()
# if choice == '2':
# print('2.1 Strong Bob')
# Strong_Bob.info()
# print('2.2 Honolulu')
# Honolulu.info()
# if choice == '3':
# print('3.1 Natural Coloring')
# Natural_Coloring.info()
# print('3.2 Blond Coloring')
# Blond_Coloring.info()
# if choice == '4':
# print('4.1 30min Massage')
# Classic_Massage_30_minutes.info()
# print('4.2 60min Massage')
# Classic_Massage_60_minutes.info()
# if choice == '5':
# search_service(Service_Names)
# if choice == '6':
# Service_Names.append(add_service())
# if choice == '7':
# Customers.append(add_journal())
# if choice == '8':
# output(Customers)
# if choice == '9':
# money(Customers)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.