blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3601560b69f2cb4882716c971ef17302ff49d8f3
Margarita89/LeetCode
/0010_Regular_Expression_Matching.py
961
3.875
4
class Solution: def isMatch(self, s: str, p: str) -> bool: """ General idea: use recursion and check for 2 options with "*" - zero or non zero matches 1. Base case: pattern p is over -> check if s is also over 2. Boolean first_match True if is not yet empty and there is a match with p 3. If there is '*': 1. Either s matches zero times with p[0], then simply skip s[0:2] -> self.isMatch(s, p[2:]) 2. Or there is a match with first characters and possibly with others from s -> self.isMatch(s[1:], p) 4. Else if first characters match -> move to the next in s and p """ if not p: return not s first_match = bool(s) and p[0] in {s[0], '.'} if len(p) >= 2 and p[1] == '*': return self.isMatch(s, p[2:]) or first_match and self.isMatch(s[1:], p) else: return first_match and self.isMatch(s[1:], p[1:])
10f8f15d418108d231fbb5e612d8e8c89005b5fb
satchidananda-tripathy/PythonHacks
/8numpy.py
1,659
4.125
4
import numpy as np # This module helps us to creates super fast and memory efficients arrays #We can store data in 1d, 2d, 3d array etc. # As numpy has a datatype and it keeps less memory (because of contigous allocation) it needs less time to read data hence it is faster # x = [1,2] y=[3,4] here the list x*y will throw error # In numpy we can get resulet [ 3, 8] a=np.array(([1,2,3]),dtype=int) b=np.array(([1,2],[3,4],[5,6]),dtype=int) print('Type of the array b is ',type(b)) print('size of the array b is ',b.shape) print('The dimension of the array a and b respectively are ',a.ndim ,'and ',b.ndim) print('The second row and second column value of the array b is ',b[1,1], 'or ', b[1][1]) print('The type of values within the array and the size are ',b.dtype,'and ',b.size) print('---------------------------------------------------') # Matrix initialization print() print('Matrix initialization') z=np.zeros((2,3),dtype=int) o=np.ones((2,3),dtype=int) # intialize an arry with all values 1 fives=np.full((3,3),5,dtype=int) ##Fill the array with values 5 identity = np.identity((5),dtype=int) print(z) print(o) print(fives) print('Identity matrix is ',identity) # create a matrix with random values r = np.random.random((2,3)) print(r) #Conditional statements print(r>0.25) print(r[r>0.25]) ## A simple way to filter data from a list (logically the true value of r>0.25 ) print('Few Mathematical Functions') print(np.sum(r)) print(np.average(r)) print(np.max(r)) print(np.floor(r)) print(np.round(r)) print('Few Mathematical Operations') distance_mit = np.array([100,2000,3456,7689,1234]) distance_km =distance_mit/1000 print(distance_km)
1a1b2853ac0a779ecaf4d71ca408b5f1e3664845
showintime/MachineLearningToolkit
/MachineLearningToolkitCore/Layer/Dense.py
1,709
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 30 00:16:56 2019 @author: ZWH """ import numpy as np from LayerBase import LayerBase ''' Dense layer is a trainable layer, which means that it has parameters to train. Attention to use this layer if you want to reuse this layer parameter. Attention : The Layer Dense in this version is not supported for reusing! parameter layer x shape = [batch_size, input_size] w shape = [input_size, output_size] b shape = [output_size] x @ w + b shape = [batch_size, output_size] ''' class Dense(LayerBase): def __init__(self, unit_nums): self.weight_shape = [None,unit_nums] self.bias_shape = [unit_nums] def build(self, input_shape): ''' 自动推断维度,确定变量维度,并在内存中初始化 ''' self.weight_shape[0] = input_shape[-1] self.w = np.random.random(size = self.weight_shape) * 6 / sum(self.weight_shape) self.b = np.zeros(shape = self.bias_shape) + 0.1 #print('you only look once') output_shape = input_shape output_shape[-1] = self.weight_shape[-1] return output_shape def forward(self, x): return x @ self.w + self.b def apply_gradient(self): self.w -= self.dw self.b -= self.db def compute_gradient(self, losses): self.dw = self.x.T @ losses self.db = np.sum(losses, axis = 0) self.dx = losses @ self.w.T return self.dx def backward(self, losses): return self.compute_gradient(losses) def __call__(self,x): self.x = x return self.forward(x)
74def28e61dbaae2bbcc0fa68b106bde4cc361d6
tarun1792/DataStructure-Algorithem-Python
/DataStructures/python/LinkedList/MiddleOfLinkedList.py
375
3.546875
4
def findMid(head): # Code here # return the value stored in the middle node if head.next is None: return head.data ptr1 = head ptr2 = head while(ptr2.next is not None): ptr1 = ptr1.next if ptr2.next.next is not None: ptr2 = ptr2.next.next else: break return ptr1.data
1b9468e0977ab2d4fe2f8a8e1131668d2ba3320c
MahirI1009/CSE-216-HW4
/binarytree.py
1,466
4.25
4
class BinaryTree: # 5. constructor to initialize binary tree as an empty tree or with a single value def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # 6. add_leftchild and add_rightchild methods # 7. TypeError if new child is not of the same type as the rest of the elements of the tree def add_leftchild(self, left): if isinstance(left.data, type(self.data)) or left.data is None: self.left = left else: raise TypeError("Type mismatch between " + str(type(self.data)) + " and " + str(type(left))) def add_rightchild(self, right): if isinstance(right.data, type(self.data)) or right.data is None: self.right = right else: raise TypeError("Type mismatch between " + str(type(self.data)) + " and " + str(type(right))) # 8. property and setter @property def data(self): return self.__data @data.setter def data(self, data): self.__data = data # 9. implementation of iter() def __iter__(self): if self.data is not None or self.data is None and isinstance(self, BinaryTree): yield self.data if self.left is not None: for d in self.left: yield d if self.right is not None: for d in self.right: yield d
5b0c8b4ed060dd178a12fe4be191b7ab4bc0f925
Growail/Python-codes
/29 7 14.py
456
3.53125
4
#29/7/14 def mcm(num1, num2, num3): cont=1 i=1 while i>num1 and i>num2 and i>num3 : if num1%i==0 and num2%i==0 and num3%i==0: num1=num1/i num2=num2/i num3=num3/i cont=cont*i i=i+1 else: i=i+1 return i def suma (num): i=0 total=0 while i>=num: total=total+(((i**3)*(i**2)*num)/n) i+=1 return total
1df078e941c0e7a5645b873915e43aa843fb1927
Aasthaengg/IBMdataset
/Python_codes/p00005/s388716206.py
721
3.53125
4
while True: try: # a >=b a, b = sorted(map(int, input().strip("\n").split(" ")), reverse=True) d = a * b # calc. gcm by ユークリッド互除法 while True: c = a % b # print("{0} {1} {2}".format(a, b, c)) if c == 0: break else: a, b = sorted([b, a % b], reverse=True) gcm = b lcm = d / gcm # print("gcm is {}".format(b)) print("{0:d} {1:d}".format(int(gcm), int(lcm))) #print("{0} {1}".format(a, b)) #a, b = sorted([b, a % b], reverse=True) #print("{0} {1}".format(a, b)) except EOFError: break # escape from while loop
e343174888344e3aff75078ed2400f589675158e
rupeq/python-crypto
/elgamal.py
2,458
3.828125
4
from random import randint from math import gcd, sqrt def isPrime(x): if x == 1: return False if x <= 3: return True if x % 2 == 0 or x % 3 == 0: return False for i in range(5, x // 2 + 1): if x % i == 0: return False return True def findPrimefactors(s, n): while n%2 == 0: s.add(2) n //= 2 for i in range(3, int(sqrt(n)), 2): while n%i==0: s.add(i) n //= i if n > 2: s.add(n) def power(x, y, p): res = 1 x %= p while y: if y&1: # нечетно res = (res * x) % p y = y >> 1 x = (x * x) % p return res def findPrimitive(n): s = set() if not isPrime(n): return f"{n} не простое число!" fi = n - 1 findPrimefactors(s, fi) for r in range(2, fi+1): flag = False for i in s: if (power(r, fi // i, n) == 1): flag = True break if not flag: return r, fi return "Первичный корень не найден" def cipher(m, y, fi, result_ab=[]): for i in m: k = randint(2, fi) a = g ** k % p b = y ** k * i % p result_ab.append((a, b)) return result_ab def decipher(c, decipher = []): for a, b in c: t = b*a**(p-1-x) % p decipher.append(chr(t+1039)) return decipher if __name__ == "__main__": message = [ord(letter)-1039 for letter in input("Введите шифруемое сообщение: ")] print(f"Открытое сообщение {message}") p = int(input("Введите простое число p = ")) result_ab = [] if not isPrime(p): print(f"Число {p} не простое!") else: g, fi = findPrimitive(p) ans = input(f"Выбрано число g = {g}. Хотите выбрать другое? (да/нет)? ") while ans != "нет": g = int(input("Число g = ")) break x = int(input(f"Введите x, меньшее {p} = ")) y = g ** x % p c = cipher(message, y, fi) print(f"Зашифрованное сообщение {c}") d = decipher(c) d = "".join(d) print(f"Расшифрованное сообщение: {d}")
22fa38c1630f576a204dc6891fcbe3ab051c4255
stys/y-test-ranknet
/lib/activation.py
1,222
3.921875
4
from abc import abstractmethod import math """ Activation functions """ class ActivationFunction(object): @abstractmethod def f(self, x): """ Activation function value at x """ pass @abstractmethod def df(self, f): """ Activation function derivative at x, computed from function value """ pass class sigmoid(ActivationFunction): """ Compute sigmoid f(x) = a / ( 1 + exp(-x/s) ) and its derivative """ def __init__(self, a = 1.0, s = 1.0): self.a = a self.s = s def f(self, x): # non-overflowing sigmoid return self.a * ( 1.0 + math.tanh(x/self.s/2.0) ) / 2.0 def df(self, f): return f * (self.a - f) / self.a / self.s class linear(ActivationFunction): def f(self, x): return x def df(self, f): return 1.0 class tanh(ActivationFunction): def __init__(self, a = 1.0, s = 1.0): self.a = a self.s = s def f(self, x): return self.a * math.tanh( x / self.s ) def df(self, f): return ( self.a*self.a - f*f ) / self.a / self.s
3e907178ff2568710426e8a2e23caa3cfb69de32
silvercobraa/competitive-programming
/1. Introduction/Ad Hoc Problems/Time, Harder/10070.py
580
3.890625
4
def is_leap(n): return n % 4 == 0 and (n % 100 != 0 or n % 400 == 0) first = True s = input() try: while s != '': n = int(s) if not first: print() else: first = False leap = is_leap(n) huluculu = n % 15 == 0 bulukulu = n % 55 == 0 and leap if not leap and not huluculu and not bulukulu: print("This is an ordinary year.") s = input() continue if leap: print("This is leap year.") if huluculu: print("This is huluculu festival year.") if bulukulu: print("This is bulukulu festival year.") s = input() except Exception as e: pass
0d5069b0a7b7869bcfc2a62d57f0e483ffabaecc
Windreelotion/store
/测试.py
2,680
3.671875
4
''' 京东的登陆、淘宝登陆、苏宁的登陆脚本 bilibili登陆脚本,搜索一个鬼畜视频并播放脚本写出来。 做知乎的官网,并登陆,和发表一篇文章。 企查查的官网登陆。 ''' from selenium import webdriver import time from selenium.webdriver.common.action_chains import ActionChains # 苏宁自动化登陆操作 driver = webdriver.Chrome() driver.get("https://www.suning.com") driver.maximize_window() driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div[2]/a[1]').click() driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[1]/a[2]/span').click() driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/div[1]/div[2]/div[1]/input').send_keys("13135992021") driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/div[1]/div[3]/div/input').send_keys("xiangyangxy123") time.sleep(2) driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/div[1]/div[6]/div/div/span').click() time.sleep(5) ac = ActionChains(driver) ele = driver.find_element_by_xpath('/html/body/div[5]/div[2]/div[2]/div[2]/div/div[3]') time.sleep(2) ac.click_and_hold(ele).move_by_offset(113.8,0).perform()# 立即执行 ac.release() # 释放鼠标 driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/div[1]/a').click() driver.quit() # 知乎自动化登陆操作 driver = webdriver.Chrome() driver.get("https://www.zhihu.com") driver.maximize_window() time.sleep(2) driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div/div/div[1]/div/div[1]/form/div[1]/div[2]').click() driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div/div/div[1]/div/div[1]/form/div[2]/div/label/input').send_keys("13135992021") driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div/div/div[1]/div/div[1]/form/div[3]/div/label/input').send_keys("xiangyangxy123") driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div/div/div[1]/div/div[1]/form/button').click() time.sleep(5) driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div[3]/div[2]/div/div/div/div[1]/div/div[2]/div[1]/div/button[3]/svg/g/circle').click() # 获取所有窗口唯一标号 data = driver.window_handles # ["s001","s002"] driver.switch_to.window(data[1]) driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div[2]/div[2]/label/textarea').send_keys("半自动化登陆操作") driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div[2]/div[2]/label/textarea').send_keys("123456") driver.find_element_by_xpath('/html/body/div[1]/div/main/div/div[1]/div/div/div[1]/div[2]/div[3]/button').click() driver.quit()
db152888584f85403424f21c0bb6ef79efb75caf
mihau1987/Python_basics
/Trello_Zadania/03_Instrukcje_Warunkowe/02_Zadania_dodatkowe/Zadanie_slodycze.py
1,215
4.15625
4
slodycze = ['paczek', 'drozdzowka', 'gniazdko', 'jagodzianka', 'szarlotka', 'muffin'] '''question = input("Czego sobie życzysz? ") if question in slodycze: print("Podany produkt jest dostepny") else: print("Niestety nie posiadamy artykulu na stanie") q1 = input("Podaj produkt no 1: ") q2 = input("Podaj produkt no 2: ") q3 = input("Podaj produkt no 3: ") if q1 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") if q2 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") if q3 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") q1 = input("Podaj produkt no 1: ") q2 = input("Podaj produkt no 2: ") q3 = input("Podaj produkt no 3: ") if q1 and q2 and q3 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy produktow na stanie")''' q = input("Podaj nazwę produktu a dowiesz sie ile sztuk posiadamy: ") if q in slodycze: print("Na stanie mamy 12 sztuk podanego produktu") else: print("Niestety w tym momencie nie posiadamy produktu na stanie")
f55046a4e13c90066c04f886536eb116ac967e18
narayansiddharth/Python
/AIMA/Assignment/NOV_17_18/AS-1-Binarization.py
1,559
4.25
4
# Write code in Python for Binarization without using any library from typing import List def Binarization(inputlist, symbol: object, threshold: object) -> object: finalList: object = [] for row in inputlist: innerList: object = [] for col in row: if symbol == '>': if col >= threshold: innerList.append(1) else: innerList.append(0) else: if threshold > col: innerList.append(1) else: innerList.append(0) finalList.append(innerList) return finalList def inputList(row, col): inputlist: List[List[int]] = [] for i in range(row): list = [] print('enter {0} list elements, please press enter after each element :'.format(col)) for j in range(col): list.append(int(input().strip())) inputlist.append(list) return inputlist row = int(input("enter no of rows: ")) col = int(input("enter no of coloumns: ")) inputlist = inputList(row, col) # [int(i) for i in list(input().split())] threshold = int(input("Enter the threshold value :")) key = input( "Do you want set 1 for value which are greter than equal threshold , then press 'y'; if you want set 0 press any " "key...") print("Input List :: ", inputlist) print("Threshold Value : ", threshold) if key == 'y': output = Binarization(inputlist, '>', threshold) else: output = Binarization(inputlist, '<', threshold) print(output)
090a87cb689d09561eaf01bfd5ca34e8b12f4f8b
roma-glushko/leetcode-solutions
/src/linked_list/merge_k_sorted_lists_test.py
1,106
3.5625
4
from typing import List from unittest import TestCase from .merge_k_sorted_lists import ListNode, MergeKSortedLists class MergeKSortedListsTest(TestCase): def get_values_from_list(self, list_head: ListNode) -> List: list_values = [] current_node = list_head while current_node: list_values.append(current_node.val) current_node = current_node.next return list_values def test_default_input(self): list_elements: List[ListNode] = [ ListNode(1, ListNode(4, ListNode(5))), ListNode(1, ListNode(3, ListNode(4))), ListNode(2, ListNode(6)), ] merged_list_head = MergeKSortedLists().mergeKLists(list_elements) list_values = self.get_values_from_list(merged_list_head) self.assertEqual([1, 1, 2, 3, 4, 4, 5, 6], list_values) def test_empty_inputs(self): solution = MergeKSortedLists() self.assertEqual([], self.get_values_from_list(solution.mergeKLists([]))) self.assertEqual([], self.get_values_from_list(solution.mergeKLists([[]])))
ca08db7b319ed35439106b19f8870a3a7ed46ffc
JuanesFranco/Fundamentos-De-Programacion
/sesion-05/ejercicio 53.py
552
3.75
4
cantidad1=0 cantidad2=0 cantidad3=0 cantidad4=0 for f in range(10): valor=int(input("ingrese numero entero")) if valor>0: cantidad1=cantidad1+1 else: if valor<0: cantidad2=cantidad2+1 if valor%15==0: cantidad3=cantidad3+1 if valor%2==0: cantidad4=cantidad4+1 print("la cantidad de positivos es de",cantidad1) print("la cantidad de negativos es de",cantidad2) print("la cantidad de multiplos de 15 es de",cantidad3) print("la cantidad de pares es de",cantidad4)
428210cea039f846bffecd4ecfa0a04345dcb378
sumanthgunda/hacktoberfest2020
/guess_the_num.py
1,673
4.125
4
import random choice=random.choice(range(21)) def print_pause(msg_to_print): print(msg_to_print) time.sleep(2) def intro(choice): print("the computer choose a number within the range 20" ) intro(choice) def try1(): c1=input("i guess the number is ") if choice == c1: print("your guess is correct") else : print("Incorrect, Try again..") try1() def hint1(): if choice%2 == 0: print("Hint: The number is even") else: print("Hint:The number is odd") hint1() def try2(): c2=input(" i guess the number is") if choice == c2: print("your guess is correct") else : print("Incorrect, Try again..") try2() def hint2(): if 10<choice<21 : print("Hint: The number is greater than 10") elif 0<choice<11 : print("Hint: The number is smaller than 10") else : print("The number is notin the given range") hint2() def try3(): c3=input("i guess the number is ") if choice == c3: print("your guess is correct") else : print("Incorrect, Try again..") try3() def hint3(): if choice%3 == 0: print("Hint: The number is divisible by 3") else: print("Hint: The number is not divisible by 3") hint3() def last_try(): c4=input("i guess the number is ") if choice == c4: print("your guess is correct") else : print("Incorrect, you were unable to guess the correct number ") last_try() score=int() def t_score(): if input == choice : score+=1 t_score() print("the correct answer is "+ str(choice)) print("the total score is "+ str(score))
d79b994433cd9ed5bfe33afb0e5e807cfe384803
garlicbread621/Garliczone
/Software.py
551
3.9375
4
price = 99 packages = int(input("Please enter amount of packages you wish to purchase: ")) sale=price*packages if packages < 10: discount=sale*0 elif 10 < packages and packages < 20: discount=sale*.10 elif 19 < packages and packages < 50: discount=sale*.20 elif 49 < packages and packages < 100: discount=sale*.30 elif packages > 99: discount=sale*.40 total = sale-discount print("You purchased", packages,"orders for a price of",sale, " dollars, you have saved", discount) print("dollars which brings your total down to",total,"dollars")
fe86ea6f3f4f43c3cf59d2b905709bbb37441c9b
olinkaz93/Algorithms
/loop.py
88
3.84375
4
list = [2, 3, 4] for i in range (len(list)): print("element", i, "value:", list[i])
a0f23cf0efb584317f4cc917008c577e18ca0cba
haoknowah/OldPythonAssignments
/Gaston_Noah_NKN328_Hwk13/015_the12DaysOfChristmas.py
2,381
4.03125
4
def the12DaysOfChristmas(): ''' the12DaysOfChristmas=asks for a number and determines the price from that many days of the 12 days of Christmas stored in Gifts.txt @param number=number of days specified @param infile=contains file Gifts.txt @param theDays=list holding the 12 days of Christmas from infile @param day=day of theDays being checked @param needed=list containing only the number of days used @param subtotal=total cost of last day @param total=total cost of all the days prints what was done on what days and the cost of the last day as well as the overall cost ''' try: while True: number=input("Enter an integer 1 through 12: ") if number.isdigit()==False: print("Wrong") elif int(number) < 1 or int(number) > 12: print("Wrong size.") else: break infile=open("Gifts.txt", 'r') print("READ") theDays=[line.rstrip() for line in infile] infile.close() for day in range(len(theDays)): theDays[day]=theDays[day].split(",") theDays[day][0]=int(theDays[day][0]) theDays[day][2]=float(theDays[day][2]) needed=[] for day in range(len(theDays)): if int(theDays[day][0]) <= int(number): needed.append(theDays[day]) print("The gifts for day ", number, " are: ", sep="") subtotal=0 total=0 for day in range(len(needed)): print("{0:<5n}{1:10s}".format(needed[day][0], needed[day][1])) subtotal=subtotal+(1+day)*needed[day][2] total=total+subtotal print("The cost for day ", number, " is: $", round(subtotal, 2), sep="") print("The total cost by day ", number, " is: $", round(total, 2), sep="") except: print("Error in the12DaysOfChristmas") if __name__ == "__main__": def test_the12DaysOfChristmas(): ''' test_the12DaysOfChristmas()=tests the the12DaysOfChristmas() method @param cont=boolean that determines if program repeats ''' try: cont=True while cont==True: the12DaysOfChristmas() end=input("Continue? y or n ") if end.lower()=="n": cont=False except: print("Error.") test_the12DaysOfChristmas()
a8bb024dcb06e69caf0ddf45926f76575aa4e701
hackrmann/learn_python
/printemoji.py
155
3.671875
4
n = input("Enter number of lines of emoji: ") n = int(n) for i in range(1,n+1): for j in range(1,i+1): print('\U0001f600',end="") print("")
7a0a88976ee867ee3be0c3844f9c2d14e80d4725
RAKS-Codes/simpyfy
/os_functions.py
1,047
3.96875
4
import os from pathlib import Path def make_directory_tree(pathname): """ Creats hierarchical paths """ path = Path(pathname) path.mkdir(parents = True, exist_ok = True) def get_directory_list(folderpath,sort = True,verbose = True): """ Returns a list of directories inside a directory """ directory_list = [] for root,d_names,f_names in os.walk(folderpath): for dname in d_names: directory_list.append(dname) # Sorting the list if sort == True : directory_list.sort() print('Directory list is .....') if verbose == True : for d in directory_list: print(d) return directory_list def get_file_list(folderpath,sort = True,verbose = True): """ Returns a list of files inside a directory """ file_list = [] for root,d_names,f_names in os.walk(folderpath): for fname in f_names: file_list.append(fname) # Sorting the list if sort == True: file_list.sort() print('File list is .....') if verbose == True: for file in file_list: print(file) return file_list if __name__ == "__main__": pass
f5ef817df3207388907878ec524bf1d3453f4f77
SaiSujithReddy/CodePython
/BInarySearchTree_Practise_v4.py
1,589
4
4
class Node: def __init__(self,data): self.val = data self.leftChild = None self.rightChild = None def bst_insert(root,data): if root is None: root = Node(data) else: if root.val > data: if root.leftChild: bst_insert(root.leftChild,data) else: root.leftChild = Node(data) else: if root.rightChild: bst_insert(root.rightChild,data) else: root.rightChild = Node(data) def print_inorder(root): if root.leftChild: print_inorder(root.leftChild) print(root.val) if root.rightChild: print_inorder(root.rightChild) #Queue based approach def printLevelOrder_using_queue(root): print("inside quque") # Base Case if root is None: return # Create an empty queue for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while (len(queue) > 0): # Print front of queue and remove it from queue print(queue[0].val) node = queue.pop(0) # Enqueue left child if node.leftChild is not None: queue.append(node.leftChild) # Enqueue right child if node.rightChild is not None: queue.append(node.rightChild) node = Node(5) bst_insert(node,4) bst_insert(node,6) bst_insert(node,7) bst_insert(node,8) bst_insert(node,3) print_inorder(node) printLevelOrder_using_queue(node) ''' 5 / \ 4 6 / \ 3 7 \ 8 '''
ff0dba9e05c724ffa54eb4320ba908220b39c14f
py1-10-2017/ElvaC-p1-10-2017
/Strlists.py
447
3.796875
4
# words = "It's thanksgiving day. It's my birthday, too!" # print words.find('day') # print words.replace("day", "month") #min # x = [2,54,-2,7,12,98] # print min(x) #max # x = [2,54,-2,7,12,98] # print max(x) #First and Last # x = ["hello",2,54,-2,7,12,98,"world"] # print x[0], x[-1] #New List x2 = [19,2,54,-2,7,12,98,32,10,-3,6] x2.sort() # print x2 y = x2[:len(x2)/2] z = len(x2)/2 result = x2[z:] print y print z print y.append(result)
889fa09f6c60e2131fb611a3e823bc3b7ec7170c
mwong33/leet-code-practice
/medium/remove_nth_node_from_end.py
925
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # O(n) time O(1) space def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: # Step One: Get the length of the Linked List # Step Two: Iterate through the Linked List for length - n # Step Three: Remove the nth node # Step Four: Return the head length = 0 temp = head while temp != None: length += 1 temp = temp.next if length - n == 0: head = head.next else: count = 1 temp = head while count < length - n: temp = temp.next count += 1 temp.next = temp.next.next return head
72de143aa2cef1c6d1691050d51d5119155fe3f6
mizrael63/learning
/lesson7/task3.py
2,151
3.921875
4
-#Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. # Найти в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: # в одной находятся элементы, которые не меньше медианы, в другой – не больше ее. import random m = int(input("Введите натуральное число m: ")) array = [random.randint(0, 100) for _ in range(2*m + 1)] def podbor(array): #Данная функция перебирает элементы исходного массива и для каждого вызывает функцию проверки #которая работает на append-ах. Как только в ходе проверки получили две равные строки выводится значение медианы #а выполнение функции прерывается n = 0 while n < len(array): appendix(array[n]) if len(minn) == len(maxx): print("Медиана: ", array[n]) break n += 1 def appendix(e): #функция создает два пустых массива, которые сама наполняет в процессе работы и возвращает в предыдущую функцию #её задача - раскидывать в два списка все большие или меньшие элементы. Равные элементы решено игнорировать, #но можно было бы добавлять в оба списка, соотношение от этого не поменялось бы global minn, maxx i = 0 minn = [] maxx = [] d = array while i < len(d): if d[i] < e: minn.append(d[i]) elif d[i] > e: maxx.append(d[i]) elif d[i] == e: pass i += 1 print("Исходный сгенерированный массив: ", array) podbor(array)
c32d2df0eec8084da4ba845f2bd260ad2ee082c5
Lmineor/Sword-to-Offer
/bin/insert_sort.py
210
3.59375
4
class Solution: def NumberOf1(self, n): # write code here count = 0 while n: count += 1 n = (n-1)&n return count s = Solution() print(s.NumberOf1(3))
6113c93ad961e231412930542739bf2d49ddc484
chogiseong/GovernmentExpenditureEducation
/Python/6.4.py
3,058
3.6875
4
''' a=[7,2,5,3,1] b=0 c=0 space = 0 for b in range(0, len(a)) : for c in range(0,len(a)) : if a[c] < a[c+1] : space = a[c] a[c] = a[c+1] a[c+1] = space c = c + 1 continue continue print(a) ''' #버블정렬 #1. 안바뀌면 정렬된 것 - 변수 #check #2. 앞과 뒤를 비교한다. #if L[x] < L[x+1] #3. 바꾸는 구문 #바꿀 때 변수가 필요하다. ''' 버블정렬 미완성 완성해보기 a=[7,4,1,6,3] check = False temp = 0 x=0 def switchData(a, index): temp = 0 temp = a[index] a[index] = a[index+1] a[index+1] = temp for x in range(0,3): if a[x] < a[x+1]: switchData(a,x) check = True while check : for x in range(0,3): if a[x]<a[x+1]: switchData(a,x) check = True print(a) ''' ''' 클래스 예제 class A: a=1 b=2 def pr(): print("a클래스입니다") ''' ''' class a: value = 1 #print("1")이런거안댐 def printval(): print("1") value += 1 ''' ''' 클래스 예제1 class a: val = 3 def valueTest(self): self.val = 4 def valueTest1(self): print(self.val) mA=a() mA.valueTest() mA.valueTest1() print(mA.val) mB=a() print(mB.val) ''' ''' class A: mClassVal=6 def _init_(self): self.val=5 mA = A() print(mA.val) ''' ''' 실패 클래스 예제 class 디자인: def test(self, name, address, age, score, rank) test.self = self test.name = name test.address = address test.age = age test.score = score test.rank = rank print(name, address, age, score, rank) ''' ''' #클래스활용방법 중요!! class a: name = "" addr = '' age = 0 grade1=0 grade2=0 sum_grade=0 rank=-1 def Sum(self): self.sum_grade = self.grade1 + self.grade2 S1 = a() S1.grade1 = 50 S1.grade2 = 60 S1.Sum() print("%d" % S1.sum_grade) S2 = a() S2.grade1 = 90 S2.grade2 = 60 S2.Sum() print("%d" % S2.sum_grade) ''' ''' #모듈화 = 최소한의 기능을 넣자 #오버로딩 오버라이딩 class Rectangle: #초기자(이니셜라이저) def __init__(self,width=0,height=0): #self 인스턴스변수 self.width =width self.height = height #메서드 def calcArea(self): area = self.width*self.height return area a = Rectangle(5,5) print(a.calcArea()) ''' ''' class Ract: count = 0 def printT(self): Ract.count = 5 self.w = 4 mA = Ract() mA.printT() print(mA.count) mB = Ract() print(mB.count) ''' ''' 상속 예제 class Ract: count = 0 w = 1 h = 3 class A(Ract): p=50 class B(A): pass mA=A() print(mA.w) mB=B() print(mB.count) ''' ''' 미완성 상속 예제 class Ract: count = 0 w = 1 h = 3 def mv(self): print("Ractfunc") class A(Ract): count = 50 def mV(self): print("afunc") class B(A): pass mA=A() mA.mV() print("00000000") mRact = Ract() mRact.mV() '''
f28610a2a9693e366d60456d90715c0b7177a4b7
zuxinlin/leetcode
/leetcode/217.ContainsDuplicate.py
603
3.828125
4
#! /usr/bin/env python # coding: utf-8 ''' 题目: 包含重复数字 https://leetcode-cn.com/problems/contains-duplicate/ 主题: array & hash table 解题思路: 1. 哈希表 ''' class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ hash_table = set() for num in nums: if num in hash_table: return True else: hash_table.add(num) return False if __name__ == '__main__': solution = Solution()
c02e9be6b021014a946ba37266a72d2725ad410d
analuisadev/100-Days-Of-Code
/Day-25.py
1,200
3.765625
4
option = 'Yy' print ('\033[1;32m{:=^40}\033[m'.format(' ANNUAL STUDENT RESULT ')) while option == 'Yy': nome = str(input('\033[1mType your name: ')) n1 = float(input('\033[1;33m{}\033[m \033[1;32mType a first note:\033[m '.format(nome.lower().capitalize()))) n2 = float(input('\033[1;33m{}\033[m \033[1;32mEnter your second note:\033[m '.format(nome.lower().capitalize()))) n3 = float(input('\033[1;33m{}\033[m \033[1;32mEnter your second note:\033[m '.format(nome.lower().capitalize()))) n4 = float(input('\033[1;33m{}\033[m \033[1;32mEnter your second note:\033[m '.format(nome.lower().capitalize()))) média = (n1+n2+n3+n4)/4 print ('\033[1m{} Your average is\033[m \033[1;36m{:.1f}\033[m'.format(nome.lower().capitalize(), média)) option = str(input('\033[1mDo you wish to continue? [Yes/No]\033[m ')).upper().strip()[0] print ('\033[1;32m{:=^40}\033[m'.format(' RESULT ')) if média <= 4: print ('\033[1mVocê está\033[m \033[1;31mDISAPPROVED\033[m') elif média == 5: print ('\033[1mVocê está em\033[m \033[1;33mRECOVERY\033[m') else: print ('\033[1mVocê foi\033[m \033[1;36mAAPPROVED\033[m') print ('\033[1;35mOperation completed\033[m')
46637a1c9fcb73b17a1be05f43f68c81c024a362
lucasayres/python-tools
/tools/sha256_file.py
397
3.78125
4
# -*- coding: utf-8 -*- import hashlib def sha256_file(file): """Calculate SHA256 Hash of a file. Args: file (str): Input file. Retruns: str: Return the SHA256 Hash of a file. """ sha256 = hashlib.sha256() with open(file, 'rb') as f: for block in iter(lambda: f.read(65536), b''): sha256.update(block) return sha256.hexdigest()
3e45129b6878afe9be84075e0356c8d694172303
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex082.py
718
3.8125
4
lista = [] pares = [] ímpares = [] while True: lista.append(int(input('Digite um número: '))) r = ' ' while r not in 'SN': r = str(input('Deseja continuar [S/N]: ').strip().upper()[0]) if r not in 'SN': print('Opção incorreta...') if r in 'N': break for pos, e in enumerate(lista): if e % 2 == 0: pares.append(e) else: ímpares.append(e) lista.sort() print(f'Valores digitados: {lista}') if pares == []: print('Não foram digitados valores pares!!!') else: print(f'Os valores pares foram: {pares}') if ímpares == []: print('Não foram digitados valores ímpares!!!') else: print(f'Os valores ímpares foram: {ímpares}')
de9115b1ac802d914749ea0593a42b9128664cb5
anmolrajaroraa/core-python-april
/tic-tac-toe.py
2,310
4.03125
4
import random print("Tic Tac Toe".center(100)) userChoice = input("Which one do you want to use (X or O) : ") userChoice = "X" if userChoice == "X" or userChoice == "x" else "O" cpuChoice = "O" if userChoice == "X" else "X" gameProgress = [1, 2, 3, 4, 5, 6, 7, 8, 9] availablePositions = [1, 2, 3, 4, 5, 6, 7, 8, 9] winningPositions = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [ 0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] turnsPlayed = 0 userTurn = True # 1 means user, 2 means cpu isGameOver = False message = "Game draw" gameBoard = f''' {gameProgress[0]} | {gameProgress[1]} | {gameProgress[2]} --------- {gameProgress[3]} | {gameProgress[4]} | {gameProgress[5]} --------- {gameProgress[6]} | {gameProgress[7]} | {gameProgress[8]} ''' print(gameBoard) while not isGameOver and len(availablePositions) > 0: if userTurn: userInput = int(input("Enter the position number : ")) if userInput not in availablePositions: print("Invalid choice") continue availablePositions.remove(userInput) gameProgress[userInput - 1] = userChoice turnsPlayed += 1 else: cpuInput = random.choice(availablePositions) availablePositions.remove(cpuInput) gameProgress[cpuInput - 1] = cpuChoice if (turnsPlayed >= 3): for position in winningPositions: # position -> [0,1,2] # position -> [3,4,5] if gameProgress[position[0]] == gameProgress[position[1]] and gameProgress[position[1]] == gameProgress[position[2]]: isGameOver = True message = "User Won" if userTurn else "CPU won" break userTurn = not userTurn gameBoard = f''' {gameProgress[0]} | {gameProgress[1]} | {gameProgress[2]} --------- {gameProgress[3]} | {gameProgress[4]} | {gameProgress[5]} --------- {gameProgress[6]} | {gameProgress[7]} | {gameProgress[8]} ''' print(gameBoard) print(message) # if str.index('python') >= 0: # print('python found') # if userInput in availablePositions: print("Valid choice") # in, not in operators - membership operators # for position in availablePositions: # if position == userInput: # print("Valid choice")
a0efa53a3efb5ceab519f7814b6ff73a419a5357
fedegsancheza/POO
/Menu.py
819
3.859375
4
def opcion0(): print("Adiós") def opcion1(): print("Código de la opción 1") def opcion2(): print("Código de la opción 2") def opcion3(): print("Código de la opción 3") switcher = { 0: opcion0, 1: opcion1, 2: opcion2, 3: opcion3 } def switch(argument): func = switcher.get(argument, lambda: print("Opción incorrecta")) func() if __name__ == '__main__': bandera = False # pongo la bandera en falso para forzar a que entre al bucle la primera vez while not bandera: print("") print("0 Salir") print("1 Opción 1") print("2 Opción 2") print("3 Opción 3") opcion= int(input("Ingrese una opción: ")) switch(opcion) bandera = int(opcion)==0 # Si lee el 0 cambia la bandera a true y sale del menú
8d892b1efc16694a89666d6d429b6d1a98d0ecce
Rohit-83/pythonproblems
/prermnutationBacktrack.py
565
3.984375
4
#input = "ABC" #wap to print all permutation #output--> "ABC","BAC","CAB","ACB","BCA","CBA" string = "ABC" #we convert this into list bcz string object does not supporr changing and assignment output = list(string) n=len(string) l=0 r=n-1 def permutation(string,output,l,r): if l==r: print("".join(output),end = " ") else: for i in range(l,r+1): output[l],output[i] = output[i],output[l] permutation(string,output,l+1,r) #backtrack output[l],output[i] = output[i],output[l] return "" print(permutation(string,output,l,r))
02e8d20dddbfe8032b4ce26369424f33cd1b5525
imouiche/Python-Class-2016-by-Inoussa-Mouiche-
/Advance1.py
299
3.546875
4
def vowel(): vow = 'aeiouAEIOU' stence = raw_input(':') word = stence.split() d = 0 for w in word: W = [] d += 1 P = [] j = 0 for i in range(len(w)): if w[i] in vow: j +=1 P.append(i) W.append(w[i]) print '%d word:%s has %d vowels %s at position %s' %(d,w,j, W,P)
cb0189351a30a5a7129470815f64f6746e645430
SuyogRane/Air_flow
/plotgraphwrtanycity.py
389
3.609375
4
import pandas as pd import plotly.graph_objects as go df = pd.read_csv(r'new.csv') a=input("Enter the origin city") fig = go.Figure(go.Scatter(x = df['PASSENGERS_ON_WAY'], y = (df['AIRLINE_NAME']==a), name='Share Prices (in USD)')) fig.update_layout(title='airlines', plot_bgcolor='rgb(230, 230,230)', showlegend=True) fig.show()
ccfc52a9aada76726447ab8d04c816d4cfe86d64
keshavkummari/python-nit-930pm
/DataTypes/String/str_center_ljust_rjust.py
776
4.25
4
#!/usr/bin/python str = "Python0007" print(len(str)) print (str.rjust(20, '*')) print (str.ljust(25, '#')) """ 29 rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns. """ #!/usr/bin/python """2. center() Method: Note: Returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space. Syntax : str.center(width[, fillchar]) width -- This is the total width of the string. fillchar -- This is the filler character.""" abc_string_1 = "abcdef" abc_string = """abcd \ tools \ py \ """ print ("abc_string.center(10, 'K') : ", abc_string_1.center(11, '&')) print("") print ("abc_string.center(10, 'J') : ", abc_string.center(30, 'J'))
50521969ee7864b2d70c996c998bc189ecc0eeda
noufal85/make_a_developer
/algorithms/grokking_algorithms/divide_conquer.py
726
3.609375
4
""" the technique of D&C""" class DivideConquer: def __init__(self) -> None: pass def recursive_addition(self, array): if array == []: return 0 return array[0] + DivideConquer.recursive_addition(array) def recursive_length(self, array): if array == []: return 0 return 1 + DivideConquer.recursive_length(array) def recursive_max(self, array): """ Assumption: At least 2 elements passed, no equal elements""" if len(array) == 2: return array[0] if array[0] > array[1] else array[1] current_max = DivideConquer.recursive_max(array[1:]) return array[0] if array[0] > current_max else current_max
7c6e695bf1f71f984896eda3dcb9d0e28efe60fb
troykiim/Python
/lpthw/ex02.py
347
3.84375
4
#This program is from lesson 2 in "Learn Python the Hard Way" # A comment, this is o you can read your program later. # Anything after the # is ignored by python. print("I could have like this.") # and the comment after is ignored # You can also use a comment to "disable" or coment out code: # print("This won't run") print("This won't run")
e26244d008ac702c12bbdb824f662d557b7a4e8f
amangautam727/rep_1
/test_list1.py
213
3.859375
4
test_list =[1,2,3,3,3,4,5,5,6,7,8,9] print ('before=:'+str(test_list)) t = [] for i in test_list: if i in t: i='n' t.append(i) else: t.append(i) print ('after=:'+str(t))
8d5dd02cb5094fb569c37522daea8b0b64d6f26c
ishandutta2007/ProjectEuler-2
/euler/algorithm/assignment.py
5,643
3.859375
4
from copy import deepcopy as __deepcopy def hungarian_algorithm(m): """Using the "Hungarian Algorithm" to solve the "Assignment Problem".""" def one(): nonlocal step, cost for r in range(L): min_r = min(cost[r]) cost[r] = [c - min_r for c in cost[r]] step = 2 def two(): nonlocal step, mask, row_cover, col_cover for r in range(L): for c in range(L): if cost[r][c] == 0 and row_cover[r] == 0 and col_cover[c] == 0: mask[r][c] = 1 row_cover[r] = 1 col_cover[c] = 1 row_cover = [0 for i in range(L)] col_cover = [0 for i in range(L)] step = 3 def three(): nonlocal step, mask, col_cover for r in range(L): for c in range(L): if mask[r][c] == 1: col_cover[c] = 1 if sum(col_cover) == L: step = 7 else: step = 4 def four(): nonlocal step, mask, row_cover, col_cover, zero_r, zero_c def find_a_zero(): for r in range(L): for c in range(L): if cost[r][c] == 0 and row_cover[r] == 0 and col_cover[c] == 0: return r, c return (-1, -1) def star_in_row(r): for c in range(L): if mask[r][c] == 1: return True return False def find_star_in_row(r): for c in range(L): if mask[r][c] == 1: return c return -1 while True: r, c = find_a_zero() if r == -1: step = 6 return else: mask[r][c] = 2 if (star_in_row(r)): c = find_star_in_row(r) row_cover[r] = 1 col_cover[c] = 0 else: step = 5 zero_r = r zero_c = c return def five(): nonlocal step, mask, row_cover, col_cover, zero_r, zero_c def find_star_in_col(c): for r in range(L): if mask[r][c] == 1: return r return -1 def find_prime_in_row(r): for c in range(L): if mask[r][c] == 2: return c def augment_path(): nonlocal mask for p in range(path_count): if mask[path[p][0]][path[p][1]] == 1: mask[path[p][0]][path[p][1]] = 0 else: mask[path[p][0]][path[p][1]] = 1 def clear_covers(): nonlocal row_cover, col_cover row_cover = [0 for i in range(L)] col_cover = [0 for i in range(L)] def erase_primes(): nonlocal mask for r in range(L): for c in range(L): if mask[r][c] == 2: mask[r][c] = 0 path_count = 1 path = [[zero_r, zero_c]] done = False while not done: r = find_star_in_col(path[path_count - 1][1]) if r > -1: path_count += 1 path.append([r, path[path_count - 2][1]]) else: done = True if not done: c = find_prime_in_row(path[path_count - 1][0]) path_count += 1 path.append([path[path_count - 2][0], c]) augment_path() clear_covers() erase_primes() step = 3 def six(): nonlocal step, cost def find_smallest(): return min([cost[r][c] for c in range(L) for r in range(L) if row_cover[r] == 0 and col_cover[c] == 0]) minval = find_smallest() for r in range(L): for c in range(L): if row_cover[r] == 1: cost[r][c] += minval if col_cover[c] == 0: cost[r][c] -= minval step = 4 L = len(m) cost = __deepcopy(m) mask = [[0 for i in range(L)] for j in range(L)] row_cover = [0 for i in range(L)] col_cover = [0 for i in range(L)] zero_r = -1 zero_c = -1 step = 1 while True: if step == 1: one() elif step == 2: two() elif step == 3: three() elif step == 4: four() elif step == 5: five() elif step == 6: six() elif step == 7: return mask if __name__ == "__main__": def pretty_print_matrix(m): s = [[str(e) for e in row] for row in m] lens = [max(map(len, col)) for col in zip(*s)] fmt = '\t'.join('{{:{}}}'.format(x) for x in lens) table = [fmt.format(*row) for row in s] print ('\n'.join(table)) import random L = random.randint(3, 10) cost_mat = [[random.randint(1, 10 * L) for j in range(L)] for i in range(L)] mask_mat = hungarian_algorithm(cost_mat) min_assignment = sum([cost_mat[i][j] for j in range(L) for i in range(L) if mask_mat[i][j] == 1]) print ('Cost Matrix:') pretty_print_matrix(cost_mat) print ('\nMask Matrix:') pretty_print_matrix(mask_mat) print ('\nMinimun Assignment: {0}'.format(min_assignment))
d6a26db881fc0d188a46fe5c646136ffea53167a
StefanCondorache/Instructiunea_IF
/Problema_3_IF.py
544
3.671875
4
# Să se verifice dacă o literă introdusă este vocală sau consoană. # Exemplu : Date de intrare a Date de ieşire vocala. l=input("litera ") list1=["a","e","i","o","u","ă","î","â","A","E","I","O","U","Ă","Î","Â"] list2=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','ș','t','ț','v','w','x','y','z','B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','Ș','T','Ț','V','W','X','Y','Z'] if l in list1: print("vocală") elif l in list2: print("consoană") else: print("caracter greșit")
335e5dd25faa149115654b6f51943413e73ef814
AtheeshRathnaweera/Cryptography_with_python
/symmetric/streamCiphers/stream.py
718
3.765625
4
#Those algorithms work on a byte-by-byte basis. The block size is always one byte. #Two algorithms are supported by pycrypto: ARC4 and XOR. #Only one mode is available: ECB. (Electronic code book) from Crypto.Cipher import ARC4 def encryptionMethod(textToEncrypt): key = "myKeY" # can use any size of key obj1 = ARC4.new(key)#to encrypt obj2 = ARC4.new(key)#to decrypt cipher_text = obj1.encrypt(textToEncrypt) print("\tOriginal text: "+textToEncrypt) print ("\tEncrypted_text: "+str(cipher_text)) #decode("utf-8") use to decode bytes to string decrypted_text = obj2.decrypt(cipher_text) print("\tDecrypted result: "+decrypted_text.decode("utf-8")) encryptionMethod("atheesh")
09181b931083dc3f412ba0c95992cbc0638e3a2c
t4d-classes/advanced-python_04122021
/random_demos/gen_exp.py
262
4.15625
4
# fully enumerated when completed # double_nums = [x * 2 for x in range(10)] # list comprehension # enumerated as it is iterated over double_nums = (x * 2 for x in range(10)) # generator comprehension print(double_nums) for num in double_nums: print(num)
77a3f4cba65ef8330b85072e13fce70c23746f54
PlusWayne/Leetcode-solution
/504.base-7/base-7.py
383
3.625
4
class Solution: def convertToBase7(self, num): """ :type num: int :rtype: str """ res='' flag=0 if num==0: return '0' if num<0: num=-num flag=1 while num>0: remainder=num%7 res+=str(remainder) num//=7 return flag*'-'+res[::-1]
e5ebc2159c5ce57efe17f18511cf08cc62105511
juanjoneri/Bazaar
/Interview/Practice/Dynamic-Programming/subset-sum-divisible.py
418
3.890625
4
""" Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Input Constraints Input : arr[] = {3, 1, 7, 5}; m = 6; Output : YES Input : arr[] = {1, 6}; m = 5; Output : NO """ def subset_sum_divisible_by(numbers, divisor): if divisor < len(numbers): return True if not any(numbers): return False
ae3e1d3fcf9ffc4caff47f46bbaac7b6d8176528
dsbrown1331/Python2
/Recursion/fibonacci.py
483
4.125
4
def fib(n): """recursive function that returns the nth Fibonacci number where fib(0) = 0, fib(1) = 1 and fib(n) = fib(n-1) + fib(n-2) """ print("calling fib({})".format(n)) #base cases if n == 0: print("returning 0") return 0 elif n == 1: print("returning 1") return 1 else: return fib(n-1) + fib(n-2) fib(4) #testing code #for i in range(0,11): # print("The {}th Fibonacci number is {}".format(i, fib(i)))
1bfd02988e5f5ab4da9f83abc7b13b33517e408b
myohei/employee_mngr
/main.py
892
3.546875
4
# -*- coding: utf-8 -*- from EmployeeManager import EmployeeManager __author__ = 'yohei' def showMenu(): print(""" <MENU> ====================================== 1. 登録 2. 紹介 3. 削除 4. 更新(←時間なかったら実装しなくてもいい) ====================================== """) return True def main(): empMng = EmployeeManager() while True: showMenu() print(">>") i = input() if i == '1': empMng.createEmployee() pass elif i == '2': print("show") empMng.showEmployee() pass elif i == '3': empMng.deleteEmployee() print("delete") pass elif i == '4': print("update") pass else: print("不正な入力です") if __name__ == '__main__': main()
983f46fc18435d014eb6759652b64c85f031c25c
Liverworks/Python_dz
/7.formatting_comprehensions/search.py
741
3.59375
4
l = [1,4,5,3,6,7,0,2] def lin_search(l, el): """ :param l: list :param el: element to find :return: index of element found """ for ind, i in enumerate(l): if i == el: return ind def bin_search(l, el, ind=0): """ :param l: sorted list :param el: element to find :param ind: do not use :return: index of element found """ a = len(l)//2 if l[a] == el: return a + ind elif len(l) == 1: return "Element not in list!" elif l[a] > el: l = l[0:a] return bin_search(l, el) else: l = l[a:len(l)] return bin_search(l, el, ind = a + ind) print(lin_search(l, 1)) l = sorted(l) print(l) print(bin_search(l, 100))
8d4f9d015481649d301b23863eafb87d87aeb911
benbendaisy/CommunicationCodes
/python_module/examples/1376_Time_Needed_to_Inform_All_Employees.py
1,976
3.84375
4
from collections import defaultdict from typing import List class Solution: """ A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure. The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the employees about the urgent news. Example 1: Input: n = 1, headID = 0, manager = [-1], informTime = [0] Output: 0 Explanation: The head of the company is the only employee in the company. Example 2: Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] Output: 1 Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. The tree structure of the employees in the company is shown. """ def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int: def dfs(man, adj_list): max_time = 0 for sub in adj_list[man]: max_time = max(max_time, dfs(sub, adj_list)) return max_time + informTime[man] adj_list = defaultdict(list) for i in range(0, n): if manager[i] != -1: adj_list[manager[i]].append(i) return dfs(headID, adj_list)
4332ed9e09378c6c3d3d40e87dec26ebf9ee9938
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/203/35027/submittedfiles/testes.py
112
3.640625
4
#coding: utf-8 n=int(input('digite n: ')) soma=0 for i in range (1,2*n,1): soma=soma+(1/2*i) print(soma)
bd74d9469abb2ab017e3b92cff988a85a833800a
Segura91Jonathan/conversor_de_moneda
/diccionarios.py
567
3.734375
4
def run(): mi_diccionario = { "key1" : 1, "key2" : 2, "key3" : 3, } # print(mi_diccionario) # print(mi_diccionario["key1"]) poblacion_paises = { "argeintina" : 45000000, "china" : 1000000000, "colombia" :50372424, } # print(poblacion_paises["maiami"]) # for pais in poblacion_paises.values(): # print(pais) # for pais in poblacion_paises.keys(): # print(pais) for pais in poblacion_paises.items(): print(pais) if __name__ == "__main__": run()
28377694dba67e97023c7f348380721b2c6400f0
oOoSanyokoOo/Course-Python-Programming-Basics
/Номер числа Фибоначчи.py
134
3.59375
4
n = int(input()) a = 0 b = 1 i = 0 while a < n: b, a = a + b, b i += 1 if a == n: print(i) else: print(-1)
d564ef3c7a178cc19f45f9ae545bb1b8f0466577
karakumm/puzzle
/puzzle.py
3,086
3.9375
4
''' Playing board for logic puzzle ''' def check_column(board: list, column: int) -> bool: ''' Checks if the column is valid. Returns True if yes, and False if not. >>> check_column([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"\ ], 4) False ''' numbers = [] for i in range(len(board)): if board[i][column] != '*' and board[i][column] != ' ': if board[i][column] in numbers: return False numbers.append(board[i][column]) return True def check_row(board: list, row: int) -> bool: ''' Checks if the row is valid. Returns True if yes, and False if not. >>> check_row([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"\ ], 2) True ''' numbers = [] for i in range(len(board)): if board[row][i] != '*' and board[row][i] != ' ': if board[row][i] in numbers: return False numbers.append(board[row][i]) return True def check_colors(board: list) -> bool: ''' Checks if the block of each color is valid. Returns True if yes, and False if not. >>> check_colors([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"\ ]) True ''' new_board = [] for row in board: row = list(row) new_board.append(row) numbers = [] color_1 = [] for i in range(4, 9): color_1.append(new_board[i][0]) for j in range(1, 5): color_1.append(new_board[8][j]) numbers.append(color_1) color_2 = [] for i in range(3, 8): color_2.append(new_board[i][1]) for j in range(2, 6): color_2.append(new_board[7][j]) numbers.append(color_2) color_3 = [] for i in range(2, 7): color_3.append(new_board[i][2]) for j in range(3, 7): color_3.append(new_board[6][j]) numbers.append(color_3) color_4 = [] for i in range(1, 6): color_4.append(new_board[i][3]) for j in range(4, 8): color_4.append(new_board[5][j]) numbers.append(color_4) color_5 = [] for i in range(5): color_5.append(new_board[i][4]) for j in range(5, 9): color_5.append(new_board[4][j]) numbers.append(color_5) for lst in numbers: while ' ' in lst: lst.remove(' ') if len(set(lst)) != len(lst): return False return True def validate_board(board: list) -> bool: ''' Checks if the playing board is consistent with the rules. Returns True if yes, and False if not >>> validate_board([\ "**** ****",\ "***1 ****",\ "** 3****",\ "* 4 1****",\ " 9 5 ",\ " 6 83 *",\ "3 1 **",\ " 8 2***",\ " 2 ****"\ ]) False ''' for i in range(len(board)): if not check_column(board, i) or not check_row(board, i) or not check_colors(board): return False return True
191e907bfb294cf8ee8612feee9fd3779efdf926
ViartX/PyProject
/lesson5_2.py
719
4.375
4
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, # выполнить подсчет количества строк, количества слов в каждой строке. # функция принимает строку и возвразает число слов в строке def get_words_number_in_string(str): str_list = str.split() return len(str_list) f_text = open("lesson5_2.txt", 'r') str_num = 0 for line in f_text: str_num += 1 print(f" слов в строке {str_num} : {get_words_number_in_string(line)}") print(f"строк в файле : {str_num}") f_text.close()
87e23a56f8f847d0c10ce6ca3fc3e91a0f88920e
shreyansh-tyagi/leetcode-problem
/kth largest element in an array.py
510
3.96875
4
''' Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 Constraints: 1 <= k <= nums.length <= 104 -104 <= nums[i] <= 104 ''' class Solution: def findKthLargest(self, a: List[int], k: int) -> int: a.sort(reverse=True) return a[k-1]
2568ec91318cdf17e0596778514afd508fc63f81
PaLaMuNDeR/algorithms
/Coding Interview Bootcamp/11_steps.py
2,054
4.25
4
import timeit """ Write a function that accepts a positive number N. The function should console log a step shape with N levels using the # character. Make sure the step has spaces on the right hand side. Examples: steps(2): '# ' '##' steps(3): '# ' '## ' '###' steps(4): '# ' '## ' '### ' '####' """ def steps(n): """ Just iterating on the numbers in one for loop Time: 1.35 sec (with 123 steps) Time: 0.78 sec (with 10 steps) """ for i in range(0, n): # print ('#'*(i+1)+' '*(n-i+1)) return ('#'*(i+1)+' '*(n-i+1)) def steps_with_inner_loop(n): """ A solution wit double loop (outer and inner loop). hIterating on the rows and then on the columns. Add to the string and print. Time: 10 sec(with 123 steps) Time: 1.78 sec (with 10 steps) """ for row in range(0, n): stair = '' for column in range(0, n): if column <= row: stair += '#' else: stair += ' ' # print stair return stair def recursion_steps(n, row=0, stair=''): """A recursive solution Time: Maximum recursion depth exceeded (with 123 steps) Time: 33 sec (with 10 steps)""" if n == row: return elif n == len(stair): # print stair return recursion_steps(n, row+1) if len(stair) <= row: stair += '#' else: stair += ' ' recursion_steps(n, row, stair) # # elif n == 1: # print "#" # return "#" # else: # stra = "#" + str(recursion_steps(n-1))+"a" # print stra # return stra # steps(4) # steps_with_inner_loop(4) # recursion_steps(4) step_counter = 10 print "Method 1 - Single loop" print min(timeit.repeat(lambda: steps(step_counter))) print "Method 2 - Inner loop" print min(timeit.repeat(lambda: steps_with_inner_loop(step_counter))) print "Method 3 - Recursive solution" print min(timeit.repeat(lambda: recursion_steps(step_counter)))
01e30fe329eb82ef40a000faee97f9bab235e478
shadow-kr/My_python
/8_using_object_classe_make_player.py
1,528
3.78125
4
class gamer: #on cree le constructeur def __init__(self, name, hp,sp): #self est une base de données qui contient les elements contenus #self sert a affecter ces éléments name,hp... à la classe self.name = name self.hp = hp self.sp = sp self.weapon = None print("hello ", self.name,"\thp:",self.hp, "\tsp:",self.sp) #methode get:pour retourner un élément def get_name(self): return self.name def get_hp(self): return self.hp def get_sp(self): return self.sp #methode set:pour modifier def domage(self,domage): self.hp -=domage print('domage inflected:',domage) def attack_player(self,target_player): att = target_player.domage(self.sp-80) #domage(sp-80) --> hp=hp-sp-80 #palyers player1 = gamer("johnny",200,100) player2 = gamer("gyro",300,200) print('\n') # game player1.attack_player(player2) print(player1.get_name(), 'attacks', player2.get_name()) print('P1->level of health:',player1.get_hp()) print('\n') print('P2->level of health:',player2.get_hp()) print('\n') class weapon: def __init__(self,w_name,w_attak): self.w_name = w_name self.w_attak = w_attak def get_w_name(self): return self.w_name def get_w_attak(self): return self.w_attak knife = weapon('knife',30)
6b44f378ffc0e4cbb50255352b73cf766fbf76b6
ChandrakalaBara/PythonBasics
/basicAssignments/assignment14.py
475
4.25
4
# Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. # Suppose the following input is supplied to the program: # Hello world # Practice makes perfect # Then, the output should be: # HELLO WORLD # PRACTICE MAKES PERFECT inputLines = [] while True: line = input() if line: (inputLines.append(line.upper())) else: break result = '\n'.join(inputLines) print(result)
81cb27ebaefd0262ee26455c113e1f8d593f83a8
RobertooMota/Curso_Python
/PythonMundo1/Exercicios/ex005 - sucessor e antecessor.py
136
4.15625
4
num = int(input('Digite um numero: ')) print('Numero digitado: {}, seu antecessor {}, seu sucessor {}.'.format(num, num - 1, num + 1))
c52301af398193471e0f0b235a01a1a2507a6204
alex4245/python_design_patterns
/creational/prototype.py
1,004
3.828125
4
from abc import ABC, abstractmethod from copy import copy, deepcopy class Prototype(ABC): def __init__(self, type, value): self._type = type self._value = value @abstractmethod def clone(self): ... def __str__(self): return f"Type: {self._type}, value: {id(self._value)};" class ConcretePrototypeA(Prototype): def __init__(self, type, value): self._type = type self._value = value def clone(self): return self.__class__(f"copy_{self._type}", copy(self._value)) class ConcretePrototypeB(Prototype): def __init__(self, type, value): self._type = type self._value = value def clone(self): return self.__class__(f"copy_{self._type}", deepcopy(self._value)) value = [1, 2, 3] cpa = ConcretePrototypeA('concrete_prototype_a', value) cpb = ConcretePrototypeA('concrete_prototype_b', value) copy_1 = cpa.clone() copy_2 = cpa.clone() print(copy_1, copy_2) copy_3 = cpb.clone() print(copy_3)
4fc235960f4e8f99ecef246067175253bed36927
harishbharatham/Python_Programming_Skills
/Prob13_10.py
462
3.75
4
class Rational: def __init__(self, numerator = 0, denominator = 1): if denominator == 0: raise RuntimeError("Denominator cannot be zero") self.numerator = numerator self.denominator = denominator def main(): r1 = Rational() print("Default values: ", r1.numerator, r1.denominator) try: r2 = Rational(9,0) except RuntimeError as re: print(re) main()
c9538e5d5f297447373c5840fca322d0d0a1b0cf
StevenDunn/CodeEval
/Pangrams/py2/pan.py
425
3.5625
4
# Pangrams solution in Python 2 for CodeEval.com by Steven A. Dunn import sys, string for line in open(sys.argv[1], 'r'): line = line.rstrip('\n').lower() alphabet = set(string.ascii_lowercase) missing_letters = alphabet - set(line) if len(missing_letters) == 0: print "NULL" else: missing_letters = list(missing_letters) missing_letters.sort() for i in missing_letters: sys.stdout.write(i) print
7d2ac4d5ce584e9ed818623704f814e91b2b276f
SamArtGS/Python-Intermedio
/Agenda.py
1,532
3.640625
4
import os personas = {} while True: print("----- AGENDA -----") print("1.Capturar datos del contacto") print("2. Ver datos") print("3. Ver todos los contactos") print("4. Eliminar contacto") print("5. Salir") opcion = int(input("\nElige una opción: ")) if opcion == 1: nombre = input("Escribe el nombre de la persona: ") apellido = input("Escribe el apellido de la persona: ") telefono = input("Ingresa el teléfono de la persona: ") personas[nombre]=apellido f=open(nombre+apellido+".txt","w") f.write("Nombre: "+nombre+"\nApellido: "+apellido+"\nTeléfono: "+telefono) f.close() os.system("clear") elif opcion == 2: try: nombre = input("Escribe el nombre de la persona: ") apellido = input("Escribe el apellido de la persona: ") f= open(nombre+apellido+".txt","r") print("Datos: \n",f.read()) f.close() os.system("clear") except FileNotFoundError: print("No se encontrarion los datos de la persona especificada") os.system("clear") elif opcion == 3: print("Personas:\n") for clave,valor in personas.items(): # método que devuelve una lista de tuplas . . print(clave + " " + valor) os.system("clear") elif opcion == 4: nombre = input("Ingresa el nombre de la persona que deseas eliminar: ") apellido = input("Escribe el apellido de la persona: ") del personas[nombre] os.remove(nombre+apellido+".txt") os.system("clear") elif opcion == 5: print("Hasta luego") break else: print("Ingrese una opción válida") os.system("clear")
cd93953357e9662a46bec82f50578642b54da191
jschnab/data-structures-algos-python
/binary_trees/ast.py
1,246
4
4
class TimesNode: def __init__(self, left, right): self.left = left self.right = right def eval(self): return self.left.eval() * self.right.eval() def inorder(self): return "(" + self.left.inorder() + " * " + self.right.inorder() + ")" def postorder(self): return self.left.postorder() + " " + self.right.postorder() + " *" class PlusNode: def __init__(self, left, right): self.left = left self.right = right def eval(self): return self.left.eval() + self.right.eval() def inorder(self): return "(" + self.left.inorder() + " + " + self.right.inorder() + ")" def postorder(self): return self.left.postorder() + " " + self.right.postorder() + " +" class NumNode: def __init__(self, num): self.num = num def eval(self): return self.num def inorder(self): return str(self.num) def postorder(self): return str(self.num) def main(): a = NumNode(5) b = NumNode(4) c = NumNode(3) d = NumNode(2) t1 = TimesNode(a, b) t2 = TimesNode(c, d) root = PlusNode(t1, t2) print(root.postorder()) print(root.eval()) if __name__ == "__main__": main()
5c74493806318799d18233995adcae879213b8b2
tsh/python-algorithms
/intervals/free_time.py
2,711
3.6875
4
from __future__ import print_function from heapq import * """ For ‘K’ employees, we are given a list of intervals representing the working hours of each employee. Our goal is to find out if there is a free interval that is common to all employees. You can assume that each list of employee working hours is sorted on the start time. """ class Interval: def __init__(self, start, end): self.start = start self.end = end def print_interval(self): print(self) def __repr__(self): return "[" + str(self.start) + ", " + str(self.end) + "]" class EmployeeInterval: def __init__(self, employee, interval, index): self.employee = employee self.interval = interval self.interval_index = index def __lt__(self, other): return self.interval.start < other.interval.start def __repr__(self): return f'{self.employee}: {self.interval}' def find_employee_free_time(schedule): result = [] heap = [] employee_number = 0 while employee_number < len(schedule): heappush(heap, EmployeeInterval(employee_number, schedule[employee_number][0], 0)) employee_number += 1 longest_end = heap[0].interval.end while heap: heap_top = heappop(heap) if longest_end < heap_top.interval.start: # gap between intervals result.append(Interval(longest_end, heap_top.interval.start)) longest_end = heap_top.interval.end else: # intervals overlaps, check if new interval takes longer time if longest_end < heap_top.interval.end: longest_end = heap_top.interval.end # try to add new interval from same employee, if any employee_intervals = schedule[heap_top.employee] cur_interval_idx = heap_top.interval_index if cur_interval_idx + 1 < len(employee_intervals): heappush(heap, EmployeeInterval(heap_top.employee, employee_intervals[cur_interval_idx+1], cur_interval_idx+1)) return result def main(): input = [[Interval(1, 3), Interval(5, 6)], [Interval(2, 3), Interval(6, 8)]] print("Free intervals [3,5]: ") for interval in find_employee_free_time(input): interval.print_interval() input = [[Interval(1, 3), Interval(9, 12)], [Interval(2, 4)], [Interval(6, 8)]] print("Free intervals [4,6] [8,9]: ", end='') for interval in find_employee_free_time(input): interval.print_interval() input = [[Interval(1, 3)], [Interval(2, 4)], [Interval(3, 5), Interval(7, 9)]] print("Free intervals [5,7]: ", end='') for interval in find_employee_free_time(input): interval.print_interval() main()
4ae9f4d6e36c323d7b77fe4f4b3a099d59919078
PiaNgg/t07_chunga.huatay
/iterar_rango_01.py
298
3.53125
4
#Contador del 0 al 20 import os for c in range(int(os.sys.argv[1])): #funcion iterar para poder indicar las repetiiones del valor segun el rango dado print(c) #se imprime el valor de la variable c entre el rango indicado #fin_iterar_rango print("fin del bucle")#se imprime fin del programa
1e5d6989eb5e4f1f8544ca49a666a35c00cf1dd4
sonushahuji4/Competitive-Programming
/Bit Manipulation/Sum_vs_XOR.py
172
3.5625
4
# Problem Statement Link : https://www.hackerrank.com/challenges/sum-vs-xor/problem n = int(input()) ans = 1 while n > 0: if n % 2 == 0: ans *= 2 n = n // 2 print(ans)
f858a27380c7aae9e94cf975404586efbb09f392
AdityaPrakash-26/450dsa
/Jayvardhan/linked-list-cycle/linked-list-cycle.py
447
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: slow_p = head fast_p = head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return 1 return 0
d8a3b6f68a1baaf13380546fcb16a5c3e8ac29d9
GShyamala/GitRep_Selenium
/Py1/strings_concat.py
358
4.09375
4
name="johan" Age=123 print("Name is ",name,"Age is ",Age) print("Name is "+name+" Age is "+str(Age)) print("Name is {} and Age is {}".format(name,Age)) print("Name is {} and Age is {}".format(Age,name)) print("Name is %s and Age is %d" %(name,Age)) # print("Name is %d and Age is %s" %(name,Age)) ---- TypeError print(f"Name is {name} and Age is {Age}")
674a8ab1f9fecfcacb1765ab8e8a7f85f96cbc75
fp-computer-programming/cycle-3-labs-p22npiselli
/lab_3-1.py
322
3.96875
4
# Author: Nolan (AMDG) 9/29/2021 x = int(input("How many points did your team score? ")) if x >= 15: print("They won the gold") else: if x >= 12: print("They won a silver medal") else: if x < 9: print("No medal for you") else: print("They won the bronze")
0ccd3b335c86e1e7a612b4841de3f263bbe6f30f
matheusmendes58/Python_fundamentos1
/dia mes ano.py
157
3.6875
4
dia = input (" dia ") mes = input (" mes ") ano = input (" ano ") print("o dia que voçê nasceu é",dia,"e o mês é",mes,"e o ano",ano,"correto?")
982cb9a456c3f5b914ef793b1fb55ea3353d659c
Hanlen520/-
/随机数字验证码/随机数字短信验证码.py
686
3.5625
4
import random verification_code = "".join(list(map(str, random.sample(range(0, 10), 6)))) # 将随机出来的内容通过map函数转换成字符串,再使用list方法将字符串转成列表 print("接收到的验证码为:" + verification_code) while True: code_str = input("请输入验证码:").strip() if not code_str.isdigit(): print("必须输入为数字,请重新输入!") elif len(code_str) != 6: print("输入必须为六位数,请重新输入!") elif code_str == verification_code: print("输入正确,您可以修改用户信息了!") break else: print("输入错误,请重新输入!")
5c2c58bed2f1b98f88e82ec543cdf1f0c3eb1467
andreea-lucau/python-hello-world-package
/tests/greeting_test.py
1,008
3.609375
4
import unittest import hello.greeting class TestGreeting(unittest.TestCase): def test_get_greeting(self): expected_greeting = "Hello, Andreea!" greeting = hello.greeting.get_greeting("Andreea") self.assertEquals(greeting, expected_greeting) def test_get_greeting_name_not_valid(self): with self.assertRaises(hello.greeting.Error): hello.greeting.get_greeting("") def test_is_valid_name_no_digits(self): valid = hello.greeting.is_valid_name("1234456") self.assertFalse(valid) def test_is_valid_name_no_whitespaces(self): valid = hello.greeting.is_valid_name("andreea lucau") self.assertFalse(valid) def test_is_valid_name_no_lowercase_start(self): valid = hello.greeting.is_valid_name("andreea") self.assertFalse(valid) def test_is_valid_name(self): valid = hello.greeting.is_valid_name("Andreea") self.assertTrue(valid) if __name__ == '__main__': unittest.main()
d8b64968678545adcf435b459aa930ec9a25e0b2
aravinve/PySpace
/utils.py
137
3.6875
4
def find_max(numbers): maximum = numbers[0] for n in numbers: if n > maximum: maximum = n return maximum
abda5fe2dbda6f1e5f9149f05fb480388523a6ab
GSchpektor/Python-Bootcamp
/week.4/day.1/xp.py
787
4.15625
4
# Exercise 1 # print("hello world\n" * 3) # Exercise 2 # print((99^3) * 8) # Exercise 4 # computer_brand = "mac" # print(f"I have a {computer_brand} computer") # Exercise 5 # name = "Guillaume" # age = 27 # shoe_size = 45 # info = f"My name is {name}, I am {age}, i have an average shoe size - {shoe_size}, but i'm not average" # print(info) # Exercise 6 # age = int(input("how old are you")) # if age %2 == 0: # print(True) # else: # print(False) # Exercise 7 # name = input("what is your name?") # if name == "Guillaume": # print("I love you man") # else: # print("i'm sure God still loves you") # Exercise 8 # height = int(input("How tall are you in inches?")) # if (height*2.54) >= 145: # print("you can ride the coaster") # else: # print("you still need to grow")
5c1264a8054112fc718f238a692776fd5bec55d0
pythonarcade/arcade
/arcade/examples/background_scrolling.py
3,448
3.6875
4
""" A scrolling Background. This program loads a texture from a file, and create a screen sized background. The background is constantly aligned to the screen, and the texture offset changed. This creates an illusion of moving. If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.background_scrolling """ from __future__ import annotations import arcade import arcade.background as background SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = "Scrolling Background Example" PLAYER_SPEED = 300 class MyGame(arcade.Window): def __init__(self): super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE, resizable=True) self.camera = arcade.SimpleCamera() # Load the background from file. Sized to match the screen self.background = background.Background.from_file( ":resources:/images/tiles/sandCenter.png", size=(SCREEN_WIDTH, SCREEN_HEIGHT), ) # Create the player sprite. self.player_sprite = arcade.SpriteSolidColor(20, 30, color=arcade.color.PURPLE) self.player_sprite.center_y = self.camera.viewport_height // 2 self.player_sprite.center_x = self.camera.viewport_width // 2 # Track Player Motion self.x_direction = 0 self.y_direction = 0 def pan_camera_to_player(self): # This will center the camera on the player. target_x = self.player_sprite.center_x - (self.camera.viewport_width / 2) target_y = self.player_sprite.center_y - (self.camera.viewport_height / 2) self.camera.move_to((target_x, target_y), 0.05) def on_update(self, delta_time: float): new_position = ( self.player_sprite.center_x + self.x_direction * delta_time, self.player_sprite.center_y + self.y_direction * delta_time, ) self.player_sprite.position = new_position self.pan_camera_to_player() def on_draw(self): self.clear() self.camera.use() # Ensure the background aligns with the camera self.background.pos = self.camera.position # Offset the background texture. self.background.texture.offset = self.camera.position self.background.draw() self.player_sprite.draw() def on_key_press(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: self.x_direction -= PLAYER_SPEED elif symbol == arcade.key.RIGHT: self.x_direction += PLAYER_SPEED elif symbol == arcade.key.DOWN: self.y_direction -= PLAYER_SPEED elif symbol == arcade.key.UP: self.y_direction += PLAYER_SPEED def on_key_release(self, symbol: int, modifiers: int): if symbol == arcade.key.LEFT: self.x_direction += PLAYER_SPEED elif symbol == arcade.key.RIGHT: self.x_direction -= PLAYER_SPEED elif symbol == arcade.key.DOWN: self.y_direction += PLAYER_SPEED elif symbol == arcade.key.UP: self.y_direction -= PLAYER_SPEED def on_resize(self, width: int, height: int): super().on_resize(width, height) self.camera.resize(width, height) # This is to ensure the background covers the entire screen. self.background.size = (width, height) def main(): app = MyGame() app.run() if __name__ == "__main__": main()
b98dc59f32b3633381855c7677e64b3e1c194f45
malmike/BucketListAPI
/tests/models/test_user.py
5,307
3.65625
4
""" Contains tests for the user model """ from unittest import TestCase from time import sleep from tests.base_case import BaseCase from myapp.models.user import User class UserTests(BaseCase, TestCase): """ Class contains tests for the user model """ def test_user_is_inserted_in_db(self): """ Method checks that a user is added to the data """ user = User.query.filter_by(id=1).first() self.assertEqual( user.email, "test@test.com", "User was not created" ) def test_password_is_not_readable(self): """ Method checks that password is not readable """ user = User.query.filter_by(email="test@test.com").first() self.assertEqual(user.password, 'Password is only writable') def test_verify_password(self): """ Method that checks that the password is for the specific user """ user = User.query.filter_by(email="test@test.com").first() self.assertTrue( user.verify_password('test'), 'Password, matches email so it should return true' ) def test_wrong_password_false(self): """ Method checks that a wrong password returns false """ user = User.query.filter_by(email="test@test.com").first() self.assertFalse( user.verify_password('testing'), "Password doesnot match email so it should return false" ) def test_add_user(self): """ Method checks that add user method actually adds a user to the database """ _pword = "test" user = User(email='test@adduser.com', password=_pword, fname='Fname', lname="Lname") check = user.save_user() self.assertTrue(check, "User should be added") self.assertTrue( user.id, "User doesnot contain id so he is not added to the db" ) def test_no_repeated_users_added(self): """ Method checks that add user method actually adds a user to the database """ _pword = "test" user = User(email='test@test.com', password=_pword) check = user.save_user() self.assertFalse(check, "User should already exist") self.assertFalse( user.id, "User doesnot contain id so he is not added to the db" ) def test_delete_user(self): """ Method checks that a user can be deleted from the database """ #retrieve a test user from the database user = User.query.filter_by(email="test2@test.com").first() self.assertTrue(user) #delete the user from the database user.delete_user() verify_user = User.query.filter_by(email="test2@test.com").first() self.assertFalse( verify_user, "User that is deleted should not exist in the database" ) def test_bucketlist_list(self): """ Method tests that the bucket list relation in the user model returns a list of bucketlists specific to that user """ user = User.query.filter_by(email="test@test.com").first() self.assertTrue(isinstance(user.bucketlists, list)) def test_token_generation(self): """ Method tests that the generate token method returns a token """ token = self.create_token()['token'] self.assertTrue(isinstance(token, bytes)) def test_decode_token(self): """ Tests that the token created can be decoded """ token_values = self.create_token() self.assertTrue( token_values['user'].verify_authentication_token(token_values['token']) ) def test_token_expiration(self): """ Should expect false when the token expires """ token_values = self.create_token(duration=0.5, sleep_time=1) self.assertFalse( token_values['user'].verify_authentication_token(token_values['token']) ) def test_token_aulteration(self): """ Method should expect a false due to aulteration of the authentication token """ token_values = self.create_token() a = 'a'.encode('utf-8') token = token_values['token'] + a self.assertFalse( token_values['user'].verify_authentication_token(token) ) def test_token_distinct(self): """ Tests that a token is distinct i.e can not generate the same token after token expiry """ token1 = self.create_token(duration=0.5, sleep_time=1)['token'] token2 = self.create_token(duration=0.5)['token'] self.assertNotEqual(token1, token2) def create_token(self, duration=300, sleep_time=0): """ Method is used to call the generate_authentication_token and returns a token """ user = User.query.filter_by(email="test@test.com").first() token = user.generate_authentication_token(duration=duration) sleep(sleep_time) return {"user": user, "token":token}
add8560a7cf81a8e057ba0de908fa8f0f76a2607
saji021198/player-set-1
/fact.py
80
3.65625
4
h=int(input()) fact=1 for i in range (1,h+1) : fact=fact*i print(fact)
d5c296062bb36c3063656eae5508d866a7947673
aliyarahman/code_that_only_does_one_thing
/v1-2018/read_a_csv/OurFirstCSVReader.py
898
4.09375
4
import csv #Python uses 'packages' to hold a set of tools you don't use all the #time. But you can import them when you need them. CSV is a package of tools for #working on CSVs. with open('the_file_name.csv', 'rb') as csvfile: event_file_reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in event_file_reader: print row[0], row[1] # Working with a csv file always has these parts: #--------------------------------------------------- # A line (like line 7) to open the file that tells the computer which file # you want to open and some options to help it understand how that file is laid out. # A line (like line 8) that tells Python how to save the info from the csv in its own # language. # A line (like line 9) that starts the for loop that will cycle through all the rows # Then, the print line prints out the value from the first and second columns for each row
bf33ee135f6849481448cab4d99177c93bdd3ff7
luanrr98/Logica-Computacao-e-Algoritmos-Lista1
/Exercicio9.py
340
4.125
4
#Crie um algoritmo que calcule a área de um quadrado, sendo que o comprimento do lado é informado pelo usuário. #A área do quadrado é calculada elevando-se o lado ao quadrado. def area_quadrado(lado): area = lado**2 print(f"A Área do Quadrado é: {area}") lado = float(input("Digite o valor do lado: ")) area_quadrado(lado)
50f7d5611010a43965b0231838bd061ec67309d1
abhikrish06/PythonPractice
/DIC/Ch3/ch3_6.py
1,291
4.03125
4
import pandas as pd # Making data frame from a dictionary # that maps column names to their values df = pd.DataFrame({ "name": ["Bob", "Alex", "Janice"], "age": [60, 25, 33] }) # Reading a DataFrame from a file other_df = pd.read_csv("C:/Krishna/UB/Spring18/CSE 574 ML/proj1/slump_test_data.csv") # Making new columns from old ones # is really easy df["age_plus_one"] = df["age"] + 1 df["age_times_two"] = 2 * df["age"] df["age_squared"] = df["age"] * df["age"] df["over_30"] = (df["age"] > 30) # this col is bools # The columns have various built-in aggregate functions total_age = df["age"].sum() median_age = df["age"].quantile(0.5) # You can select several rows of the DataFrame # and make a new DataFrame out of them df_below50 = df[df["age"] < 50] # Apply a custom function to a column df["age_squared"] = df["age"].apply(lambda x: x*x) print(df) ##################### df2 = pd.DataFrame({ "name": ["Bob", "Alex", "Jane"], "age": [60, 25, 33] }) print(df2.index) # prints 0‐2, the line numbers # Create a DataFrame containing the same data, # but where name is the index df_w_name_as_ind = df2.set_index("name") print(df_w_name_as_ind.index) # prints their names # Get the row for Bob bobs_row = df_w_name_as_ind.ix["Bob"] print(bobs_row["age"]) # prints 60 print(df2)
5cbb2241ff1d7cccda2b84f49670d87ce47a2970
Ajay-2007/Python-Codes
/hackerrank/Python/Introduction/python_if-else.py
395
4
4
# Problem Link # https://www.hackerrank.com/challenges/py-if-else #!/bin/python3 import math import os import random import re import sys def main(n): if n%2: print("Weird") elif 2 <= n <= 5: print("Not Weird") elif 6<= n <= 20: print("Weird") else : print("Not Weird") if __name__ == '__main__': n = int(input().strip()) main(n)
6d29c28531f5603ff8757d946cbfd2af80b0b064
jmederosalvarado/daa-project
/icpc-finals/fibonacci-words/article/code.py
849
3.609375
4
# Nota: Este codigo solo cumple función ilustrativa # en el artículo, para ver una versión # completamente funcional, vea la carpeta solutions def kmp(text, pattern): pass def fibonacci_words(n, p): dp = [0]*(n+2) dp[0] = 1 if p == '0' else 0 dp[1] = 1 if p == '1' else 0 prefix, suffix = ['0', '1'], ['0', '1'] m = len(p) - 1 for i in range(2, n+1): center = (suffix[i-1][-m:] + prefix[i-2][:m] if m > 0 else '') dp[i] = dp[i-1] + dp[i-2] + kmp(center, p) if len(prefix[i-1]) >= len(p) - 1: prefix.append(prefix[i-1]) else: prefix.append(prefix[i-1] + prefix[i-2]) if len(suffix[i-2]) >= len(p) - 1: suffix.append(suffix[i-2]) else: suffix.append(suffix[i-1] + suffix[i-2]) return dp[n]
3dde3c6f74b194239bbde9667ecda89e13339450
hyperion-mk2/git
/Remove Duplicates from Sorted Array.py
489
3.765625
4
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ deletenum = 0 index = 0 while index < len(nums) - 1: if(nums[index] == nums[index+1]): nums.pop(index) deletenum += 1 else: index += 1 return nums if __name__ == "__main__": nums =[1,2,2,1,1] Solution.removeDuplicates(Solution, nums) print(nums)
df96413aa70595868b7097afa7d26da23fb78d29
Parzha/First_assignment
/ex3.py
1,953
4.28125
4
def BMI_calculator(W,H): H=H/100 return(W/pow(H,2)) def BMI_calculator_american(W,H): return((W/pow(H,2))*703) flag=1 while(flag==1): print("What measurment do you prefer => for kg/cm type 1 or for pounds/inches type 2 ") user_perference=int(input()) if user_perference==1: flag=0 user_weight=int(input("please enter your weight in kg")) user_height=int(input("please enter your height in cm")) BMI = BMI_calculator(user_weight, user_height) if 18.5<BMI<24.9: print("with this",BMI,"you are Normal") elif BMI<18.5: print(("with this",BMI,"you are Underweight eat something for god sake")) elif 25<BMI<29.9: print("with this", BMI, "you are Overweight bro it's time to go to gym") elif 30<BMI<34.9: print("with this", BMI, "you are Obese STOP EATING YOU NEED TO VISIT A DOCTOR") else: print("with this", BMI, "you are Extremely Obese YOU NEED SOME SERIOUS TREATMENT MY FRIEND") elif user_perference ==2: flag = 0 user_weight = int(input("please enter your weight in pounds")) user_height = int(input("please enter your height in inches")) BMI = BMI_calculator(user_weight, user_height) if 18.5 < BMI < 24.9: print("with this", BMI, "you are Normal") elif BMI < 18.5: print(("with this", BMI, "you are Underweight eat something for god sake")) elif 25 < BMI < 29.9: print("with this", BMI, "you are Overweight bro it's time to go to gym") elif 30 < BMI < 34.9: print("with this", BMI, "you are Obese STOP EATING YOU NEED TO VISIT A DOCTOR") else: print("with this", BMI, "you are Extremely Obese YOU NEED SOME SERIOUS TREATMENT MY FRIEND") else: print("invalid input try again")
e92b91d5f7c47045a004078478b788235d3bd54a
95subodh/Leetcode
/069. Sqrt(x).py
182
3.703125
4
#Implement int sqrt(int x). # #Compute and return the square root of x. class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ return int(x**0.5)
c524d8fd919167cc6d1ccb28f301bb5da90744c5
saad181/CSPP1
/module 5/p4/square_root_newtonrapson.py
621
4
4
# Write a p_numthon program to find the square root of the given number '''writing newton rapson method to find square''' # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 def main(): '''using newton raphson method''' # epsilon and step are initialized # don't change these values # _numour code starts here _num = int(input()) epsilon = 0.01 guess = _num/2.0 while (guess**2-_num) >= epsilon: guess = guess - (((guess**2)-_num)/(2*guess)) print(guess) if __name__ == "__main__": main()
86d627967d3becda11b8579fce200bc1aaa36f13
gburdge/python-exercises
/Project 5/Project 5.py
357
3.671875
4
from datetime import date with open("dates.txt") as f: lines = f.readlines() # f represents file with data lines = [int(l) for l in lines] t = date.today() # t represents today for l in lines: # l represents line d1 = date.fromtimestamp(l) td = d1-t # td represents today's date print "%s is happening in %s days" % (d1, td.days)
4d62cba71ad14de4792ecdaa9ad0ffe56e796ef8
JLMunozOl/curso-python-1
/clases/clases.py
3,180
3.953125
4
#!/usr/bin/env python3 from math import pi class Foo(object): a = 1 b = "Soy Foo" class Gato(object): numero_de_patas = 0 color = "negro" cv = "" def __init__(self, nombre="Juan"): self.nombre = nombre def dormir(self): print("Yo el gato {} estoy durmiendo. Zzzz...".format(self.nombre)) def molestar_humano(self): while True: acariciar = input( "Acariciame a mi, el gato {}".format( self.nombre)) if acariciar == "Acariciado": break gato = Gato() gato.numero_de_patas = 4 gato.color = "marron" print( "El gato tiene {} patas y es de color {}".format( gato.numero_de_patas, gato.color)) print("El gato {} tiene {} patas y es de color {} ".format( gato.nombre, gato.numero_de_patas, gato.color)) ################################ # Implementación de la esfera. # ################################ class Esfera(object): """Implementación de una clase que representa una esfera en python. Define los métodos: - getRadio(self) :: Regresa el radio de la esfera - superficie(self) :: Regresa el valor total de la superficie de la esfera - volumen(self) :: Regresa el volumen total de la esfera """ def __init__(self, radio=1): """Método constructor, recibe el radio de la esfera. En caso de que no sea provisto, este va tomar el valor de 1 por defecto.""" self.radio = radio def getRadio(self): """Regresa el radio de la esfera""" return self.radio def volumen(self): """Calcula el volumen de la esfera utilizando la formula (4*pi*radio**3)/3""" return (4 * pi * (self.radio ** 3)) / 3 def superficie(self): """Calcula la superficie de la esfera utilizando la formula 4*pi*radio**2""" return 4 * pi * (self.radio ** 2) ############ # Herencia # ############ class Animal(object): nombre = "" class Perro(Animal): color = "" def __init__(self, nombre, color): self.color = color self.nombre = nombre def descripcion(self): print("El perro {} es de color {} ".format(self.nombre, self.color)) class Gato1(Animal): patas = 0 def __init__(self, nombre, patas=4): self.nombre = nombre self.patas = patas def descripcion(self): print("El gato {} tiene {} patas ".format(self.nombre, self.patas)) ################ # Polimorfismo # ################ class Persona(object): def __init__(self, identificacion, nombre, apellido): self.identificacion = identificacion self.nombre = nombre self.apellido = apellido def __str__(self): return " {}: {} {} ".format( self.identificacion, self.apellido, self.nombre) class Alumno(Persona): def __init__(self, identificacion, nombre, apellido, padron): Persona.__init__(self, identificacion, nombre, apellido) self.padron = padron def __str__(self): return "{}: {} {}".format(self.padron, self.apellido, self.nombre) def imprimir(persona): print(persona)
4a4c9a78851d100e6b08ce93a43aa1410c47ee8c
Jawaharbalan/python-programing
/oddeven.py
165
3.84375
4
import sys try: a=int(input("input:")) except ValueError: print ("Error..numbers only") sys.exit() if(a%2==0): print("even") else: print("odd")
ea36e998000a658daf09bb2d7c165be3f525baac
dogeplusplus/Python-Projects
/Data Science from Scratch/Histogram.py
793
3.734375
4
from matplotlib import pyplot as plt from collections import Counter grades = [83,95,91,87,70,0,85,82,100,67,73,77,0] decile = lambda grade : grade // 10 * 10 histogram = Counter(decile(grade) for grade in grades) plt.bar([x - 4 for x in histogram.keys()],histogram.values(),8) plt.axis([-5,105,0,5]) plt.xticks([10 * i for i in range(11)]) plt.xlabel("Decile") plt.ylabel("# of students") plt.title("Distribution of exam grades") plt.show() mentions = [500,505] years = [2013, 2014] plt.bar([2012.6,2013.6], mentions, 0.8) plt.xticks(years) plt.ylabel('# of times I heard someone say "data science"') plt.ticklabel_format(useOffset=False) plt.axis([2012.5,2014.5,0,506]) plt.title("Look at the 'huge' increase") plt.ylabel('# of times i heard soemone say data science') plt.show()
d3d0a62c5ec422a61807dba09fee5fb8414dfa37
vampypandya/LeetCode
/146. LRU Cache.py
1,479
3.546875
4
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.drum = {} self.cap = capacity self.latest = [] def get(self, key): """ :type key: int :rtype: int """ # print key,self.drum if (key in self.drum): val = self.drum[key] self.drum.pop(key) self.drum[key] = val if (key not in self.latest): self.latest.append(key) else: self.latest.remove(key) self.latest.append(key) return val return -1 def put(self, key, value): """ :type key: int :type value: int :rtype: None """ # self.latest = key # print "PUT",key,self.latest,self.drum if (key in self.drum): self.drum[key] = value else: if (len(self.drum.keys()) == self.cap): self.drum.pop(self.latest[0]) self.latest.remove(self.latest[0]) self.drum[key] = value else: self.drum[key] = value if (key not in self.latest): self.latest.append(key) else: self.latest.remove(key) self.latest.append(key) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
ad53c130d412a4516d37140ce11350cb2f3e6b7a
Beasted1010/MachineLearning_Assignment
/hw3reg.py
1,106
3.546875
4
import pandas as pd from sklearn import linear_model from sklearn.metrics import mean_squared_error housing_data_set = pd.read_csv('boston_housing.txt', header=None) housing_data_set = housing_data_set.values #print(housing_data_set) shape_list = housing_data_set.reshape(housing_data_set.shape[0]) split_list = [val.split() for val in shape_list] float_list = [ [float(y) for y in x] for x in split_list ] median_values = [x[13] for x in float_list] features = [x[:13] for x in float_list] # Training set X_train = features[:400] Y_train = median_values[:400] # Test set X_test = features[400:] Y_test = median_values[400:] #Linear regression object regr = linear_model.LinearRegression() # Train the model regr.fit(X_train, Y_train) # Make the prediction housing_pred = regr.predict(X_test) #print(housing_pred) #print('\n\n') #print(Y_test) # Compute the error print("Mean squared error: {}".format(mean_squared_error(Y_test, housing_pred))) #Plot output #import matplotlib.pyplot as plt #plt.scatter(X_test, Y_test, color='black') #plt.plot(X_test, housing_pred, color='blue', linewidth=3)
d1e18fb781aeaba07da06e92206b178f04d5af60
erjan/coding_exercises
/network_delay_time.py
1,941
3.8125
4
''' You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target. We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1. ''' class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: adj_list = defaultdict(list) for x,y,w in times: adj_list[x].append((w, y)) visited=set() heap = [(0, k)] while heap: travel_time, node = heapq.heappop(heap) visited.add(node) if len(visited)==n: return travel_time for time, adjacent_node in adj_list[node]: if adjacent_node not in visited: heapq.heappush(heap, (travel_time+time, adjacent_node)) return -1 --------------------------------------------------------------------------------------------------------------- import heapq from collections import defaultdict def f(times, N, K): elapsedTime = [0] + [float("inf")] * N graph = defaultdict(list) # it's a min-heap heap = [(0, K)] for u, v, w in times: graph[u].append((v, w)) print(graph) while heap: time, node = heapq.heappop(heap) if time < elapsedTime[node]: elapsedTime[node] = time for v, w in graph[node]: heapq.heappush(heap, (time + w, v)) mx = max(elapsedTime) return mx if mx < float("inf") else -1 if __name__ == '__main__': times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]] n = 4 k = 2 f(times, n, k)
eb8a5f62736252db16bcccccd378be78dc7e9268
vishantbhat/myfiles
/test-files.py
1,039
3.953125
4
""" my_input_file = open("hello.txt", "r") print ("Line 0 (first line):", my_input_file.readline()) my_input_file.seek(0) # jump back to beginning print("Line 0 again:", my_input_file.readline()) print("Line 1:", my_input_file.readline()) my_input_file.seek(8) # jump to character at index 8 print("Line 0 (starting at 9th character):", my_input_file.readline()) my_input_file.seek(10, 1) # relative jump forward 10 characters print("Line 1 (starting at 11th character):", my_input_file.readline()) my_input_file.close() """ # Review Exercises #1 """ poem_file = open("poetry.py", "r") line = poem_file.readline() while line != "": print line line = poem_file.readline() poem_file.close() #2 with open("poetry.py", "r") as poetry_file: for lines in poetry_file: print lines """ #3 ## Poetry file in read mode read_poem = open("poetry.py","r") ## Output file in write mode write_op = open("output.txt","w") lines = read_poem.readline() for line in lines: write_op.writelines(line) read_poem.close() write_op.close()
9834c629e5cf95ab25c168db1b36afbbb5ddc733
Sahil4UI/PythonJan3-4AfternoonRegular2021
/list exercise.py
1,596
4.03125
4
#store numbers from 1-10 in list '''x= [] for i in range(1,11): x.append(i) print(x) ''' #list comprehension ''' x = [i for i in range(1,11)] print(x) ''' # #find the largest element from the list ''' x = [-100,1,1000000,2,1000000,1000000,1000000,5,900,2000] largest = -9999999999 secondLargest = -888888888 for i in range(0,len(x)): if x[i]>largest: largest,secondLargest = x[i],largest elif x[i]>secondLargest: secondLargest = x[i] print(largest) print(secondLargest) ''' ''' x = [-100,1,1000000,2,1000000,1000000,1000000,5,900,2000] y=[] for i in range(0,len(x)): if x[i] not in y: y.append(x[i]) print(y) ''' #sort the list in ascending order ''' x = [1,89,23,98,34,-100,20] for i in range(0,len(x)): for j in range(i+1,len(x)): if x[i] > x[j]: x[i],x[j] = x[j],x[i] print(x) ''' ''' x = [1,89,23,98,34,-100,20] user = int(input("Enter Number :")) if user in x: print("Found") else: print("Not Found") ''' #linear Search & binary Search, #linear Search x = [1,89,23,98,34,-100,20] ''' for i in range(0,len(x)): if user == x[i]: print(f"{user} found at {i}") break else: print("Not found") ''' #binary Search #list must be sorted x = [1,89,23,98,34,-100,20] user = int(input("Enter Number :")) x.sort() left =0 right = len(x)-1 while left<=right: mid = (left+right)//2 if user > x[mid]: left = mid+1 elif user == x[mid]: print(f"{user} found at {mid}") break else: right = mid-1 else: print("value not found")
bc44d40fa8ca4f4de80c2e56a0d6c4d3a3ae7d5c
projeto-de-algoritmos/Grafos1_Labirintite
/main.py
2,250
3.515625
4
import random import pygame import queue from Constantes import size, cols, rows, width, GREY import Theme import maze_generator as mg from Cell import Cell, removeWalls, reload_colors from importlib import reload pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Maze Generator") opt = 0 while opt > 2 or opt < 1: opt = int(input("1- DFS \n2- BFS\n3- Mudar Tema\n")) if opt == 3: new_theme = Theme.next_theme() reload_colors() print("\n"*50, "\nTema definido para:", new_theme) done = False clock = pygame.time.Clock() stack = [] queue = queue.Queue() grid = mg.generate() grid[0][0].caller = grid[0][0] finded = False current_cell = grid[0][0] # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True current_cell.current = True current_cell.visited = True if(current_cell.goal == True): finded = True for y in range(rows): for x in range(cols): grid[y][x].draw(screen) next_cells = current_cell.getNextCell() if opt == 1: if finded and len(stack): current_cell.path = True current_cell.current = False current_cell = stack.pop() elif len(next_cells) > 0: current_cell.neighbors = [] stack.append(current_cell) current_cell.current = False current_cell = next_cells[0] elif len(stack) > 0: current_cell.current = False current_cell = stack.pop() elif opt == 2: for cell in next_cells: cell.queued = True cell.caller = current_cell queue.put(cell) if finded: current_cell.path = True current_cell.current = False current_cell = current_cell.caller elif queue.qsize() > 0: current_cell.current = False current_cell = queue.get() clock.tick(100) pygame.display.flip() a = input() pygame.quit()
5c98f1d881b88a6dae99e17a5fc5d2682d8923e9
barrymun/euler
/30-39/38.py
942
3.828125
4
MAX_LEN = 9 DIGIT_CHECK = [str(i) for i in xrange(1, 10)] def derive_pandigital(n): """ """ r = "" x = 1 while len(r) < 9: r += str(n * x) x += 1 return r def has_pandigital_multiples(n): """ """ r = "" x = 1 while len(r) < 9: r += str(n * x) x += 1 if is_pandigital(n=r): return True return False def is_pandigital(n): """ """ n = str(n) if len(n) > MAX_LEN or len(n) < MAX_LEN: # sanity check return False # can do this but seems to be slower return set(DIGIT_CHECK) == set(n) # ... check = True for digit in DIGIT_CHECK: if digit not in n: check = False break return check if __name__ == "__main__": i = None for i in xrange(9, 98766): if has_pandigital_multiples(n=i): r = i print r print derive_pandigital(n=r)
5bc66a4c52a3bbb68b6bdad3115a77c4ab254e08
savlino/2019_epam_py_hw
/03-fp-decorator/hw2.py
471
3.96875
4
""" function is_armstrong allows to check if the given number is one of Armstrong(narcissistic) numbers """ import functools def is_armstrong(int_number): number = str(int_number) digits = [int(number[x]) for x in range(len(number))] dig_sum = functools.reduce(lambda x, y: x + y**len(number), digits) return int_number == dig_sum assert if is_armstrong(153) is True, 'Armstrong number' assert if is_armstrong(10) is False, 'not an Armstrong number'