blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b6d285ab84015d4e2c9ebdf8a9ea632065ab6293 | yeisoncasta/Fundamentos-De-Programaci-n | /16-03-2021.py | 949 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 16 19:11:30 2021
@author: Yeison David Aguirre
"""
#Factura de venta
def f_titulo():
print("calculo valor factura")
def f_despedida():
print("..... ADIOS ...")
def f_valorfactura(): #encabezado de la funcion
#desarrollo de la funcion
#definicion de la funcion
# Definicion de variables
ve_nomArt = ""
ve_canArt = 0
ve_valUniArt= 0.0
cons_porIva= 0.19
vps_netPag=0.0
vps_ivaPag=0.0
vps_totPag=0.0
# Entrada de datos
ve_nomArt = input("Articulo: ")
ve_canArt = int(input("Cantidad: "))
ve_valUniArt = float(input("Valor Unitario: "))
# Procesos
vps_netPag=ve_canArt * ve_valUniArt
vps_ivaPag=vps_netPag * cons_porIva
vps_totPag=vps_netPag + vps_ivaPag
# Salidas
print( "Neto: ", vps_netPag)
print( "Iva: ", vps_ivaPag)
print( "Total: ",vps_totPag)
#llamado a la funcion
f_titulo()
f_valorfactura()
f_despedida() |
27243cff5e2fa102c7b1b65ae13e56b3072ac392 | KuKuOOOOOO/AE402_KUKUO | /Lesson1/pygame_模板.py | 1,305 | 3.765625 | 4 | """
Pygame 模板程式
"""
# 匯入pygame模組
import pygame
# 定義一些會用到的顏色
# 常數使用大寫
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
# 初始化pygame
pygame.init()
# 創造一個pygame視窗並設定大小及標題
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("我的遊戲")
# 設定一個開關供迴圈使用
done = False
# 創造一個clock控制畫面更新速度
clock = pygame.time.Clock()
# -------- 主要的程式迴圈 -----------
while not done:
# --- 事件迴圈 event loop
for event in pygame.event.get(): # 從事件list中抓取事件
if event.type == pygame.QUIT: # 當使用者按下結束
done = True # 將done變數設為True-->while迴圈將會結束
# --- 程式的運算與邏輯
# --- 繪圖的程式碼
# 先將畫面塗滿底色(將原有畫面清掉)
# 繪圖的程式要寫在這行後面,不然會被這行清掉
screen.fill(WHITE)
pygame.draw.polygon(screen, GREEN, [(350,250),(550,250), (550, 400)], 4)
# --- 更新畫面
pygame.display.flip()
# --- 每秒鐘60個frame
clock.tick(60)
# 關閉式窗並離開程式
pygame.quit()
|
c8a110f526f16ffd9b60e3c2326b3dd364338285 | JaydeepKachare/Python-Classwork | /Recursion/7_5 sum of digit.py | 366 | 4 | 4 | # find sum of digit of number till it is reduceo single digit
def sumdigit(num) :
if int(num/10) == 0 :
return num
return num%10 + sumdigit(int(num/10))
def main() :
num = int(input("Enter any number : "))
sumd = sumdigit(num)
print("Sum of digit of {} is {} ".format(num,sumd))
if __name__ == "__main__" :
main() |
ee04bfff8656142d1abd103c4994d257af6e64c9 | JaydeepKachare/Python-Classwork | /Session11/05.py | 838 | 4.21875 | 4 | # Inheritance in Python
class Base1 :
def __init__(self):
self.i = 10
self.j = 20
print("Inside Base Constructor")
def fun(self) :
print("Inside Base1 fun")
class Base2 :
def __init__(self):
self.x = 30
self.y = 40
print("Inside Base Constructor")
def fun(self) :
print("Inside Base2 fun")
class Derived (Base1,Base2) :
def __init__(self):
Base2.__init__(self)
Base1.__init__(self)
self.a = 50
self.b = 60
print("Inside Derived Constructor")
def fun(self) :
Base2.fun(self)
def main() :
dobj = Derived()
print(dobj.i)
print(dobj.j)
print(dobj.x)
print(dobj.y)
print(dobj.a)
print(dobj.b)
dobj.fun()
if __name__ == "__main__" :
main()
|
199da8145e506f6e08900a15431258286e8216dc | JaydeepKachare/Python-Classwork | /Recursion/7_7 PrimeFactors.py | 718 | 4.1875 | 4 | # find prime factors of given number
# using while loop
def primeFactors(num) :
i = 2
while (i <= num ) :
if num % i == 0 :
print(i,end=" ")
num = int(num/i)
i = 1
i+=1
print()
# using recursion
def primeFactorsR(num,i) :
if i >= num :
print(i)
return
if (num%i == 0) :
print(i,end=" ")
primeFactorsR(int(num/i),2)
else :
primeFactorsR(num,i+1)
return
def main() :
num = int(input("ENterany number : "))
print("Prime factors of {} are ".format(num), end=" ")
# primeFactors(num)
primeFactorsR(num,2)
if __name__ == "__main__" :
main() |
08ea268eeef6f3db56017baaca8b433d0d15c5e6 | JaydeepKachare/Python-Classwork | /Session14/Practice/02.py | 1,174 | 3.75 | 4 | # classis sumarray example for multithreding
import time
import threading
class SumArray :
def add(self,arr,name,lock) :
lock.acquire()
total = 0
for ele in arr :
total += ele
print(f"Running total {name}: ",total)
time.sleep(0.5)
lock.release()
return total
class PThread :
sa = SumArray()
def __init__(self,numList,name):
self.numList = numList
self.name = name
def getTotal(self,lock) :
# lock.acquire()
result = PThread.sa.add(self.numList,self.name,lock)
print(f"{self.name} total is {result}")
# lock.release()
def main() :
print("Start of main ")
lcok = threading.Lock()
arr1 = [11,12,13,14,15,16,17,18,19,20]
th1 = PThread(arr1,"Th1")
# th1.getTotal()
t1 = threading.Thread(target=th1.getTotal,args=(lcok,))
t1.start()
arr2 = [21,22,23,24,25,26,27,28,29,30]
th2 = PThread(arr2,"Th2")
# th2.getTotal()
t2 = threading.Thread(target=th2.getTotal,args=(lcok,))
t2.start()
print("End of main")
if __name__ == "__main__" :
main() |
65fc4f293f441ff863eb83dc60cdf7e7935b5121 | JaydeepKachare/Python-Classwork | /Session6/practice/01 isPrime.py | 432 | 4.15625 | 4 | # check whether given number is prime or not
def isPrime (num) :
for i in range(2,num) :
if num % i == 0 :
return False
return True
# main function
def main() :
num = int(input("Enter any number : "))
if isPrime(num) == True :
print("{} is prime number ".format(num))
else :
print("{} is not prime number ".format(num))
if __name__ == "__main__" :
main() |
b430b75b9901d8ede78c838c9c9c1a1d00719366 | JaydeepKachare/Python-Classwork | /Session5/01.py | 508 | 3.796875 | 4 |
def demo() :
pass
# import module for arithmetic function
import functionFile
# main function for entry point
def main() :
value1 = int(input("Enter num1 : "))
value2 = int(input("Enter num2 : "))
addition = functionFile.add(value1,value2)
subtraction = functionFile.sub(value1 ,value2)
print("Addition of {} and {} is {}".format(value1,value2,addition))
print("Subtraction of {} and {} is {}".format(value1,value2,subtraction))
if __name__ == "__main__" :
main()
|
8429ac7352246d3aec08252c854331b760f94cee | JaydeepKachare/Python-Classwork | /Session5/ways to pass args to function/01.py | 927 | 3.859375 | 4 | # how to pass arguments to functions
# positional argument passing
# sequence of passed arguments matters
def student(name, roll, address, marks):
print("Name : ", name)
print("roll : ", roll)
print("address : ", address)
print("marks : ", marks)
# keyword arguments
def computer(ram, processor, HDD):
print("RAM size : ", ram)
print("processor : ", processor)
print("Hard disk : ", HDD)
# default argument
def calcArea(radius, PI=3.14):
print("Values of PI is {}".format(PI))
area = PI * radius * radius
return area
# variable number of argument
def fun(*value):
print("number of arguments are : ", len(value))
def main():
# student("Jaydeep" , 101 , "Pune" , 80)
# computer(processor="i9",ram="16 GB", HDD="512 GB")
# calcArea(10,3)
# calcArea(10)
fun(10, 20, 30, 40, 50)
if __name__ == "__main__":
main()
|
a0033278eee5f2ce160875caa8bd5d270989d3ea | JaydeepKachare/Python-Classwork | /Recursion/7_9 nth term of fibo.py | 278 | 4.1875 | 4 | # calculate nth term of fibonacci series
def fibo(num) :
if num == 0 or num == 1 :
return 1
return fibo(num-1) + fibo(num-2)
def main() :
n = int(input("Enter term to find : "))
print(fibo(n))
if __name__ == "__main__" :
main() |
3ac676ad03420612fc457e1af99f3a24a805d6fb | JaydeepKachare/Python-Classwork | /Session3/identation.py | 280 | 3.9375 | 4 |
num1 = int(input("Enter number : ") ) # ident 0
num1 = int(input("Enter number : ") ) # ident 1
num1 = int(input("Enter number : ") ) # ident 2
num1 = int(input("Enter number : ") ) # ident 3 |
429eba9184269362ba990a7e9268b17786012b1f | JaydeepKachare/Python-Classwork | /Session10/01.py | 581 | 3.84375 | 4 | # init and destroy method in Pythob OOP
class Demo :
x=10 # class variable
y=20 # class variable
def __init__(self):
print("Inside __init__ (constructor)")
self.i = 30 # instance variable
self.j = 40 # instance variable
def __del__ (self) :
print("Inside destructor ")
def fun(self) :
print("Inside fun")
def main() :
obj1 = Demo()
obj2 = Demo()
obj1.fun() # fun(obj1)
del obj1
del obj2
if __name__ == "__main__" :
main()
|
b9d16e4a06e0485a6e4e5c26bf4673d063c1eb7e | JaydeepKachare/Python-Classwork | /Session3/Arithematic6.py | 429 | 4.125 | 4 | # addition of two number
def addition(num1, num2):
ans = num1+num2
return ans
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2)
print("Addition : ",ans)
num1 = int(input("Enter num1 : "))
num2 = int(input("Enter num2 : "))
ans = addition(num1,num2) # reusing same function (function call)
print("Addition : ",ans)
|
e200d189bee58ad51f7ad8721ef54aaf2d5d63e0 | JaydeepKachare/Python-Classwork | /Recursion/540.py | 366 | 4.375 | 4 | # check whether if string is palindrome or not
def isPalindrome(str) :
if len(str)==0 or len(str)==1 :
return True
if str[0] == str[-1] :
return isPalindrome(str[1:-1])
else :
return False
str = input("Enter string : " )
if isPalindrome(str) == True :
print("Palindrome")
else :
print("Not Palindrome") |
b4edc9c68745dd45a11162dbe19b83f151fca469 | JaydeepKachare/Python-Classwork | /Session12/04 function overloading.py | 226 | 3.828125 | 4 | # function overloading
class Demo :
def add(self,no1,no2) :
return no1+no2
def add(self,no1,no2,no3) :
return no1+no2+no3
obj = Demo()
print(obj.add(10,20))
print(obj.add(10,20,30))
|
0630477126760d237493e91a65b1bc4b2678b45b | nickmoran06/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 277 | 3.75 | 4 | #!/usr/bin/python3
def no_c(my_string):
if my_string is None:
return
my_list = list(my_string)
for counter in range(len(my_list)):
if my_list[counter] is "c" or my_list[counter] is "C":
my_list[counter] = ""
return(''.join(my_list))
|
273b506420992223e0e5f18d11d6b46b191afe17 | nickmoran06/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 354 | 3.96875 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for row in range(0, len(matrix)):
for line in range(0, len(matrix[row])):
if line == (len(matrix[row]) - 1):
print("{:d}".format(matrix[row][line]), end="")
else:
print("{:d}".format(matrix[row][line]), end=" ")
print()
|
9c5ddd2cb66158b8afefb4ba47d7d3e7d34f3e06 | nickmoran06/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/8-simple_delete.py | 258 | 3.609375 | 4 | #!/usr/bin/python3
def simple_delete(a_dictionary, key=""):
if key in a_dictionary:
for counter in a_dictionary:
if counter is key:
del a_dictionary[counter]
return a_dictionary
return a_dictionary
|
a98550e8476a525f420b2fb444d0651dfe030083 | nickmoran06/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 178 | 3.796875 | 4 | #!/usr/bin/python3
def inherits_from(obj, a_class):
"""returns boolean if obj is a subclass of a_class"""
return(issubclass(type(obj), a_class) and type(obj) != a_class)
|
ddb1217174e32573b306d270dca7530a3e70914a | cs-cordero/interview-prep | /leetcode/0092_reverse_linked_list_ii.py | 688 | 3.765625 | 4 | from typing import Optional
class ListNode:
# Provided by Leetcode
...
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
def helper(
node: ListNode, start: Optional[ListNode], a: int, b: int
) -> ListNode:
reverse_head = node if a == 0 else start
if b == 0:
start.next = node.next
return node
tail = helper(node.next, reverse_head, a - 1, b - 1)
if a <= 0:
node.next.next = node
return tail
node.next = tail
return node
return helper(head, None, m - 1, n - 1)
|
148a796b2c070f68639f755d9927e077ecd1a6e5 | cs-cordero/interview-prep | /leetcode/0733_flood_fill.py | 1,076 | 3.5625 | 4 | from collections import deque
from typing import Iterable, List, Tuple
class Solution:
def floodFill(
self, image: List[List[int]], sr: int, sc: int, newColor: int
) -> List[List[int]]:
if not image or not image[0]:
return image
limits = len(image), len(image[0])
old_color = image[sr][sc]
queue = deque([(sr, sc)])
visited = {(sr, sc)}
while queue:
row, col = queue.popleft()
for nrow, ncol in neighbors(row, col, limits):
if (nrow, ncol) in visited or image[nrow][ncol] != old_color:
continue
visited.add((nrow, ncol))
queue.append((nrow, ncol))
image[row][col] = newColor
return image
def neighbors(row: int, col: int, limits: Tuple[int, int]) -> Iterable[Tuple[int, int]]:
if row - 1 >= 0:
yield row - 1, col
if col - 1 >= 0:
yield row, col - 1
if row + 1 < limits[0]:
yield row + 1, col
if col + 1 < limits[1]:
yield row, col + 1
|
2199f68b8685f53bcc1512349eaa42064d23bcf0 | cs-cordero/interview-prep | /leetcode/0085_maximal_rectangle.py | 1,180 | 3.5625 | 4 | from typing import List
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
largest = 0
histogram = [0 for _ in range(len(matrix[0]))]
for row in matrix:
for col_index, value in enumerate(row):
if value == "0":
histogram[col_index] = 0
else:
histogram[col_index] += 1
area = get_largest_area_of_rectangle_in_histogram(histogram)
largest = max(area, largest)
return largest
def get_largest_area_of_rectangle_in_histogram(hist: List[int]) -> int:
max_area = 0
stack = []
for i, height in enumerate(hist):
left_width = 0
while stack and height < hist[stack[-1][0]]:
j, j_left_width = stack.pop()
left_width += j_left_width + 1
max_area = max(max_area, hist[j] * (i - j + j_left_width))
stack.append((i, left_width))
i = len(hist)
while stack:
j, j_left_width = stack.pop()
max_area = max(max_area, hist[j] * (i - j + j_left_width))
return max_area
|
0e0c7ab5784b2906e0ad82ae69ded76825480438 | cs-cordero/interview-prep | /grokking-coding/sliding_window/problem_challenge_3.py | 994 | 3.59375 | 4 | from collections import Counter
def find_substring(s: str, pattern: str):
pattern_counts = Counter(pattern)
begin = 0
remaining = set(pattern_counts.keys())
best = None
for end, character in enumerate(s):
if character not in pattern_counts:
continue
pattern_counts[character] -= 1
if pattern_counts[character] == 0:
remaining -= {character}
while not remaining:
candidate = s[begin : end + 1]
best = candidate if best is None or len(candidate) < len(best) else best
removed_char = s[begin]
if removed_char in pattern_counts:
pattern_counts[removed_char] += 1
if pattern_counts[removed_char] > 0:
remaining |= {removed_char}
begin += 1
return best or ""
assert find_substring("aabdec", "abc") == "abdec"
assert find_substring("abdabca", "abc") == "abc"
assert find_substring("adcad", "abc") == ""
|
82344c72a36c4bba71e45f3fa8dbd541b1b1b0a6 | cs-cordero/interview-prep | /hackerrank/journey_to_the_moon.py | 1,048 | 3.5 | 4 | from typing import List
class UnionFind:
def __init__(self, n: int) -> None:
self.uf = list(range(n))
self.lengths = [1] * n
self.components = n
def find(self, i: int) -> int:
if i != self.uf[i]:
self.uf[i] = self.find(self.uf[i])
return self.uf[i]
def union(self, i: int, j: int) -> None:
parent_i = self.find(i)
parent_j = self.find(j)
if parent_i == parent_j:
return None
self.uf[parent_i] = parent_j
self.lengths[parent_j] += self.lengths[parent_i]
self.lengths[parent_i] = 0
def journeyToMoon(n: int, astronaut: List[List[int]]):
uf = UnionFind(n)
for astronaut1, astronaut2 in astronaut:
uf.union(astronaut1, astronaut2)
countries = [count for count in uf.lengths if count > 0]
if len(countries) <= 1:
return 0
answer = 0
count = countries[0]
for i in range(1, len(countries)):
answer += count * countries[i]
count += countries[i]
return answer
|
c26af73ad3ce8a774588bc9cfcd4f9b0313ceed0 | cs-cordero/interview-prep | /leetcode/0951_flip_equivalent_binary_trees.py | 559 | 3.734375 | 4 | class TreeNode:
# Provided by Leetcode
...
class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if root1 is None and root2 is None:
return True
elif root1 is None or root2 is None or root1.val != root2.val:
return False
return (
self.flipEquiv(root1.left, root2.right)
and self.flipEquiv(root1.right, root2.left)
) or (
self.flipEquiv(root1.left, root2.left)
and self.flipEquiv(root1.right, root2.right)
)
|
cb236b24386d6e0d299f4c34d14cbbc40d87cf3d | cs-cordero/interview-prep | /leetcode/0752_open_the_lock.py | 862 | 3.5625 | 4 | from collections import deque
from typing import Iterable, List
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
deadends = set(deadends)
if "0000" in deadends or target in deadends:
return -1
queue = deque([("0000", 0)])
deadends.add("0000")
while queue:
current, steps = queue.popleft()
if current == target:
return steps
for move in moves(current):
if move in deadends:
continue
deadends.add(move)
queue.append((move, steps + 1))
return -1
def moves(base: str) -> Iterable[str]:
for i, val in enumerate(base):
num = int(val)
yield f"{base[:i]}{(num+1)%10}{base[i+1:]}"
yield f"{base[:i]}{(num-1)%10}{base[i+1:]}"
|
3702b011a7d1e16dd58b7517552e7201a71d3759 | cs-cordero/interview-prep | /leetcode/0208_implement_trie.py | 1,223 | 3.640625 | 4 | from dataclasses import dataclass, field
from typing import Dict, Optional
TERMINAL = "*"
@dataclass
class TrieNode:
value: str
children: Dict[str, "TrieNode"] = field(default_factory=dict)
class Trie:
def __init__(self):
self.root = TrieNode(TERMINAL)
def insert(self, word: str) -> None:
current_node = self.root
for char in word:
current_node = current_node.children.setdefault(char, TrieNode(char))
current_node.children.setdefault(TERMINAL, TrieNode(TERMINAL))
def walk_to_end(self, word: str) -> Optional[TrieNode]:
current_node = self.root
for char in word:
current_node = current_node.children.get(char)
if not current_node:
return None
return current_node
def search(self, word: str) -> bool:
last_node = self.walk_to_end(word)
return last_node and bool(last_node.children.get(TERMINAL))
def startsWith(self, prefix: str) -> bool:
return bool(self.walk_to_end(prefix))
obj = Trie()
obj.insert("hello")
print(obj.search("hello"))
print(obj.search("hell"))
print(obj.startsWith("hello"))
print(obj.startsWith("he"))
print(obj.startsWith("hep"))
|
caacbc16aa19b6e229633d4035cb3da44c526a34 | cs-cordero/interview-prep | /leetcode/1055_shortest_way_to_form_string.py | 778 | 3.640625 | 4 | class Solution:
def shortestWay(self, source: str, target: str) -> int:
source_i = 0
target_i = 0
result = 0
source_chars = set(source)
while target_i < len(target):
if target[target_i] not in source_chars:
return -1
if target[target_i] == source[source_i]:
target_i += 1
source_i += 1
if source_i == len(source):
source_i %= len(source)
result += 1
if source_i > 0:
result += 1
return result
print(Solution().shortestWay("abc", "abcbc"))
print(Solution().shortestWay("abc", "acdbc"))
print(Solution().shortestWay("xyz", "xzyxz"))
print(Solution().shortestWay("aaaaa", "aaaaaaaaaaaaa"))
|
12583e346ba8da8008589b5e8a7719cbc2e792a0 | cs-cordero/interview-prep | /grokking-coding/binary_search/problem_search_1.py | 1,363 | 3.734375 | 4 | from typing import List
def search_bitonic_array(arr: List[int], key: int) -> int:
max_index = binary_search_for_max_index(arr)
return max(
binary_search_exact(arr, key, 0, max_index),
binary_search_exact(arr, key, max_index, len(arr) - 1, True),
)
def binary_search_exact(
arr: List[int], key: int, left: int, right: int, desc: bool = False
) -> int:
while left <= right:
mid = (left + right) // 2
if arr[mid] == key:
return mid
if desc is False:
if arr[mid] > key:
left = mid + 1
else:
right = mid - 1
else:
if arr[mid] > key:
right = mid - 1
else:
left = mid + 1
return -1
def binary_search_for_max_index(arr: List[int]) -> int:
left = 1
right = len(arr) - 2
while left <= right:
mid = (left + right) // 2
if arr[mid] > arr[mid - 1] and arr[mid] > arr[mid + 1]:
return mid
elif arr[mid] > arr[mid - 1]:
left = mid + 1
else:
right = mid - 1
return -1
def main():
print(search_bitonic_array([1, 3, 8, 4, 3], 4))
print(search_bitonic_array([3, 8, 3, 1], 8))
print(search_bitonic_array([1, 3, 8, 12], 12))
print(search_bitonic_array([10, 9, 8], 10))
main()
|
1e9ac15b03887131a1be560591b669fe154532d5 | cs-cordero/interview-prep | /grokking-coding/two_pointers/make_squares.py | 464 | 3.71875 | 4 | from typing import List
def make_squares(arr: List[int]) -> List[int]:
squares = []
if not arr:
return squares
left = len(arr) // 2
right = left + 1
while left >= 0 or right < len(arr):
if left >= 0 and (right == len(arr) or abs(arr[left]) < abs(arr[right])):
squares.append(arr[left] ** 2)
left -= 1
else:
squares.append(arr[right] ** 2)
right += 1
return squares
|
2f73be64df175f0bb6d19ff2bfbeee278ee72a67 | cs-cordero/interview-prep | /leetcode/0020_valid_parentheses.py | 533 | 3.859375 | 4 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
bracket_map = {
")": "(",
"}": "{",
"]": "[",
}
open_brackets = {"(", "[", "{"}
for character in s:
if character in open_brackets:
stack.append(character)
continue
expected = bracket_map[character]
if not stack or stack[-1] != expected:
return False
stack.pop()
return not bool(stack)
|
97698cede6a3b92b48c6c47beb936605cc2cf927 | cs-cordero/interview-prep | /leetcode/1293_shortest_path_in_a_grid_with_obstacles_elmination.py | 1,325 | 3.671875 | 4 | from collections import deque
from typing import Iterable, List, Tuple
class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
if not grid or not grid[0]:
return 0
memo = {}
target = len(grid) - 1, len(grid[0]) - 1
queue = deque([(0, 0, 0, k)])
while queue:
row, col, steps, remaining = queue.popleft()
if (row, col) == target:
return steps
memo_key = (row, col, remaining)
if memo_key in memo and steps >= memo[memo_key]:
continue
memo[memo_key] = steps
for next_row, next_col in get_adjacent_points_in_grid(row, col, grid):
if grid[next_row][next_col] == 1:
if remaining > 0:
queue.append((next_row, next_col, steps + 1, remaining - 1))
else:
queue.append((next_row, next_col, steps + 1, remaining))
return -1
def get_adjacent_points_in_grid(
row: int, col: int, grid: List[List[int]]
) -> Iterable[Tuple[int, int]]:
if row - 1 >= 0:
yield row - 1, col
if col - 1 >= 0:
yield row, col - 1
if row + 1 < len(grid):
yield row + 1, col
if col + 1 < len(grid[0]):
yield row, col + 1
|
4bffea9ecd9b760b7ed2efc324bf3f5e847a4227 | cs-cordero/interview-prep | /leetcode/0139_word_break.py | 579 | 3.59375 | 4 | from collections import deque
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
queue = deque([0])
visited = set()
while queue:
start = queue.popleft()
if start in visited:
continue
visited.add(start)
if start == len(s):
return True
for end in range(start, len(s)):
if s[start : end + 1] in words:
queue.append(end + 1)
return False
|
ba41f32aa0373bbffd739f18cd89e7e5f8389c59 | cs-cordero/interview-prep | /grokking-coding/fast_and_slow/find_cycle_start.py | 438 | 3.5625 | 4 | from typing import Optional
class Node:
...
def find_cycle_start(head: Node) -> Optional[Node]:
fast = head
slow = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast != slow:
return None
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return fast
|
a6ade1e6c7dd0902e3c0ab5e02e23bf0b86fdcfd | cs-cordero/interview-prep | /leetcode/0448_find_all_numbers_disappeared_in_an_array.py | 726 | 3.75 | 4 | from typing import List
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
def place_in_correct_position(value: int) -> None:
while nums[value - 1] not in (value, None):
temp = nums[value - 1]
nums[value - 1] = value
value = temp
if nums[value - 1] is None:
nums[value - 1] = value
i = 0
while i < len(nums):
temp = nums[i]
nums[i] = None
place_in_correct_position(temp)
i += 1
result = []
for i, value in enumerate(nums):
if value is None:
result.append(i + 1)
return result
|
86faba0db30dec228cafce129a644291736a3eee | cs-cordero/interview-prep | /leetcode/utils.py | 3,998 | 3.875 | 4 | from __future__ import annotations
from collections import deque
from typing import Any, Iterable, List, Optional
class _Empty:
def __repr__(self) -> str:
return "<Empty>"
Empty = _Empty()
class TreeNode:
EMPTY = Empty
def __init__(self, value: Any) -> None:
self.val = value
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
def __repr__(self) -> str:
return f"TreeNode({str(self.val)})"
def __eq__(self, other: object) -> bool:
return isinstance(other, TreeNode) and self.val == other.val
@classmethod
def subtrees_match(cls, a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
if a is None and b is None:
return True
return (
isinstance(a, TreeNode)
and isinstance(b, TreeNode)
and a == b
and cls.subtrees_match(a.left, b.left)
and cls.subtrees_match(a.right, b.right)
)
@classmethod
def from_array(
cls, arr: List[Any], i: int = 0, allow_none: bool = False
) -> Optional[TreeNode]:
"""
Usually makes sense to assume that values of None in an array mean no
node should be created instead a TreeNode with value of None.
If you want None to be converted to a TreeNode with value None, then
set allow_none == True.
"""
if (
not arr
or i >= len(arr)
or arr[i] == cls.EMPTY
or (allow_none and arr[i] is None)
):
return None
root = TreeNode(arr[i])
root.left = cls.from_array(arr, i * 2 + 1)
root.right = cls.from_array(arr, i * 2 + 2)
return root
def to_array(self) -> List[Any]:
array = []
queue = deque([self])
while queue:
node = queue.popleft()
value = TreeNode.EMPTY if node is None else node.val
array.append(value)
if node:
queue.append(node.left)
queue.append(node.right)
return array
def generate_permutations(base_list: List[Any]) -> Iterable[Any]:
"""
Generates permutations in lexicographical order.
1. Find highest j where arr[j] < arr[j+1]
2. Find highest k where arr[j] < arr[k]
3. Swap elements at indexes j and k
4. Reverse in place all elements after the original j
"""
if len(base_list) < 2:
return None
def find_index_j(arr: List[Any]) -> Optional[int]:
j = None
for i in range(len(arr) - 1):
j = i if arr[i] < arr[i + 1] else j
return j
def find_index_k(arr: List[Any], k: int) -> int:
k = k + 1
for i in range(k, len(arr)):
k = i if arr[i] > arr[k] else k
return k
copied_list = base_list[:]
yield copied_list[:]
while True:
j = find_index_j(copied_list)
if j is None:
return None
k = find_index_k(copied_list, j)
copied_list[j], copied_list[k] = copied_list[k], copied_list[j]
reverse_in_place(copied_list, left=j + 1)
yield copied_list[:]
def quicksort_in_place(
l: List[int], lower_bound: int = 0, upper_bound: int = None
) -> None:
if upper_bound is None:
upper_bound = len(l) - 1
if lower_bound >= upper_bound:
return
pivot = l[upper_bound]
target = lower_bound
for i in range(lower_bound, upper_bound):
if l[i] >= pivot:
continue
l[target], l[i] = l[i], l[target]
target += 1
l[upper_bound], l[target] = l[target], l[upper_bound]
quicksort_in_place(l, lower_bound, target - 1)
quicksort_in_place(l, target + 1, upper_bound)
def reverse_in_place(nums: List[int], left: int = 0, right: int = None) -> None:
if not right:
right = len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
|
07c74c232e2f87e3c0023eb9db1b1d93ad6412d7 | cs-cordero/interview-prep | /grokking-coding/subsets/problem_challenge_3.py | 399 | 3.84375 | 4 | def count_trees(n: int) -> int:
def helper(n: int) -> int:
if n <= 1:
return 1
count = 0
for i in range(n):
count += helper(i - 0) * helper(n - i - 1)
return count
if n < 1:
return 0
return helper(n)
def main():
print("Total trees: " + str(count_trees(2)))
print("Total trees: " + str(count_trees(3)))
main()
|
3d59d6e64cfce68ad29d2efb64fc50b2ac5f06b5 | cs-cordero/interview-prep | /leetcode/0028_implement_strstr.py | 748 | 3.5 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
elif len(needle) > len(haystack):
return -1
target_hash = 0
for i, character in enumerate(needle):
target_hash += ord(character) << (8 * i)
current_hash = 0
for i in range(len(needle)):
current_hash += ord(haystack[i]) << (8 * i)
if current_hash == target_hash:
return 0
for i in range(len(needle), len(haystack)):
current_hash >>= 8
current_hash |= ord(haystack[i]) << (8 * (len(needle) - 1))
if current_hash == target_hash:
return i - len(needle) + 1
return -1
|
0381596838b8e07c110faa88d5462ff676689699 | cs-cordero/interview-prep | /leetcode/0040_combination_sum_2.py | 986 | 3.625 | 4 | from typing import List, Optional, Set, Tuple
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[Tuple[int]]:
return list(get_combination(candidates, target))
def get_combination(
candidates: List[int],
target: int,
current_sum: int = 0,
current_combo: Optional[List[int]] = None,
) -> Set[Tuple[int]]:
current_combo = current_combo or []
if current_sum == target:
return {tuple(sorted(current_combo))}
elif current_sum > target:
return set()
results = set()
for i, candidate in enumerate(candidates):
if candidate + current_sum > target:
continue
results |= get_combination(
candidates[i + 1 :],
target,
current_sum + candidate,
current_combo + [candidate],
)
return results
print(Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8))
print(Solution().combinationSum2([2, 5, 2, 1, 2], 5))
|
e844e141616db856a8d71684deb8c7ab4d368daa | cs-cordero/interview-prep | /leetcode/0239_sliding_window_maximum.py | 741 | 3.53125 | 4 | from collections import deque
from typing import List
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if not nums:
return []
result = []
window = deque()
def monotonic_append_with_index(i: int) -> None:
while window and nums[window[-1]] < nums[i]:
window.pop()
window.append(i)
for i in range(k):
monotonic_append_with_index(i)
result.append(nums[window[0]])
for j in range(k, len(nums)):
if window and window[0] <= j - k:
window.popleft()
monotonic_append_with_index(j)
result.append(nums[window[0]])
return result
|
09dbff4dcbf8f90f1adc69dc52005ec78b8e2016 | cs-cordero/interview-prep | /implementations/fenwick_tree.py | 1,226 | 3.5625 | 4 | from typing import List
class FenwickTree:
def __init__(self, array: List[int]) -> None:
self._data = [0] + array[:]
for i, value in enumerate(self._data):
j = i + get_least_significant_bit_value(i)
if j < len(self._data):
self._data[j] += value
def prefix_sum(self, index: int) -> int:
result = 0
while index > 0:
result += self._data[index]
index -= get_least_significant_bit_value(index)
return result
def sum_range(self, i: int, j: int) -> int:
""" indexes are assumed to be 0-based, like the input array """
return self.prefix_sum(j + 1) - self.prefix_sum(i)
def add_to_index(self, i: int, x: int) -> None:
""" indexes are assumed to be 0-based, like the input array """
i += 1
while i < len(self._data):
self._data[i] += x
i += get_least_significant_bit_value(i)
def get_least_significant_bit_value(value: int) -> int:
return value & -value
tree = FenwickTree([3, 4, -2, 7, 3, 11, 5, -8, -9, 2, 4, -8])
assert tree._data == [0, 3, 7, -2, 12, 3, 14, 5, 23, -9, -7, 4, -11]
assert tree.sum_range(2, 6) == -2 + 7 + 3 + 11 + 5
|
86c9d2d94721f27a7f134ee3d2285b48205c57b2 | cs-cordero/interview-prep | /grokking-dp/unbounded_knapsack.py | 1,323 | 3.640625 | 4 | from typing import List
def solve_knapsack(profits: List[int], weights: List[int], capacity: int):
def helper(cap: int, current: int) -> int:
if cap < 0:
return 0
elif cap == 0:
return current
best = current
for weight, profit in zip(weights, profits):
best = max(best, helper(cap - weight, current + profit))
return best
return helper(capacity, 0)
def solve_knapsack_top_down(profits: List[int], weights: List[int], capacity: int):
memo = {}
def helper(cap: int, current: int) -> int:
key = (cap, current)
if key not in memo:
if cap < 0:
memo[key] = 0
elif cap == 0:
memo[key] = current
else:
best = current
for weight, profit in zip(weights, profits):
best = max(best, helper(cap - weight, current + profit))
memo[key] = best
return memo[key]
return helper(capacity, 0)
def main():
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 8))
print(solve_knapsack([15, 50, 60, 90], [1, 3, 4, 5], 6))
print(solve_knapsack_top_down([15, 50, 60, 90], [1, 3, 4, 5], 8))
print(solve_knapsack_top_down([15, 50, 60, 90], [1, 3, 4, 5], 6))
main()
|
714329be247af7c185050290351a46ca9d8c95c3 | IslamBojahh/ProjectRails | /week2/cw2/Q#3.py | 3,085 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 21:24:56 2019
@author: ORCAS_ISLAM
"""
#Each week you are meeting with your friends to spend some quality time together. Usually you're hanging out in a bar on Friday nights, or going out of town on Saturdays, or playing board games on Sundays. You want to simplify the process of gathering people and that's why you've decided to write a program which could automate this process.
#You should create the class Party(place) which will send the invites to all of your friends. Also you should create the class Friend and each friend will be an instance of this class.
#Sometimes the circle of friends is changing - new friends appear, the old ones disappear from your life (for example - move to another town). To form right connections you should create the Party class with the next methods:
#add_friend(Friend(name)) - add friend 'name' to the list of the 'observers' (people, which will get the invitations, when the new party is scheduled).
#del_friend(friend) - remove 'friend' from the 'observers' list.
#send_invites() - send the invites with the right day and time to the each person on the list of 'observers'.
#Class Friend should have the show_invite() method which returns the string with the last invite that the person has received with the right place, day and time. The right place - is the 'place' which is given to the Party instance in the moment of creation. If the person didn't get any invites, this method should return - "No party..."
#Examples:
#party = Party("Midnight Pub")
#nick = Friend("Nick")
#john = Friend("John")
#lucy = Friend("Lucy")
#chuck = Friend("Chuck")
#
#party.add_friend(nick)
#party.add_friend(john)
#party.add_friend(lucy)
#party.send_invites("Friday,...
People_invitation={}
class Party(object):
def __init__(self , invitation):
self.friend=[]
self.invitation=invitation
def add_friend(self ,f):
self.friend.append(f.getName())
def del_friend(self , f):
self.friend.remove(f.getName())
def send_invites(self,details):
for people in self.friend:
if people in People_invitation:
People_invitation[people].insert(0,self.invitation+''+details)
else:
People_invitation[people]=[self.invitation+''+details]
class Friend(object):
def __init__(self, name):
self.__name=name
def getName(self):
return self.__name
def show_invite(self):
if self.__name in People_invitation:
return People_invitation[self.__name][0]
else:
return "No Party"
party = Party("test2")
nick = Friend("Nick")
john = Friend("John")
lucy = Friend("Lucy")
chuck = Friend("Chuck")
party.add_friend(nick)
party.add_friend(john)
party.add_friend(lucy)
party.del_friend(nick)
party.send_invites("Friday,...")
party2 = Party("test1")
party2.add_friend(nick)
party2.add_friend(john)
party2.send_invites("Tuesday,...")
print(nick.show_invite())
print(john.show_invite())
print(lucy.show_invite())
print(chuck.show_invite()) |
8bf5ca07b63351502911b50328ca0a6eac240187 | AndrewGEvans95/foobar | /breedinglikerabbits.py | 675 | 4.125 | 4 | def BinSearch(a, b, target, parity):
#Standard binary search w/ recursion
if b <= a:
return None
n = a + ((b - a)/2)
n += parity != n & 1
S = Scan(n)
if S == target:
return n
if S > target:
b = n - 1
else:
a = n + 1
return BinSearch(a, b, target, parity)
dic = {}
def Scan(n):
if n < 3:
return [1 ,1, 2][n]
h = n/2
if n & 1:
dic[n] = Scan(h) + Scan(h - 1) + 1
else:
dic[n] = Scan(h) + Scan(h + 1) + h
set(dic)
return dic[n]
def answer(str_S):
str_S = int(str_S)
return BinSearch(0, str_S, str_S, 1) or BinSearch(0, str_S, str_S, 0)
print answer(7) |
0819ffcd81a015ea16ff6493531e4f70a635f304 | guillermd/Python | /Learning Projects Python/Ejercicios/ejercicio2.py | 1,931 | 4.34375 | 4 |
class ejercicio2():
#Escribir un programa que pregunte el nombre del usuario en la consola
# y un número entero e imprima por pantalla en líneas distintas
# el nombre del usuario tantas veces como el número introducido.
def HacerEjercicio(self):
nombre=input("Dame tu nombre:")
vueltas=input("cuantas vueltas quieres?")
for i in range(int(vueltas)):
print(nombre, "\n")
class ejercicio3():
#Escribir un programa que pregunte el nombre del usuario en la consola y
#después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras,
#donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el número de letras que tienen el nombre.
#Escribir un programa que realice la siguiente operación aritmética (3+2 partido de 2*5)elevado a 2
class ejercicio4():
#Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros), calcule el índice de masa corporal
# y lo almacene en una variable, y muestre por pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el
# índice de masa corporal calculado redondeado con dos decimales.
#Escribir un programa que pida al usuario dos números enteros y muestre por pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son los números introducidos por el usuario, y <c> y <r> son el cociente y el resto de la división entera respectivamente.
#Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión.
#Escribir un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas.
ej=ejercicio2()
ej.HacerEjercicio() |
f6715a1c40daddd7a1179a1fb98a75ba2fbeeff1 | guillermd/Python | /Learning Projects Python/Funcion Filter/filterConObjetos.py | 770 | 3.6875 | 4 | class Empleado:
def __init__(self, nombre, cargo, salario):
self.nombre=nombre
self.cargo=cargo
self.salario=salario
def __str__(self):
return "{} trabaja como {} y cobra {} €".format(self.nombre, self.cargo, self.salario)
empleadosLista=[
Empleado("juan", "director", 75000),
Empleado("Alicia", "gerente", 55000),
Empleado("Antonio", "vendedor", 45000),
Empleado("juana", "atencion", 35000),
]
#obtener lista de empleados que ganen mas de 50000
salarios_altos=filter(lambda empleado:empleado.salario>50000, empleadosLista)
for e in salarios_altos:
#print("{} trabaja como {} y cobra {} €".format(e.nombre, e.cargo, e.salario)) la funcion __str__ tiene el texto por defecto al hacer print()
print(e) |
80da56a9610f10228eb50946f440f38511dec245 | guillermd/Python | /Learning Projects Python/Basic/Bucles.py | 344 | 4.09375 | 4 | miLista=[1,2,3]
for item in miLista:
print(item)
for item in [4,5,6]:
print(item)
for i in "pepito": #recorre caracter a caracter
print(i)
for i in range(5):
print (i)
for i in range(5,15,2):
print (f"valor de i: {i}")
#(f....) =string.format
#para bucar un caracter en la lista => if(i=="X")
#tmb existe el while |
9aa52c0d2effdbcd75ae3c64d76a3af06e6a833c | guillermd/Python | /Learning Projects Python/POO/poo1.py | 745 | 3.6875 | 4 | class Coche():
###Creacion de metodo constructor
def __init__(self): #El constructor SIEMPRE se llama init
self.largo=2500
self.ancho=1000
#propiedad encapsulada (privada).- dos guiones bajos
self.__ruedas=4
self.enMarcha=True
ventanillas=6
def arrancar(self,arrancamos):
if arrancamos==True:
print("ya esta arrancado")
else:
self.enMarcha=True
miCoche=Coche()
print("Ventanillas ", miCoche.ventanillas)
print(miCoche.enMarcha)
miCoche.arrancar(miCoche.enMarcha)
print(miCoche.enMarcha)
miCoche2=Coche()
print("Largo: ", miCoche2.largo)
#print("Ruedas: ", miCoche2.__ruedas) ERROR????
miCoche2.__ruedas=6
print("Ruedas: ", miCoche2.__ruedas)
|
9bc0f38b22e60a26543a6f607b4b58bdacb28b41 | guillermd/Python | /Learning Projects Python/Basic/Tuplas.py | 649 | 4.28125 | 4 | miTupla=("item1", 18, "item3")
print(miTupla)
#busqueda de elementos
print(miTupla.index("item3"))
#Convertir una tuppla en Lista
miLista=list(miTupla)
print (miLista)
#Convertir una lista en tupla
miLista.append(7)
miTupla2=tuple(miLista)
print (miTupla2)
#buscar elementos en la tupla => in
print("item1" in miTupla)
#contar las veces que esta un elemento en la tupla
print(miTupla.count(18))
#longitud de una tupla
print(len(miTupla2))
#asignar cada item de la tupla a una variable distitna. Asigna por orden cada valor a la variable
miTupla3=("pepe", 13,3,2010)
nombre, dia, mes, anyo = miTupla3
print(nombre); print(dia);print(mes);print(anyo) |
acdaeabd1aa5057b299fb16216f538862447a481 | tangzhuochen/Python_ML_Code | /SK/sk_linear_regression.py | 2,030 | 3.546875 | 4 | from sklearn import datasets
import numpy as np
diabetes = datasets.load_diabetes()
diabetes_X_train = diabetes.data[:-20]
diabetes_X_test = diabetes.data[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
# The mean square error
print np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)
# Explained variance score: 1 is perfect prediction
# and 0 means that there is no linear relationship
# between X and y.
print regr.score(diabetes_X_test, diabetes_y_test)
X = np.c_[ .5, 1].T
y = [.5, 1]
test = np.c_[ 0, 2].T
#linear regression
regr = linear_model.LinearRegression()
import matplotlib.pyplot as plt
plt.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1 * np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
plt.plot(test, regr.predict(test))
plt.scatter(this_X, y, s=3)
#ridge regression
#the larger the ridge alpha parameter, the higher the bias and the lower the variance
regr = linear_model.Ridge(alpha=.1)
plt.figure()
np.random.seed(0)
for _ in range(6):
this_X = .1 * np.random.normal(size=(2, 1)) + X
regr.fit(this_X, y)
plt.plot(test, regr.predict(test))
plt.scatter(this_X, y, s=3)
#lasso regression
alphas = np.logspace(-4, -1, 6)
regr = linear_model.Lasso()
scores = [regr.set_params(alpha=alpha).fit(diabetes_X_train, diabetes_y_train).score(diabetes_X_test, diabetes_y_test) for alpha in alphas]
best_alpha = alphas[scores.index(max(scores))]
regr.alpha = best_alpha
regr.fit(diabetes_X_train, diabetes_y_train)
print(regr.coef_)
#logistic regression
logistic = linear_model.LogisticRegression(C=1e5)
logistic.fit(iris_X_train, iris_y_train)
#The C parameter controls the amount of regularization in the LogisticRegression object: a large value
#for C results in less regularization. penalty="l2" gives Shrinkage (i.e. non-sparse coefficients), while
#penalty="l1" gives Sparsity
|
12ed374366709b8dbddf4034ca3cb6fad14718f5 | htmercury/codingDojoAssignments | /python_stack/python_OOP/math_dojo.py | 888 | 3.609375 | 4 | import unittest
class Math_Dojo:
def __init__(self):
self.result = 0
def add(self, *x):
self.result += sum(x)
return self
def subtract(self, *x):
self.result -= sum(x)
return self
class Math_Dojo_Tests(unittest.TestCase):
def setUp(self):
# add the setUp tasks
print("running setUp")
self.md = Math_Dojo()
def test_basic(self):
x = self.md.add(2).add(2,5,1).subtract(3,2).result
return self.assertEqual(x, 5)
def test_1(self):
x = self.md.subtract(3,2).result
return self.assertEqual(x, -5)
def test_2(self):
x = self.md.add(2).add(0,1,1).add(3).result
return self.assertEqual(x, 7)
def test_3(self):
x = self.md.add(0).subtract(0).result
return self.assertEqual(x, 0)
if __name__ == "__main__":
unittest.main() |
7ccff781110f6a1cdefcda48c00fca3c9be5e0b6 | AbrahamCain/Python | /PasswordMaker.py | 1,501 | 4.375 | 4 | #Password Fancifier by Cyber_Surfer
#This program takes a cool word or phrase you like and turns it into a decent password
#you can comment out or delete the following 3 lines if using an OS other than Windows
import os
import sys
os.system("color e0") #It basically alters the colors of the terminal
#Enter a password and store it in the variable "word"
word = input("Give me a word/phrase to turn into a password of at least 10 characters please:\n\n--->")
word = word.lower()
#check the length of the password/phrase
count = len(word)
if count >= 10:
for i in word:
if "e" in word:
word = word.replace("e", "3") #replace e's with 3's
if "a" in word:
word = word.replace("a", "@") #replace a's with @'s
if "s" in word:
word = word.replace("s", "$") #replace s's with $'s
word = word.title() #make the first letter of words uppercase
#make 3 other options for passwords if the environment doesn't allow spaces, underscores, or dashes
underscore = word.replace(" ", "_")
tac = word.replace(" ", "-")
nospace = word.replace(" ", "")
#print results
print("Here are four different options:")
print("1.",word)
print("2.",underscore)
print("3.",tac)
print("4.",nospace)
#Let user know the password is too short
else:
print("That password is too short. Try something over 10 characters next time.")
#End/Exit the program
input("Press ENTER To Exit")
exit(0)
|
8a729dff999346c9f4508fbe6f0c3e37ae8edf20 | AbrahamCain/Python | /Tab Opener.py | 2,092 | 3.65625 | 4 | #my basic dashboard CLI for opening tabs
#utilizes the following modules:
#webbrowser.open(url, new=1,2, 0r 3)
#time.sleep(# of seconds)
import webbrowser
import time
import sys
import os
#adust cmd.exe colors
os.system("color 3")
tabs = []
end = False
#display options
print("""
Here is a list of websites I can open up for you:
1. frederick.blackboard.com
2. hackthebox.eu
3. bugcrowd.com
4. netacad.com
5. overthewire.org
6. Other
""")
#make a loop to determine how many tabs are needed
done = "NO"
while done == "NO":
num = int(input("How many tabs do you need?:\t"))
done = input("Are you sure? YES or NO:\t")
done = done.upper()
if done == "YES" or done == "Y":
break
else:
None
#make a valid list of options
valid = [1,2,3,4,5,6]
for i in range(1, num++1):
print("""
Here is a list of websites I can open up for you. Please select one of the following:
1. frederick.blackboard.com
2. hackthebox.eu
3. bugcrowd.com
4. netacad.com
5. overthewire.org
6. Other
""")
option = int(input("Please present option as a single digit number---->"))
#make sure option is valid and let them enter a URL if not
if option not in valid:
print("That isn't a valid option, so we chose 6 for you.")
option = 6
tabs.append(option) #add the option to a list
#Start opening the tabs or if option 6, allow them to specify a URL
for i in tabs:
if i == 1:
webbrowser.open("frederick.blackboard.com", new=1)
elif i == 2:
webbrowser.open("hackthebox.eu/login", new=1)
elif i == 3:
webbrowser.open("bugcrowd.com/user/sign_in", new=1)
elif i == 4:
webbrowser.open("netacad.com/saml_login", new=1)
elif i == 5:
webbrowser.open("overthewire.org", new=1)
elif i == 6:
url = str(input("Please enter the exact URL you would like to enter---->"))
webbrowser.open(url, new=2)
else:
print("Something went wrong")
time.sleep(5) #add a 5 second delay to load pages
#end of program
input("Press ENTER To Exit")
exit(0)
|
6d528e812305c5865562757bfbb5cbf244abbebd | Autumn-Chrysanthemum/complete-python-bootcamp | /Python-Object-and-Data-Structure-Basics/Section_6/args_kwargs.py | 1,323 | 3.875 | 4 | # argument and key-word arguments
def myfunc(a,b):
return sum((a,b))*0.05
print(myfunc(40,60)) # positional arguments because 40 is assing to a, and 60 is assing to 60
def myfunc(a,b,c=0,d=0):
return sum((a,b,c,d))*0.05
print(myfunc(40,60,100))
def myfunc(*args): # name can be anything *args = *natalia = *spam, by convention use *args
print(args) # all parameters will be a tuple
return sum(args)*0.05
print(myfunc(34,67,34,234))
def myfunc(**kwargs): # name can be anything *kwargs = *natalia = *spam, by convention use *kwargs
print(kwargs) # return back a dictionary
if 'fruit' in kwargs:
print("My fruit of chose is: {}".format(kwargs['fruit']))
else:
print("I did not fund any fruit here")
myfunc(fruit="apple", veggie = "avocado")
def myfunc(*args,**kwargs): # have to be the same order as we define
print(args)
print(kwargs)
print('I would like {} {}'.format(args[0],kwargs['food']))
myfunc(10,30,50, fruit="orange", food="eggs", animal = 'dog') # have to be the same order as we define, do not mix
def mynum(mystring):
new_string = ''
for item in enumerate(mystring):
if item[0]%2==0:
new_string += item[1].upper()
else:
new_string += item[1].lower()
print(new_string)
mynum("asdfghjkl")
|
74a3dd1a7ec3f71e4dd641f42e22738c989128d4 | Autumn-Chrysanthemum/complete-python-bootcamp | /Python-Object-and-Data-Structure-Basics/Section_5/If_elif_else.py | 635 | 4.125 | 4 | # control flow
# if some_condition:
# execute some code
# elif some_other_condition:
# do something different
# else:
# do something else
if True:
print("It is True")
hungry = True
if hungry:
print("feed me")
else:
print("i not hungry")
location = "Bank"
if location == "Auto Shop":
print("Cars are cool")
elif location == "Bank":
print("Money is cool")
elif location == "Store":
print("Let go shopping")
else:
print("I don not know much")
name = "Samy"
if name == "Natalia":
print("hello Natalia")
elif name == "Samy":
print("hello Samy")
else:
print("what is your name? ") |
4b4c8fbcccaa8ea4644346160e4a4739eaf11b35 | Roast-Lord/PythonTeXScripts | /Matrices/printsym.py | 1,545 | 4.0625 | 4 | # This function prints a symbolic matrix.
#Don't forget to use the amsmath package by writing \includepackage{amsmath} in your document preamble.
def newterm(j, size):
# This is an auxiliar function that chooses whether or not to print '&' after a new term of the matrix.
if (j < size):
print(end=r"& ")
def printsym(nl, nc=1, sym='a', t='b'):
#This function only needs 1 argument 'nl' which is the number of lines in the matrix.
#This function receives a number of lines 'nl' and a number of columns 'nc', a symbol 'sym' and a LaTeX matrix style 't'.
#The parameter 'sym' is any string you want for a symbolic variable.
#The style 't' can be: '' for plain matrix, 'b' for square brackets matrix, 'B' for curly brackets matrix, 'v' for pipes matrix, 'V' for double pipes matrix and 'small' for small matrix.
#By default if 'nc', 'sym and 't' are no especified, the function will print a collum matrix with the symbol 'a' and LaTeX square brackets matrix style.
matrix_style = '{' + t + 'matrix' + '}'
print(end=r"\begin")
print(matrix_style)
for i in range(1, nl+1):
for j in range(1, nc+1):
if(nl == 1):
print(end='%s_{%i} ' % (sym, j))
newterm(j, nc)
else:
if(nc == 1):
print(end='%s_{%i} ' % (sym, i))
else:
print(end='%s_{%i%i} ' % (sym, i, j))
newterm(j, nc)
print(r"\\")
print(end=r"\end")
print(matrix_style)
|
0f679c78696c3d221458ece5c214502f58449c9d | GuillermoDeLaCruz/python--version3 | /name.py | 726 | 4.4375 | 4 |
#
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
# Combining or Concatenating Strings
# Python uses the plus symbol (+) to combine strings
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
#1
favorite_language = 'python '
print(favorite_language)
favorite_language.rstrip()
print(favorite_language)
#2 rstrip() removes whitespaces from the right
# lstrip() from left
# strip() from both
favorite_language = favorite_language.rstrip()
print(favorite_language)
|
a50c2f85ed149af29cd69ce9e5b974768a0507e8 | GuillermoDeLaCruz/python--version3 | /great_magicians.py | 381 | 3.890625 | 4 | names = ['aaa', 'bbbb', 'cccc', 'dddd', 'eeeeeee']
great = []
def show_magicians(list):
"""
"""
while list:
current_item = list.pop()
print(current_item)
def make_great(list, great):
while list:
current_item = "Great " + list.pop()
great.append(current_item)
make_great(names[:], great)
show_magicians(great[:])
|
7befde83f96f5cbc393b0d28d3e4a8feba2c4767 | GuillermoDeLaCruz/python--version3 | /hello_admin.py | 296 | 3.765625 | 4 | usernames = ['apple_27', 'guyonwheels21', 'admin', 'jellybean', 'bananas_23']
for username in usernames:
if username == 'admin':
print("Hello admin, would you like to see a staus report?")
else:
print("Hello " + username + ", thank you for loging in again.")
|
1dc74c9fee351c9f21c2f75d05a56bc26859c8cd | GuillermoDeLaCruz/python--version3 | /magicians.py | 211 | 3.921875 | 4 | names = ['aaa', 'bbbb', 'cccc', 'dddd', 'eeeeeee']
def show_magicians(list):
"""
"""
while list:
current_item = list.pop()
print(current_item)
show_magicians(names[:])
|
3ddf3f2e83be93c7fa3b7df0e7214b8abb6443cd | GeVhoo/python-project-lvl1 | /brain_games/games/prime.py | 505 | 3.828125 | 4 | from random import randint
from math import sqrt
DESCRIPTION = 'Answer "yes" if given number is prime. Otherwise answer "no".'
def is_prime(number):
if number % 2 == 0:
return number == 2
d = 3
sqrt_number = sqrt(number)
while d <= sqrt_number and number % d != 0:
d += 2
return d > sqrt_number
def get_conditions():
number = randint(2, 100)
question = number
correct_answer = 'yes' if is_prime(number) else 'no'
return (question, correct_answer)
|
d7cd4cc71be5bf275300d36bf4dbc8d2de4d118e | Qannaf/Python | /heritage.py | 1,212 | 3.953125 | 4 | #coding:utf-8
#voila mon 13émé code en python pass si il y a pas un constructeur
#class mere
class Vehicule :
def __init__(self,nom,peneau):
self.nom = nom
self.peneau = peneau
def se_deplacer (self):
print("la vehicule {} est deplacer...".format(self.nom))
#class fille
class Voiture(Vehicule):
def __init__(self,nom,m_peneau,vitesse):
Vehicule.__init__(self,nom,m_peneau)
self.vitesse = vitesse
class Avion(Vehicule):
def __init__(self,nom,m_peneau,voyage):
Vehicule.__init__(self,nom,m_peneau)
self.voyage = voyage
#prgm principale
v1 = Vehicule("Taxi",31)
v1.se_deplacer()
print(v1.peneau,"Voila")
v2 = Voiture("Toyota",16,220)
v2.se_deplacer()
print(v2.vitesse,"Voila")
v3 = Avion("Airbus",3,"Yémen")
v3.se_deplacer()
print("Sana'a",v3.voyage)
#vérification la class de l'objet
if isinstance(v3,Vehicule):
print("v2 est une Véh")
if isinstance(v3,Avion):
print("v2 est une Véh")
#verification l'héritage
if issubclass(Avion,Vehicule):
print("Avion hérite Vehicule ")
#héritage multiple
class Etudiant :
pass
class Enseignant:
pass
class Doctorant(Etudiant,Enseignant):
pass
|
2021b8cc8a1d42cc16e2d5d6e6849f8641ea0d43 | Qannaf/Python | /gestion_erreurs.py | 836 | 4.0625 | 4 | #coding:utf-8
"""
voila mon 8éme code en python les variables
"""
age = input("Quels age as-tu ? ")
try:
age = int(age)
except:
print("l'age indiqué est c'est pas un nombre !")
else:
print("Tu as {} ans".format(age))
finally:
print("fin de programme !")
#mieux comprandre try
n1 = 150
n2 = input("entrer n2 = ")
try:
n2 = int(n2)
except ValueError:
print("valeur incorrecte")
except ZeroDivisionError:
print("Vous ne pouvez pas divider par zéro")
else:
print("Bravo, tu as noté un nbr valide")
print("Résultats = {}/{} = {}".format(n1,n2,int(n1/n2)))
finally:
print("Fin du programme...")
#pas important
try:
age = int(input("Quels age as-tu ? "))
assert age > 25 #je veux que age soit > 25
except AssertionError:
print("je veux que age soit > 25")
|
57d5a8c2dfc81b0908abe7504e8a417d9fcdd89b | Qannaf/Python | /gestion_dates.py | 631 | 3.625 | 4 | #coding:utf-8
import datetime
from datetime import date
''' =============== pgm ============= '''
d1 = datetime.datetime(2019, 12, 29, 7, 59, 58)
d2 = datetime.datetime(2019, 12, 30, 7, 59, 58)
if d1<d2:
print("d1 est plus ancien que d2")
else:
print("d1 est plus récent que d2")
"""" =========================="""
d1 = datetime.date(2019, 12, 29)
print(d1.year)
print(type(d1))
d1 = datetime.time(20, 12, 29)
print(d1)
print(type(d1))
#=================
print(date.today())
now = date.today()
date_de_naissance = datetime.date(1992,5,6)
print("{} ans".format(now.year - date_de_naissance.year)) |
09c7e37e018aca4322c8c2a904c40d04753758f6 | game-Tnadon/-1 | /Lab4.py | 785 | 3.71875 | 4 | def minimumCheck(applyList):
minWage = applyList[0][0]
minPpl = 1
jobPref = 1
for i in range(len(applyList)):
pplWage = applyList[i][0]
pplJob = 1
for j in range(len(applyList[i])):
if applyList[i][j]<minWage:
minWage = applyList[i][j]
minPpl = i+1
jobPref = j+1
if applyList[i][j]<pplWage:
pplWage = applyList[i][j]
pplJob = j+1
print("Minimum in People No.",i+1," is ",pplWage,"In job : ",pplJob)
return print("Minimum in person No.",minPpl,"Minimum wage = ",minWage,"In job : " ,jobPref)
applyList = [[20,25,22,28],[15,18,23,17],[19,17,21,24],[58,23,24,24]]
print(minimumCheck(applyList)) |
1f5845dcbaef25a1d88fb4a6f211547eca7679a3 | game-Tnadon/-1 | /lad7.py | 993 | 3.59375 | 4 | #62055008
import math
class Circle2D:
def __init__(self,r):
self.__rad = r
@property
def rad(self):
return self.__rad
@rad.setter
def rad(self, r): self.__rad = r
def computerArea(self):
return math.pi*self.__rad**2
def computerCircumferrence(self):
return 2* math.pi*self.__rad
class Circle3D(Circle2D):
def __init__(self,r,col):
super().__init__(r)
self.__color = col
@property
def color(self):
return self.__color
@color.setter
def color(self, col):
self.__color = col
def spehereVolume(self):
return 4/3 * math.pi* b2.rad**3
c1 = Circle2D(4)
print('1','=',c1.rad)
c1.rad = 5
print('2','=',c1.rad)
print('3','=',c1.computerArea())
print('4','=',c1.computerCircumferrence())
b2 = Circle3D(2,'red')
print('5','=',b2.color)
b2.color = 'Black'
print('6','=',b2.color)
print('7','=',b2.spehereVolume()) |
78cc76b9d85d6e53bc725e7bc99e364e98883fc0 | abhijitmamarde/py_notebook | /programs/exception_handling_demo.py | 1,035 | 3.84375 | 4 | class MessageLengthError(Exception):
def __init__(self, msg):
super().__init__(msg)
def hello(msg):
if len(msg) < 3:
# raise Exception("Length of msg should be >= 3")
raise MessageLengthError("Length of msg should be >= 3")
print("Hello " + msg)
hello("world")
obj = 123
try:
hello(obj)
except TypeError as err:
print("Error occured, handled...")
hello(str(obj))
obj = "hi"
try:
hello(obj)
# except TypeError as err:
# print("Error occured, handled...")
# hello(str(obj))
# except MessageLengthError as err:
# print("MessageLengthError occured:", err)
except Exception as err:
print("Exception occured:", err)
else:
print("After try - 1")
finally:
print("Ok done, this part! - 1")
obj = "hey there"
try:
hello(obj)
except TypeError as err:
print("Error occured, handled...")
hello(str(obj))
except Exception as err:
print("Exception occured:", err)
else:
print("After try - 2")
finally:
print("Ok done, this part! - 2")
print("Last line of prgoram") |
1baa2deb1b490cf11b6e658be4f101ae914e6588 | abhijitmamarde/py_notebook | /programs/overload_opertor_user_types.py | 1,877 | 3.9375 | 4 | class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __lt__(self, p2):
if isinstance(p2, Point):
print("Point(%d, %d) < Point(%d, %d)" % (self.x, self.y, p2.x, p2.y))
if (self.x <= p2.x) and (self.y <= p2.y):
return True
else:
return False
elif isinstance(p2, Point3D) and (self.x <= p2.x) and (self.y <= p2.y):
print("Point(%d, %d) < Point3(%d, %d, %d)" % (self.x, self.y, p2.x, p2.y, p2.z))
return True
elif isinstance(p2, int) and (self.x <= p2):
print("Point(%d, %d) < Int(%d)" % (self.x, self.y, p2))
return True
elif isinstance(p2, tuple) and (len(p2) >= 2) and (self.x <= p2[0]) and (self.y <= p2[1]):
print("Point(%d, %d) < Tuple(%d, %d)" % (self.x, self.y, p2[0], p2[1]))
return True
print("Point '<' defult False ")
return False
class Point3D:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __lt__(self, p2):
if isinstance(p2, Point3D) and (self.x <= p2.x) and (self.y <= p2.y) and (self.z <= p2.z):
return True
elif isinstance(p2, Point) and (self.x <= p2.x) and (self.y <= p2.y):
return True
elif isinstance(p2, int) and (self.z <= p2):
return True
elif isinstance(p2, tuple) and (len(p2) >= 3) and (self.x <= p2[0]) and (self.y <= p2[1]) and (self.z <= p2[2]):
return True
return False
p2d_1 = Point(10,21)
p2d_2 = Point(12,22)
p3d_1 = Point3D(10,21,20)
p3d_2 = Point3D(12,22,40)
print(p2d_1 < p2d_2)
print(p2d_2 < p2d_1)
print(p2d_1 < 12)
print(p2d_2 < 10)
print(p2d_1 < (12, 22))
# print(p3d_1 < p3d_2)
# print(p3d_2 < p3d_1)
print(p2d_1 < p3d_1)
print(p3d_1 < p2d_1) |
e1bd57bab74bb6de441abf31e60cbc1b0f62e5cc | abhijitmamarde/py_notebook | /programs/finally_else_exception_handling.py | 708 | 3.5 | 4 | class FailedError(Exception):
def __init__(self):
super().__init__()
class ExcellentError(Exception):
def __init__(self):
super().__init__()
def calc_grade(n1,n2,n3):
avg = int((n1 + n2 + n3)/3)
if avg == 0:
raise FailedError()
if avg >= 75:
raise ExcellentError()
if True:
try:
calc_grade(0,0,0)
except FailedError:
print("Failed!")
except ExcellentError:
print("Excellent")
except Exception:
print("Some unknow exception occured")
else:
print("No error occured? condition not handled")
finally:
print("Great, now lets calculate your total!")
print("....END....")
|
8452809dcba1877adc24cdf9a254e12f52ad285f | abhijitmamarde/py_notebook | /programs/super_class_inheritance_new.py | 674 | 3.71875 | 4 | class A(object):
def __init__(self):
self.n1 = 1
self.n2 = 2
print('A.__init__')
super().__init__()
def comm(self):
print("A.comm()")
class B(object):
def __init__(self):
self.n3 = 3
self.n4 = 4
print('B.__init__')
super().__init__()
def comm(self):
print("B.comm()")
class C(B, A):
def __init__(self):
self.z = 100
print('C.__init__')
super().__init__()
def show(self):
print("4 nums are: %d %d %d %d" % (self.n1, self.n2, self.n3, self.n4))
c = C()
c.show()
c.comm()
print(C.__mro__)
# for c in C.mro():
# print(c.__name__) |
741bf635cffb29fe1c30c23b9516cc1d77ea00af | abhijitmamarde/py_notebook | /programs/class_str_repr_methods.py | 558 | 4.1875 | 4 |
class Point:
'''Defines simple 2D Points'''
def __init__(self):
self.x = 10
self.y = 20
def __str__(self):
return "Point(x=%d, y=%d)" % (self.x, self.y)
def __repr__(self):
return "P(x=%d, y=%d)" % (self.x, self.y)
def show(self, flag, capital):
'''prints the object on command line'''
print(self.x, self.y)
p = Point()
p.show()
p = Point()
print(p)
print("Point p is:", p)
print("Point p is: %s" % p)
print("Point p: %s" % repr(p))
s1 = "Point is:" + str(p)
print(s1)
print(p.__doc__) |
2b435f5ee04586b845397c3379351c5e24fc4a8e | abhijitmamarde/py_notebook | /programs/list_demos.py | 1,734 | 3.9375 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
# a=[1,[2,[3,[4,[5,[6]]]]]]
a = [
1,
[
2,
[
3,
[
4,
[
5,
[6]
]
]
]
]
]
print(a)
#first element
print(a[0])
print(a[1][1][1][1][1][0])
print("The length is:",len(a))
a = [[1,2,3],[4,5,6],[7,8,9]]
print(a)
print("The length is:",len(a))
# b = [1,2,3,4,5]
# b = 1+2+3 + 2+3+4 + 3+4+5
# print b
print('-'*30)
# to get Help on list object
# >>> help([])
vowels1 = ['a', 'e', 'i', 'o', 'u']
vowels2 = list('aeiou')
print(vowels1)
print(vowels2)
print(vowels1 == vowels2)
vowels1.append('z')
print(vowels1)
print(vowels1 == vowels2)
print(len(vowels1))
vowels1.clear()
print(vowels1)
print(len(vowels1))
# list is mutable, string is not
print('-'*30)
l1 = [1,2,3]
l2 = l1
print(id(l1))
print(id(l2))
l1[0] = 10
print(l1)
print(l2)
# string is not mutable
s1 = "abhi"
s2 = s1
print(s1)
print(s2)
print(id(s1))
print(id(s2))
s1 += "!"
print(s1)
print(s2)
print(id(s1))
print(id(s2))
print('-'*30)
print(id(vowels1))
print(id(vowels2))
vowels1 = vowels2.copy()
print(vowels1)
print(id(vowels1))
print(id(vowels2))
# count(), extend() usage
print('-'*30)
l1 = [1,2,3,3,4,2,1,4,3,1]
l2 = ['a', 'b', 'c']
print(l1.count(1))
# append is not similar to extend
# l1.append(l2)
# this would yield same o/p
l1.extend(l2)
# l1.extend('abc')
# l1 += 'abc'
print(l1)
print(l1.index(3))
l1 = list('abc')
print(l1)
print(len(l1))
print(id(l1))
print(l1.pop())
print(l1)
print(len(l1))
print(id(l1))
# usage of reverse(), sort(), sorted() |
30127c36f55f6f3afa442575ee0ec738f29b87b4 | Treycinayara510/forca | /Treyci-forca.py | 5,322 | 3.9375 | 4 | # O comando import rondom, está importando uma biblioteca para sortear uma palavra aleatória.
import random
# Foi atribuida à variável palavras, uma lista de palvras que irão ser sortedas para o jogo.
palavras = []
# Nessa variável as letras que o jogador digitar e não conter na palavra, ficam salvas nessa variável.
letrasErradas = ''
# Nessa variável as letras que o jogador digitar e conter na palavra, ficam salvas nessa variável.
letrasCertas = ''
FORCAIMG = ['''
+---+
| |
|
|
|
|
=========''','''
+---+
| |
O |
|
|
|
=========''','''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
/| |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
|
=========''','''
+---+
| |
O |
/|\ |
/ |
|
=========''','''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
def receberPalavra():
while True:
receber = input('Qual palavra você deseja sortear?')
palavras.append(receber)
if receber == '':
break
def principal(): # def - Define funções. Nesse caso está definindo a principal função do jogo.
"""
Função Princial do programa
"""
receberPalavra()
print('F O R C A') # print imprimi na tela o argumento passado à ele.
palavraSecreta = sortearPalavra() # Essa variável recebe a função do sortearPalavra.
palpite = '' # Variáriavel atribuida para a letra escolhida pelo jogador.
desenhaJogo(palavraSecreta,palpite)
while True: # Enquanto for verdade vai sempre ficar rodando essa condição
palpite = receberPalpite() # Variável palpite recebe a função receberPalpite.
desenhaJogo(palavraSecreta,palpite)
# if é um comando condicional.
if perdeuJogo():
print('Voce Perdeu!!!')
break
# break é a condição para, se fizer a condição anterior parar o jogo.
if ganhouJogo(palavraSecreta):
print('Voce Ganhou!!!')
break
def perdeuJogo(): # Aqui está definindo a função perdeuJogo.
global FORCAIMG # torna global a variável, para dizer que ela é a mesma usada anterior.
if len(letrasErradas) == len(FORCAIMG): # len - lê o número de caracteres.
return True # Forma de retornar dados quando a condição for verdadeira.
else: # É execultado se o if anterior for falso.
return False # Forma de retornar dados quando a condição for falsa.
def ganhouJogo(palavraSecreta): # Aqui está definindo a função ganhouJogo.
global letrasCertas # dizer que letrasCartas é a mesma que já foi mensionada antes.
ganhou = True # para dizer se a o que diz na variável é verdade.
for letra in palavraSecreta: # for gera um loop dentro de uma lista e o in indica em qual lista ocorrerá.
if letra not in letrasCertas: # letra não está dentro da lista letrasCartas.
ganhou = False # para dizer se o que diz na variável é falso.
return ganhou # Forma para retornar à variável ganhou.
def receberPalpite(): # Aqui está definindo a função receberPalpite.
palpite = input("Adivinhe uma letra: ") # Pedir para o jogador digitar uma letra.
palpite = palpite.upper() # colocar palpite em maiúsculo.
if len(palpite) != 1: # dizer que se palpite tiver mais de uma letra, imprimir na tela que é para digitar apenas uma letra.
print('Coloque um unica letra.')
elif palpite in letrasCertas or palpite in letrasErradas: # se a letra já tiver sido digitada, imprimi na tela que o jogador já disse essa letra.
print('Voce ja disse esta letra.')
elif not "A" <= palpite <= "Z": # se o jogador não digitar letras que estiver entre o A e o Z, pedir para ele digitar apenas letras.
print('Por favor escolha apenas letras')
else:
return palpite # retornar para a variável palpite.
def desenhaJogo(palavraSecreta,palpite): # definir a função desenhaJogo.
# dizer que essas variáveis são as mesmas comentadas acima.
global letrasCertas
global letrasErradas
global FORCAIMG
print(FORCAIMG[len(letrasErradas)]) # imprimir na tela o que está dento dessas variáveis.
vazio = len(palavraSecreta)*'-' # colocar um _ para cada letra da palavra sorteada.
if palpite in palavraSecreta: # se a letra digitada estiver correta adicionar ela na variável letrasCertas.
letrasCertas += palpite
else:
letrasErradas += palpite # se a letra digitada estiver errada adicionar ela na variável letrasErradas.
for letra in letrasCertas:
for x in range(len(palavraSecreta)):
if letra == palavraSecreta[x]:
vazio = vazio[:x] + letra + vazio[x+1:]
print('Acertos: ',letrasCertas ) # Imprime na tela as letras que forem certas.
print('Erros: ',letrasErradas) # Imprime na tela as letras que forem erradas.
print(vazio)
def sortearPalavra():
global palavras
return random.choice(palavras).upper() # Retorna no random com a função choice e escolhe uma palavra da lista da variável palavra. Upper deixa em maiúsculo.
principal()
|
f841f92cb177b6123adc3c8db14ecd6680078069 | annabaig2023/Madlibs | /main.py | 521 | 4.28125 | 4 | # string concatenation
# swe = "Anna Baig"
# print (swe + " likes to code")
# # print (f"{swe} likes to code")
# # print ("{} likes to code".format(swe))
swe = input("Name: ")
adj = input("Adjective: ")
verb1 = input("Verb: ")
verb2 = input("Verb: ")
famous_person = input("Famous person: ")
madlib = ("Hi! My name is " + swe + ". Computer programming is so " + adj + "! It makes me so excited all the time because I love to " + verb1 + "! Stay hydrated and " + verb2 + " like you are " + famous_person)
print(madlib)
|
ad8ad997ed8f9103cff43928d968f78201856399 | kevyo23/python-props | /what-a-birth.py | 1,489 | 4.5 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# what-a-birth.py - simple birthday monitor, check and add birthdays
# Kevin Yu on 28/12/2016
birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}
all_months = 'January February March April May June July August September October November December'
while True:
print('Enter a name: (blank to quit)')
name = raw_input()
if name == '':
break
if not name.isalpha():
print ('Invalid name entered - must contain letters only, eg Daniel')
continue
name = name.title()
if name in birthdays:
print(name + ' has a birthday on ' + birthdays[name])
else:
print('No birthday record found for ' + name)
print('What month is ' + name + '\'s birthday?')
while True:
print('Enter a month:')
month = raw_input()
if not name.isalpha() or month.title() not in all_months:
print('Invalid month entered - must contain letters only, eg January')
continue
break
month = month.title()
month = month[:3]
while True:
print('Enter a date:')
date = raw_input()
if not date.isdigit() or int(date) < 1 or int(date) > 31:
print('Invalid date entered - must contain numbers only, eg 21')
continue
break
birthdays[name] = month + ' ' + date
print ('Birthday database updated.')
|
4b591002cba5476b7c691657f0f34eb2a154690e | ffcccc/MachineLearning | /preProcess.py | 3,766 | 4.09375 | 4 | import numpy as np
import sys
'''
Function: Normalization
Description: Normalize input data. For vector x, the normalization process is given by
normalization(x) = (x - min(x))/(max(x) - min(x))
Input: data dataType: ndarray description: input data
Output: normdata dataType: ndarray description: output data after normalization
'''
def Normalization(data):
# get the max and min value of each column
minValue = data.min(axis=0)
maxValue = data.max(axis=0)
diff = maxValue - minValue
# normalization
mindata = np.tile(minValue, (data.shape[0], 1))
normdata = (data - mindata) / np.tile(diff, (data.shape[0], 1))
return normdata
'''
Function: Standardization
Description: Standardize input data. For vector x, the normalization process is given by
Standardization(x) = x - mean(x)/std(x)
Input: data dataType: ndarray description: input data
Output: standarddata dataType: ndarray description: output data after standardization
'''
def Standardization(data):
# get the mean and the variance of each column
meanValue = data.mean(axis=0)
varValue = data.std(axis=0)
standarddata = (data - np.tile(meanValue, (data.shape[0], 1))) / np.tile(varValue, (data.shape[0], 1))
return standarddata
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: x1 dataType: ndarray description: input vector
x2 dataType: ndarray description: input vector
Output: d dataType: float description: distance between input vectors
'''
def calculateDistance(distance_type, x1, x2):
if distance_type == "Euclidean":
d = np.sqrt(np.sum(np.power(x1 - x2, 2), axis=1))
elif distance_type == "Cosine":
d = np.dot(x1, x2)/(np.linalg.norm(x1)*np.linalg.norm(x2))
elif distance_type == "Manhattan":
d = np.sum(x1 - x2)
else:
print("Error Type!")
sys.exit()
return d
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: input dataType: ndarray description: input vector
traind_ata dataType: ndarray description: data for training
train_label dataType: ndarray description: labels of train data
k dataType: int description: select the first k distances
Output: prob dataType: float description: max probability of prediction
label dataType: int description: prediction label of input vector
'''
# def calculateDistance(input, train_data, train_label, k):
# train_num = train_data.shape[0]
# # calcuate the distances
# distances = np.tile(input, (train_num, 1)) - train_data
# distances = distances**2
# distances = distances.sum(axis=1)
# distances = distances**0.5
# # get the labels of the first k distances
# disIndex = distances.argsort()
# labelCount = {}
# for i in range(k):
# label = train_label[disIndex[i]]
# labelCount[label] = labelCount.get(label, 0) + 1
# prediction = sorted(labelCount.items(), key=op.itemgetter(1), reverse=True)
# label = prediction[0][0]
# prob = prediction[0][1]/k
# return label, prob
'''
Function: calculateAccuracy
Description: show detection result
Input: test_data dataType: ndarray description: data for test
test_label dataType: ndarray description: labels of test data
Output: accuracy dataType: float description: detection accuarcy
'''
def calculateAccuracy(test_label, prediction):
test_label = np.expand_dims(test_label, axis=1)
# prediction = self.prediction
accuracy = sum(prediction == test_label)/len(test_label)
return accuracy
|
dc5b049c6635da54baaa0f9246d722aa090cf8f6 | HelenMaksimova/python_lessons | /lesson_4/lesson_4_5.py | 768 | 4.15625 | 4 | # Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
from functools import reduce
start_list = [elem for elem in range(100, 1001) if elem % 2 == 0]
print(f'Список чётных чисел от 100 до 1000:\n{start_list}')
product_list = reduce(lambda num_1, num_2: num_1 * num_2, start_list)
print(f'Произведение всех чисел в списке равно: {product_list}')
|
096fdfcc98881c90cf16a3761c6df9d3122dbdaa | HelenMaksimova/python_lessons | /lesson_7/lesson_7_2/core.py | 3,619 | 3.859375 | 4 | import tkinter as tk
from tkinter import messagebox
from clothes import Clothes
# константы для графического интерфейса
WIN_SIZE = '530x420'
WIN_TITLE = 'Расход ткани'
MAIN_FONT = 'arial 14'
ENTER_FONT = 'arial 16'
def add_position(name, value):
"""
Добавляет позицию в список одежды
"""
clothes.add_clothes(name, value)
list_clothes.delete(0, 'end')
for elem in clothes.clothes_list:
list_clothes.insert('end', elem)
def delete_position():
"""
Удаляет выделенную позицию из списка одежды
"""
if list_clothes.curselection():
idx = list_clothes.curselection()[0]
clothes.clothes_list.remove(clothes.clothes_list[idx])
list_clothes.delete(list_clothes.curselection())
def calculate():
"""
Производит расчёт суммарного расхода ткани на все позиции из списка одежды и выводит сумму в метку
"""
result = round(clothes.clothes_tissue_consumption(), 2)
label_answer.configure(text=str(result))
def if_error(name, parameter):
"""
Проверяет корректность введённых данных
"""
try:
size = float(parameter)
add_position(name, size)
except ValueError:
messagebox.showerror('Ошибка ввода данных', 'Необходимо ввести размер или рост в виде числа!')
parameter_text.delete(0, 'end')
# создание объекта класса, с которым и будет работать программа
clothes = Clothes()
# создание графического интерфейса
root = tk.Tk()
root.title(WIN_TITLE)
root.geometry(WIN_SIZE)
root.grid()
main_frame = tk.Frame(root, borderwidth=2)
main_frame.grid(padx=20, pady=20)
list_clothes = tk.Listbox(main_frame, width=20, font=MAIN_FONT)
list_clothes.grid(rowspan=4, column=0)
scrollbar = tk.Scrollbar(main_frame)
scrollbar.grid(row=0, rowspan=4, column=0, sticky='nse')
list_clothes.configure(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_clothes.yview)
button_calc = tk.Button(main_frame, text='Рассчитать', width=20, font=MAIN_FONT, command=calculate)
button_calc.grid(row=4, column=0, pady=20)
label_answer = tk.Label(main_frame, text='0', font=MAIN_FONT, width=20, height=2, bd=2, relief='ridge')
label_answer.grid(row=5, column=0, pady=10)
label_text = tk.Label(main_frame, text='Добавить в список:', font=MAIN_FONT)
label_text.grid(row=0, column=1, columnspan=2, padx=20)
label_entry = tk.Label(main_frame, text='Размер/рост:', font=MAIN_FONT)
label_entry.grid(row=1, column=1, padx=10)
parameter_text = tk.Entry(main_frame, width=5, font=ENTER_FONT)
parameter_text.grid(row=1, column=2, padx=10)
button_add_coat = tk.Button(main_frame, text='Пальто', width=20, font=MAIN_FONT,
command=lambda: if_error('coat', parameter_text.get()))
button_add_coat.grid(row=2, column=1, columnspan=2, padx=20)
button_add_suit = tk.Button(main_frame, text='Костюм', width=20, font=MAIN_FONT,
command=lambda: if_error('suit', parameter_text.get()))
button_add_suit.grid(row=3, column=1, columnspan=2, padx=20)
button_delete = tk.Button(main_frame, text='Удалить позицию', width=20, font=MAIN_FONT, command=delete_position)
button_delete.grid(row=5, column=1, columnspan=2, padx=20)
root.mainloop()
|
c1cf6cbd5d29a936ccc3682874bcf9718c1cf1ed | HelenMaksimova/python_lessons | /lesson_8/lesson_8_2.py | 1,264 | 3.9375 | 4 | # Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль.
# Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя
# программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
class ZeroDivision(Exception):
def __init__(self, text='Ай-ай! Нельзя делитль на ноль, никак нельзя :('):
self.txt = text
while True:
try:
num_1, num_2 = [int(num) for num in input('Введите два числа через пробел: ').split()]
if num_2 == 0:
raise ZeroDivision
else:
print(f'Делим {num_1} на {num_2} и получаем {num_1 / num_2}')
break
except ValueError:
print('Необходимо ввести два числа через пробел! Попробуйте ещё раз!')
continue
except ZeroDivision as e:
print(f'{e.txt} Попробуйте ещё раз!')
continue
|
1f7276d99e03bd4e62cb805ff499f5b6120af0aa | HelenMaksimova/python_lessons | /lesson_1/lesson_1_3.py | 416 | 4 | 4 | # Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
user_num = input('Введите число: ')
result = int(user_num) + int(user_num*2) + int(user_num*3)
print(f'Сумма чисел {user_num}, {user_num*2} и {user_num*3} равна {result}')
|
9dc87519db8f6aecfe7a641c9f25c3491271e441 | HelenMaksimova/python_lessons | /lesson_2/lesson_2_5.py | 1,362 | 3.75 | 4 | # Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы с одинаковыми
# значениями, то новый элемент с тем же значением должен разместиться после них.
user_list = [5, 2, 2, 1]
print(f'Изначально рейтинг выглядит так: {user_list}')
confirm = True
while confirm:
try:
user_answer = int(input('Введите новую позицию рейтинга: '))
except ValueError:
print(f'Ошибка:! Необходимо ввести целое число!')
continue
new_pos = 0
for elem in user_list:
if elem >= user_answer:
new_pos = user_list.index(elem) + user_list.count(elem)
user_list.insert(new_pos, user_answer)
user_confirm = input('Ввести следующий элемент рейтинга? (да / любой символ)')
confirm = True if user_confirm == 'да' else False
print(f'Теперь рейтинг выглядит так: {user_list}')
|
de047437d8ec928ea2c97d87eec791f5b903d9ad | meshalalsultan/python---input-prosess | /user.py | 454 | 3.859375 | 4 | def sentence (phases):
q = ('how' , 'what' , 'whare' , 'how')
capitalized = phases.capitalize()
if phases.startswith(q):
return f'{capitalized}?'
else :
return f'{capitalized}.'
#print (sentence('what are you today'))
result = []
while True :
user_input = input('Write something here : ')
if user_input == '\end':
break
else :
result.append(sentence(user_input))
print(" " .join(result))
|
684bd733266ca2fb374c0fccb707e17429e63b82 | Vikas-KM/python-programming | /counter.py | 855 | 3.796875 | 4 | import operator
from collections import Counter
from functools import cache
from itertools import accumulate
c = Counter('gallahad') # a new counter from an iterable
print(c)
c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
print(c)
c = Counter(cats=4, dogs=8) # a new counter from keyword args
print(c)
c = Counter() # a new, empty counter
print(c)
c = Counter(['eggs', 'ham'])
print(c)
c = Counter(a=4, b=2, c=0, d=-2)
print(sorted(c.elements()))
print(Counter('abracadabra').most_common(3))
lst = [1,2,3,4,5,6,7,8,0,8,8,6,4,2]
l_add = list(accumulate(lst, operator.add))
l_mul = list(accumulate(lst, operator.mul))
print(l_add)
print(l_mul)
# Feature of python 3.9
@cache
def factorial(n):
return n * factorial(n-1) if n else 1
print(factorial(10))
print(factorial(5)) |
f98aeb7d429aae2a54eaaa52530889c6129ddc57 | Vikas-KM/python-programming | /repr_vs_str.py | 741 | 4.375 | 4 | # __str__ vs __repr__
class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
# print and it returns always string
# for easy to read representation
def __str__(self):
return '__str__ : a {self.color} car with {self.mileage} mileage'.format(self=self)
# typing mycar in console calls this
# unambiguous
# for internal use, for developers
def __repr__(self):
return '__repr__ :a {self.color} car with {self.mileage} mileage'.format(self=self)
my_car = Car('red', 123)
# see which methods they are calling
# comment __STR__ method see what is the output again
print(my_car)
print(str(my_car))
print('{}'.format(my_car))
print(repr(my_car))
|
f6e844303827db40e6e55bdf34347467a8a71249 | maderski/Grocerylist | /grocerylist.py | 6,406 | 3.5625 | 4 | __author__ = 'Jason Maderski'
__date__ = '8-25-2015'
import time
import os.path
import re
class DateAndTime:
getTimeAndDate = time.localtime()
# Return year from current date
def getYear(self):
year = DateAndTime.getTimeAndDate[0]
return year
# Return month from current date
def getMonth(self):
month = DateAndTime.getTimeAndDate[1]
return month
# Return day from current date
def getDay(self):
day = DateAndTime.getTimeAndDate[2]
return day
# Return current date in a array
def getDate(self):
date = []
date.append(self.getMonth())
date.append(self.getDay())
date.append(self.getYear())
print date
# Return Hour from current time
def getHour(self):
twentyFourHour = DateAndTime.getTimeAndDate[3]
if twentyFourHour > 12:
hour = twentyFourHour - 12
else:
hour = twentyFourHour
return hour
# Return minutes from current time
def getMinutes(self):
minutes = DateAndTime.getTimeAndDate[4]
return minutes
# Return seconds from current time
def getSeconds(self):
seconds = DateAndTime.getTimeAndDate[5]
return seconds
# Return 0 if AM and 1 if PM
def getAMPM(self):
twentyFourHour = DateAndTime.getTimeAndDate[3]
if twentyFourHour < 12 or twentyFourHour == 24:
AMPM = 0
else:
AMPM = 1
return AMPM
# Return time as an Array
def getTime(self):
lTime = []
lTime.append(self.getHour())
lTime.append(self.getMinutes())
lTime.append(self.getSeconds())
lTime.append(self.getAMPM())
print lTime
return lTime
# Return date as a string in a readable format
def dateAsString(self):
sDate = str(self.getMonth()) + "-" + str(self.getDay()) + "-" + str(self.getYear())
return sDate
# Return time as a string in a readable format
def timeAsString(self):
if self.getAMPM() == 0:
AMPM = "AM"
else:
AMPM = "PM"
if self.getMinutes() <10:
minutes = "0"+ str(self.getMinutes())
else:
minutes = str(self.getMinutes())
sTime = str(self.getHour()) + ":" + minutes + " " + AMPM
return sTime
class groceries:
listName = ""
groceryList = []
# Ask user to input the name of the list
def setNameOfList(self):
groceries.listName = raw_input("Please enter a list name: ")
# Ask user to add items to list until 'done' is typed
def addItems(self):
i = 0
item = ""
print "Please add items to your grocery list now!"
print "When finished type 'done'"
while item != "done":
item = raw_input(str(i+1) + ": ")
if item != "done":
groceries.groceryList.append(item)
i += 1
# Checks if inputed item is on the grocery list
def checkItemOnList(self, item):
if item in groceries.groceryList:
return True
else:
return False
class PreviousFileWithList:
# Returns True if file is found
def doesFileExist(self):
t = DateAndTime()
currentFileName = groceries.listName + "_" + t.dateAsString() + ".txt"
return os.path.isfile(currentFileName)
# Add a item from the old list to the new list if it is not on the new list
def addOldlistItem(self, oldList):
g = groceries()
# Checks to see if item from previous list is on the new list, if not the item is added
i = 0
while i < len(oldList):
item = oldList[i]
if(g.checkItemOnList(item) == False):
g.groceryList.append(item)
print "Adding item " + item
i += 1
# Edit previous file
def previousFileToList(self):
t = DateAndTime()
currentFileName = groceries.listName + "_" + t.dateAsString() + ".txt"
oldList = []
# Attempt to open file, if file is found then get items listed in file and put them in a list called 'oldList'
try:
inputFile = open(currentFileName, "r")
print "File found"
i = 1
for line in inputFile:
if line.startswith(" " + str(i)):
line = re.sub('[ .)\n]', '', line)
line = ''.join(i for i in line if not i.isdigit())
oldList.append(line)
i += 1
print "Old List:"
print oldList
inputFile.close()
except Exception, e:
print e
print "Creating File: " + currentFileName
return oldList
class ListToFile:
# Output grocery list to a file
def outputToFile(self):
t = DateAndTime()
# Set Output File name
outputFile = open(groceries.listName + "_" + t.dateAsString() + ".txt", "w")
# Add timestamp to file
outputFile.write("Created at: " + t.timeAsString() + "\n\n" + "Items to get:" + "\n" + "-------------" + "\n")
i = 0
# Add grocery list items to file
while i < len(groceries.groceryList):
outputFile.write(" " +str(i+1) + ".) " + groceries.groceryList[i])
outputFile.write("\n")
i += 1
# Stop Writing to File
outputFile.close()
class main:
def __init__(self):
pass
def start(self):
t = DateAndTime()
p = PreviousFileWithList()
g = groceries()
l = ListToFile()
# Print time in console
print "Time is: " + t.timeAsString()
# Ask user for name of the list
g.setNameOfList()
# Ask user to add grocery items
g.addItems()
# Check to see if file exists, if so
if p.doesFileExist():
oldList = p.previousFileToList()
p.addOldlistItem(oldList)
# Print grocerylist information in console
print "\n" + "Please Open file: " + groceries.listName + "_" + t.dateAsString() + "\n"
print "List name: " + groceries.listName
print "Date: " + t.dateAsString()
print "Groceries on list: "
print groceries.groceryList
# Output grocery list to File
l.outputToFile()
m = main()
m.start()
|
cbb68b5a739a298268d2f150aa25841ff4156ffe | sp2013/prproject | /Assgn/Linear_Regression2.py | 1,597 | 4.1875 | 4 | '''
Linear_Regression2.py
Implements Gradient Descent Algorithm
'''
import numpy as np
import random
import matplotlib.pyplot as plt
def linear_regression2():
'''
1. Read training data in to input, output array.
2. Initialize theta0 - y intercept, theta1 - slope of line.
3. Repeat following steps until convergence:
a. Compute theta0.
b. Compute theta1.
c. Compute cost.
d. Check convergence by finding the difference between previous and current cost.
4. Plot data with line using theta0, theta1.
'''
x = np.array([10, 9, 2, 15, 10, 16, 11, 16])
y = np.array([95, 80, 10, 50, 45, 98, 38, 93])
m = x.size
theta0 = random.random()
theta1 = random.random()
delta = 1000000;
error = 0.05
learningrate = 0.001
prevJtheta = 1000
Jtheta = 1000
while (delta > error):
# compute theta0
hx = theta0 + theta1*x
s1 = (hx - y).sum() / m
temp0 = theta0 - learningrate * s1
# compute theta1
s2 = ((hx - y) * x).sum() / m
temp1 = theta1 - learningrate * s2
theta0 = temp0
theta1 = temp1
#compute cost
hx = theta0 + theta1 * x
tempx = (hx - y) * (hx - y)
Jtheta = tempx.sum() / (2 * m)
delta = abs(prevJtheta - Jtheta)
prevJtheta = Jtheta
plt.xlabel('X')
plt.ylabel('Y')
axis = plt.axis([0, 20, 0, 100])
plt.grid(True)
plt.plot(x, y, 'k.')
plt.plot(x, theta1*x + theta0, '-')
plt.show()
return theta0, theta1
|
7662db9a88dd92d432bc53f1f1c6f1856763047e | Bhushan-Jagtap-2013/Python-Examples | /Link_List/203.py | 1,777 | 3.90625 | 4 | # https://leetcode.com/problems/remove-linked-list-elements/description/
# remove all ocurence of given element in LL
class Node:
def __init__(self, data):
self.next = None
self.data = data
class SLL:
def __init__(self):
self.head = None
def printSLL(self):
temp = self.head
while(temp != None):
print temp.data
temp = temp.next
def insertInFront(self, data):
n = Node(data);
if self.head == None:
self.head = n
return
n.next = self.head
self.head = n
def removeElementDummy(self, data):
temp = Node(0)
temp.next = self.head
n = temp
while n.next != None:
if n.next.data == data:
n.next = n.next.next
else:
n = n.next
self.head = temp.next
def removeElement(self, data):
while self.head != None and self.head.data == data:
self.head = self.head.next
if self.head == None:
return
temp = self.head
while temp.next != None:
if temp.next.data == data:
temp.next = temp.next.next
else:
temp = temp.next
if __name__ == "__main__":
s = SLL()
s.insertInFront(10)
s.insertInFront(10)
s.insertInFront(10)
s.insertInFront(10)
s.insertInFront(10)
s.insertInFront(10)
s.insertInFront(20)
s.insertInFront(20)
s.insertInFront(20)
s.insertInFront(20)
s.insertInFront(20)
s.insertInFront(20)
s.insertInFront(30)
print "ORIGINAL:"
s.printSLL()
print "remove 10"
s.removeElement(10)
s.printSLL()
print "remove 20"
s.removeElement(20)
s.printSLL()
|
1cd8c08aba207e7d463b7487e7be54d21beaec6d | Bhushan-Jagtap-2013/Python-Examples | /old_python_examples/binary_and_slice.py | 187 | 3.90625 | 4 | #!/usr/bin/python3
# program to print binary value and slice operator
list = []
list[:] = range(0,100)
print(list)
for i in list[0:16]:
print ("{} in binary {:08b}".format(i, i))
|
5c33baae0e50f099028f50a221f18e0d1437f30a | babzman/Babangida_Abdullahi_day30 | /Babangida_Abdullahi_day30.py | 1,429 | 4.28125 | 4 | def nester(n):
"""Given a string of digits S, This function inserts a minimum number of opening and closing parentheses into it such that the resulting
string is balanced and each digit d is inside exactly d pairs of matching parentheses.Let the nesting of two parentheses within a string be
the substring that occurs strictly between them. An opening parenthesis and a closing parenthesis that is further to its right
are said to match if their nesting is empty, or if every parenthesis in their nesting matches with another parenthesis in their nesting.
The nesting depth of a position p is the number of pairs of matching parentheses m such that p is included in the nesting of m.
"""
if type(n) is not str:
return "Parameter must be in string"
for t in n:
if t not in "0123456789":
return "Parameters must be numbers and greater than zero"
if len(n)==1:
return "("*int(n)+n+")"*int(n)
no=list(n)
u=no
no[0]="("*int(no[0])+no[0]
no[-1]=no[-1]+")"*int(no[-1])
num=[int(i) for i in list(n)]
diff=[int(num[i])-int(num[i+1]) for i in range(len(no)-1)]
for d in range(len(diff)):
if diff[d]>0:
u[d]=u[d]+")"*diff[d]
if diff[d]<0:
u[d]=u[d]+"("*abs(diff[d])
return "".join(u)
#test cases
print(nester("-111000"))
print(nester("4512"))
print(nester("000"))
print(nester("302"))
|
7d6e284b9a6d072d604c2e022c23358bfcebe1c2 | AlvinJS/Python-practice | /grp 2.py | 477 | 3.828125 | 4 | for pypart in range(1,11):
# Function to demonstrate printing pattern
def pypart(n):
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
pypart(n)
print(pypart) |
74789b8d7f88978a688db1b902cdb8954f315a22 | AlvinJS/Python-practice | /Group6_grades.py | 747 | 4.15625 | 4 | # Function to hold grade corresponding to score
def determinegrade(score):
if 80 <= score <= 100:
return 'A'
elif 65 <= score <= 79:
return 'B'
elif 64 <= score <= 64:
return 'C'
elif 50 <= score <= 54:
return 'D'
else:
return 'F'
count = 0
# Use range(10) because function should repeat 10 times
for name in range(10):
# Ask user to input name which is stored in name as a string
name = str(input('Please enter your name: '))
# Ask user to input score which is stored in grade as an integer
grade = int(input('What is your score? '))
# count shows you which iteration you are on
count = count + 1
print(count,'Hello',name,'your grade is:',determinegrade(grade))
|
d19e62ad9a6c8df990322e981c92f95721a49487 | paulQuei/pandas_tutorial | /groupby.py | 700 | 3.84375 | 4 | # groupby.py
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Name': ['A','A','A','B','B','B','C','C','C'],
'Data': np.random.randint(0, 100, 9)})
print('df=\n{}\n'.format(df))
groupby = df.groupby('Name')
print("Print GroupBy:")
for name, group in groupby:
print("Name: {}\nGroup:\n{}\n".format(name, group))
print('Sum: \n{}\n'.format(groupby.sum()))
print('Agg Sum: \n{}\n'.format(groupby.agg(['sum'])))
print('Agg Map: \n{}\n'.format(
groupby.agg([('Total', 'sum'), ('Min', 'min')])))
print('Describe: \n{}\n'.format(groupby.describe()))
def sort(df):
return df.sort_values(by='Data', ascending=False)
print("Sort Group: \n{}\n".format(groupby.apply(sort))) |
2b56d2123723e7ce4bb0cb41aaef1f768bbb819e | Ferril/Antibiosis | /Controls.py | 3,710 | 3.546875 | 4 | from Projectile import Projectile
from World import DELAY
class Controls:
'''
This class contains controls methods for 'w','a','s','d' keys:
start motion for pressed keys and stop motion for released, -
and function for shot on left button click.
'''
def __init__(self, camera, hero, screen, good_shots):
self.keys = {'w': [0, self.up, self.stop_up],
's': [0, self.down, self.stop_down],
'a': [0, self.left, self.stop_left],
'd': [0, self.right, self.stop_right]}
self.camera = camera
self.hero = hero
self.screen = screen
self.projectiles = good_shots
'''
This methods called start-moving-function on press and stop-moving on release.
'''
def key_pressed(self, event):
if event.char in self.keys:
if not self.keys[event.char][0]:
self.keys[event.char][0] = 1
self.keys[event.char][1](event.char)
def key_release(self, event):
if event.char in self.keys:
self.keys[event.char][0] = 0
'''
Motion methods.
'''
def up(self, char):
if self.keys[char][0]:
self.hero.moving['up'] = True
self.hero.move_up()
self.screen.after(DELAY, self.keys[char][1], char)
else:
self.keys[char][2](char)
def down(self, char):
if self.keys[char][0]:
self.hero.moving['down'] = True
self.hero.move_down()
self.screen.after(DELAY, self.keys[char][1], char)
else:
self.keys[char][2](char)
def left(self, char):
if self.keys[char][0]:
self.hero.moving['left'] = True
self.hero.move_left()
self.screen.after(DELAY, self.keys[char][1], char)
else:
self.keys[char][2](char)
def right(self, char):
if self.keys[char][0]:
self.hero.moving['right'] = True
self.hero.move_right()
self.screen.after(DELAY, self.keys[char][1], char)
else:
self.keys[char][2](char)
'''
Stop motion methods.
'''
def stop_up(self, char):
if not self.keys[char][0]:
self.hero.moving['up'] = False
if self.hero.speed['y_up'] < 0:
self.hero.move_up()
self.screen.after(DELAY, self.keys[char][2], char)
def stop_down(self, char):
if not self.keys[char][0]:
self.hero.moving['down'] = False
if self.hero.speed['y_down'] > 0:
self.hero.move_down()
self.screen.after(DELAY, self.keys[char][2], char)
def stop_left(self, char):
if not self.keys[char][0]:
self.hero.moving['left'] = False
if self.hero.speed['x_left'] < 0:
self.hero.move_left()
self.screen.after(DELAY, self.keys[char][2], char)
def stop_right(self, char):
if not self.keys[char][0]:
self.hero.moving['right'] = False
if self.hero.speed['x_right'] > 0:
self.hero.move_right()
self.screen.after(DELAY, self.keys[char][2], char)
'''
Calling Projectile on left-click event.
'''
def click(self, event):
if not self.projectiles:
self.projectiles.append(Projectile(self.hero.x, self.hero.y,
event.x + self.camera.x, event.y + self.camera.y,
'Projectile', self.projectiles))
|
efbd816f05a2c6a3343546048145be328f5ad501 | EdwinSantos/EECS-4088 | /flask/instructions.py | 3,222 | 3.671875 | 4 | class Instructions():
def __init__(self):
self.string = ""
def get(self, name):
getattr(self, name.casefold())()
return self
def double07(self):
self.string = """
Each player starts with 3 life points and 1 action point
Defending and attacking cost 1 action point
Reloading grants 1 action point
Successfully attack hitting an attack on a player grants 1 action point
An attack is successful if the target is reloading or attacking a different players
If the attack is not blocked, the target loses 1 HP
Defending against an attack from another player will grant the player defending 1 action point for each block
Once a player loses all of their life points they are eliminated
The goal is to be the last player alive
"""
def hot_potato(self):
self.string = """
The objective the game is to to be the first player to equal or exceed the point total
When the potato is in your possession swipe the potato away to pass it to another player.
For each second you hold the potato without it exploding you will earn 1 point.
If the potato explodes in your possession you will lose points equal to the total number of seconds the current potato has been in play
"""
def match(self):
self.string = """
One at a time, the current player will be tasked with picking a card from the board of cards displayed on the main computer screen by navigating with the directional pad on their mobile device.
A selected card will be turned appear face down on their mobile device.
The next player attempts to find the matching pair to the card selected by the first player by navigating through the board and selecting another card.
If there is not a match both cards are turned face down and returned to the board.
If there is a match then those 2 cards are are returned to the board.
The standings at the end will show the players based on the number of matches they were a part of.
"""
def fragments(self):
self.string = """
An image will be shown on the main computer screen.
Your task is to select the image on your mobile device that is part of the larger image on the computer screen.
Users who select the correct fragment will be awarded a points.
The faster you select the correct image the more points you will be awarded.
If you are incorrect, they will lose points.
The user with the most points at the end of all the rounds wins.
"""
def multigame(self):
self.string = """
You will be asked to complete a series of tasks. Failure to complete the task correctly will result the offending player being deducted 1 life.
Last player with lives remaining wins.
Quicktap
Your task is to tap the button on your screen as many times as is indicated on the computer screen in the time allotted.
Simon
A series of squares of varying colors are shown on the computer screen. Your task is to re-enter the combination of colors on your mobile device within the time allotted.
Quick maffs
A math equation will be shown on the computer screen. You will be prompted to enter the result on your handheld device within the time allotted.
""" |
60e842bf4ae64f317d94e3aca5b7d813fd9e9130 | magotheinnocent/Simple_Chatty_Bot | /Problems/Rich man's world/main.py | 136 | 3.53125 | 4 | deposit = int(input())
years = 0
rate = 1.071
while 50000 < deposit < 700000:
deposit = deposit * rate
years += 1
print(years)
|
fab1979adbfa20245e24943f73ba15566cd06f69 | magotheinnocent/Simple_Chatty_Bot | /Simple Chatty Bot/task/bot/bot.py | 1,188 | 4.25 | 4 | print("Hello! My name is Aid.")
print("I was created in 2020.")
print("Please, remind me your name.")
name = str(input())
print(f"What a great name you have, {name}!")
print("Let me guess your age.")
print("Enter remainders of dividing your age by 3, 5 and 7")
remainder1 = int(input())
remainder2 = int(input())
remainder3 = int(input())
age = (remainder1 * 70
+ remainder2 * 21
+ remainder3 * 15) % 105
print(f"Your age is {age}; that's a good time to start programming!")
print("Now I will prove to you that I can count to any number you want")
number=int(input())
i = 0
while i <= number:
print(f"{i}!")
i += 1
print("Let's test your programming knowledge.")
print("Why do we use methods?")
answer_1 = list("1. To repeat a statement multiple times.")
answer_2 = list("2. To decompose a program into several small subroutines.")
answer_3 = list("3. To determine the execution time of a program.")
answer_4 = list("4. To interrupt the execution of a program.")
answer = input()
while answer != "2":
print('Please, try again.')
answer = input()
if answer == "2":
print("Completed, have a nice day!")
print("Congratulations, have a nice day!")
|
8d002273f95b08e2c7327a1e0c7859c80817f5a4 | magotheinnocent/Simple_Chatty_Bot | /Problems/Good rest on vacation/main.py | 250 | 3.765625 | 4 | # put your python code here
days = int(input())
food_cost_daily = int(input()) * days
flight_return = int(input()) * 2
hotel_cost_nightly = int(input()) * (days - 1)
total_cost = food_cost_daily + flight_return + hotel_cost_nightly
print(total_cost) |
692bf8260e39ad900a17d75a0403734064b27eb9 | michaelssss/DailyWritting | /Day1/list.py | 384 | 3.625 | 4 | from Day1.Node import Node
def puton(root, string):
root.forward = Node(string)
root.forward.backward = root
root = root.forward
return root
def showcontainasc(node):
print(node)
if node.forward is not None:
showcontainasc(node.forward)
root = Node('root')
node = root
for i in range(0, 25):
node = puton(node, str(i))
showcontainasc(root)
|
8f24830f555f179172638a947c49bf315cdb0d9a | PriyaBasker/desk_allocation_optimisation | /src/data/suggestions.py | 3,040 | 3.71875 | 4 | import pandas as pd
def load_data():
People = pd.read_csv("datasrc/People.csv")
People = People.where((pd.notnull(People)), None)
Attendance = pd.read_csv("datasrc/Attendance.csv")
Desks = pd.read_csv("datasrc/Desks.csv")
return People, Attendance, Desks
def suggest_seat( user: int,Todays_Date:str) -> str:
"""
Suggest a seat for an employee.
Args:
user (int): Employee number
Returns:
seat (str): Suggested seat range
caveats (str): Does this seat exactly fit requirements?
"""
People, Attendance, Desks = load_data()
Special_Feature = People.loc[People["Username"] == user, "Special_Feature"].values[-1]
Employee_Team = People.loc[People["Username"] == user, "Team"].values[-1]
# Ideally the Attendance data would be realtime
Todays_Attendance = Attendance[Attendance["Date"] == Todays_Date]
# Ratio of occupancy/desks to assess if a seat is available:
Team_Capacity = Todays_Attendance["Team"].value_counts() / Desks["Team"].value_counts()
Available_Desks_By_Team = (Desks["Team"].value_counts()) - Attendance.loc[Attendance["Date"]==Todays_Date ,"Team"].value_counts().sort_values(ascending=False)
Available_Desks_By_Team = Available_Desks_By_Team.where((pd.notnull(Available_Desks_By_Team)), 0).map(int)
# Less than 1 means a seat is available
if Team_Capacity[Employee_Team] < 1:
# So sit on your team's allocated desks
if Special_Feature is None:
Team_Seats = Desks.loc[Desks["Team"] == Employee_Team, "Desk"]
return {
"Team" : Employee_Team,
"Feature" : None,
"Seats" : Team_Seats.tolist(),
"DesksAvailable" : Available_Desks_By_Team[Employee_Team],
"FirstChoice" : True
}
# If you need a special feature sit on a particular desk
if Special_Feature is not None:
Team_Seats = Desks.loc[Desks["Team"] == Employee_Team]
Feature_Seats = Team_Seats.loc[Team_Seats["Special Requirements"] == Special_Feature, "Desk"]
return {
"Team" : Employee_Team,
"Feature" : Special_Feature,
"Seats" : Feature_Seats.tolist(),
"DesksAvailable" : Available_Desks_By_Team[Employee_Team],
"FirstChoice" : True,
}
# More than 1 means a seat isn't available
if Available_Desks_By_Team[Employee_Team] > 1:
# Suggest they sit with a low occupancy team
if Special_Feature is None:
Surrogate_Team = Team_Capacity.sort_values().index[2]
Team_Seats = Desks.loc[Desks["Team"] == Surrogate_Team, "Desk"]
return {
"Team" : Surrogate_Team,
"Feature" : None,
"Seats" : Team_Seats.tolist(),
"DesksAvailable" : Available_Desks_By_Team[Employee_Team],
"FirstChoice" : False
} |
1f3934705d0f2c74e9068f55ee1217f98c8bc44f | mavelin/Blackjack | /testcases.py | 772 | 3.6875 | 4 | import unittest
from Card import Card
from Hand import Hand
from Deck import Deck
class TestCard(unittest.TestCase):
def test(self):
kingofclubs = Card('Clubs', 'K')
nocard = Card('A', 'S')
self.assertEquals(kingofclubs.rank, 'K')
self.assertEquals(kingofclubs.suit, 'Clubs')
self.assertEquals(nocard.suit, None)
self.assertEquals(nocard.rank, None)
print 'Test 1 Passed'
class TestHand(unittest.TestCase):
def test(self):
hand = Hand()
kingofclubs = Card('Clubs', 'K')
hand.add_card(kingofclubs)
self.assertEquals(hand.get_value(), 10)
print 'Test 2 Passed'
class TestDeck(unittest.TestCase):
def test(self):
newdeck = Deck()
print newdeck
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.