blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
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
#definici... |
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... |
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... |
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 Constru... |
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 :
... |
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.re... |
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(n... |
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)
p... |
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 compute... |
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__ (se... |
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 = ad... |
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("Pa... |
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]... |
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... |
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])
o... |
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)... |
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[char... |
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... |
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 (
... |
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"... |
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:
... |
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_... |
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[... |
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.a... |
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(chara... |
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)])
... |
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:
... |
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:
re... |
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
... |
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
... |
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: " + ... |
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)
curre... |
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: ... |
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 nu... |
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 pre... |
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):
... |
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 th... |
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, parit... |
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... |
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... |
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"... |
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,arra... |
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)
#... |
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... |
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 setU... |
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 passwo... |
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... |
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 = ... |
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":
pri... |
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"& ")... |
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() + "!")
... |
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)... |
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... |
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 V... |
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 = inpu... |
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")
"""" ====... |
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]
... |
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(... |
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)
exc... |
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
... |
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 ExcellentE... |
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__()... |
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... |
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]
]
... |
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.
l... |
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... |
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... |
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 descrip... |
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 e... |
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_c... |
c1cf6cbd5d29a936ccc3682874bcf9718c1cf1ed | HelenMaksimova/python_lessons | /lesson_8/lesson_8_2.py | 1,264 | 3.9375 | 4 | # Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль.
# Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя
# программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
class ZeroDivision(Exception):
def __init__(... |
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]
p... |
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 h... |
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 coun... |
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... |
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... |
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 f... |
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.hea... |
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 oc... |
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
... |
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... |
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".form... |
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... |
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... |
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())
remaind... |
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 ran... |
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_D... |
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')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.