blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
26d60373ba20e7c396d6b3c3eb3d41e21eca9b0c
rohangoli/PythonAdvanced
/Leetcode/Queue & Stack/p1337.py
4,649
3.96875
4
## Design Circular Queue # Example 1: # Input # ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"] # [[3], [1], [2], [3], [4], [], [], [], [4], []] # Output # [null, true, true, true, false, 3, true, true, true, 4] # Explanation # MyCircularQueue myCircular...
8c21e39689213672f21000b4c89f275774dbdbf8
rohangoli/PythonAdvanced
/Leetcode/Binary Trees/p110.py
1,281
3.875
4
## 110. Balanced Binary Tree # Example 1: # Input: root = [3,9,20,null,null,15,7] # Output: true # Example 2: # Input: root = [1,2,2,3,3,null,null,4,4] # Output: false # Example 3: # Input: root = [] # Output: true # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, rig...
886ac89206db08b18aba70ecf92eb88d4c59061b
rohangoli/PythonAdvanced
/ParallelProgramming/p5_UsingEnumerate.py
108
3.609375
4
numbers = [1,2,3] # Enumerate gets the both index and value for i,j in enumerate(numbers): print i,j**2
f7dd236bcc363ebb96e481d4728c28dd1131d669
rohangoli/PythonAdvanced
/Leetcode/Binary Search/p948.py
1,461
3.984375
4
## Find Peak Element # Example 1: # Input: nums = [1,2,3,1] # Output: 2 # Explanation: 3 is a peak element and your function should return the index number 2. # Example 2: # Input: nums = [1,2,1,3,5,6,4] # Output: 5 # Explanation: Your function can return either index number 1 where the peak element is 2, or index nu...
45f78e884aeae0708f75f37b4454f301c8e69493
rohangoli/PythonAdvanced
/Leetcode/Queue & Stack/p1391.py
1,005
3.96875
4
## Keys and Rooms # Example 1: # Input: rooms = [[1],[2],[3],[]] # Output: true # Explanation: # We visit room 0 and pick up key 1. # We then visit room 1 and pick up key 2. # We then visit room 2 and pick up key 3. # We then visit room 3. # Since we were able to visit every room, we return true. # Example 2: # Inpu...
fb7d9005836f314130988068ddb85ab99615485f
rohangoli/PythonAdvanced
/Leetcode/HashTable/p1140.py
2,110
4.03125
4
## Design HashMap # Example 1: # Input # ["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] # [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] # Output # [null, null, null, 1, -1, null, 1, null, -1] # Explanation # MyHashMap myHashMap = new MyHashMap(); # myHashMap.put(1, 1); // The map is ...
b26e503efa73c40df3de2622245f1c343b909416
rohangoli/PythonAdvanced
/Leetcode/HashTable/p1131.py
583
3.703125
4
## Happy Number # Example 1: # Input: n = 19 # Output: true # Explanation: # 12 + 92 = 82 # 82 + 22 = 68 # 62 + 82 = 100 # 12 + 02 + 02 = 1 # Example 2: # Input: n = 2 # Output: false class Solution: def isHappy(self, n: int) -> bool: tempSet=set() while n not in tempSet: tem...
ab7cd8aebc2666bc3247edca551d2e40e0d51c32
rohangoli/PythonAdvanced
/Leetcode/Binary Trees/p230.py
646
3.546875
4
## 230. Kth Smallest Element in BST # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: ...
53e981dd0962cfce15c4975b575c98d86049444d
rohangoli/PythonAdvanced
/Leetcode/Arrays/p3259.py
1,643
3.859375
4
## Replace Elements with Greatest Element on Right Side # Example 1: # Input: arr = [17,18,5,4,6,1] # Output: [18,6,6,6,1,-1] # Explanation: # - index 0 --> the greatest element to the right of index 0 is index 1 (18). # - index 1 --> the greatest element to the right of index 1 is index 4 (6). # - index 2 --> the gr...
1912ddf3986cbf6704d30c778e548b838727f4aa
rohangoli/PythonAdvanced
/Leetcode/HashTable/p1105.py
534
3.921875
4
## Intersection of Two Arrays # Example 1: # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # Example 2: # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # Explanation: [4,9] is also accepted. class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: res...
496a7816bc06781a0f66278a8d6998a459e73d29
rohangoli/PythonAdvanced
/Leetcode/Trie/p1047.py
2,071
4.28125
4
## Implement Trie (Prefix Tree) # Example 1: # Input # ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] # [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] # Output # [null, null, true, false, true, null, true] # Explanation # Trie trie = new Trie(); # trie.insert("apple"); # tri...
70b05165e669cc709a9aa5ba2ba890565054a03e
rohangoli/PythonAdvanced
/Leetcode/LinkedList/p1215_v2.py
946
3.515625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: tempA = headA tempB = headB while tempA!=temp...
897860213eab0bfe18cbb1fa911662a249d3d4de
rohangoli/PythonAdvanced
/Leetcode/Arrays/p1173.py
944
3.796875
4
## Remove Duplicates from Sorted Array # Example 1: # Input: nums = [1,1,2] # Output: 2, nums = [1,2,_] # Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. # It does not matter what you leave beyond the returned k (hence they are underscores). # Example 2:...
b45d1cfa57e9567283c358a4a4296f48e086d564
rohangoli/PythonAdvanced
/TensorFlow/p3(intro2pandas).py
892
3.5625
4
import pandas as pd city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) print city_names print population sampleDF = pd.DataFrame({ 'City name': city_names, 'Population': population }) print sampleDF california_housing_dataframe = pd.read_csv("http...
1e91375b76beeb94480539720ad62296270510b7
rohangoli/PythonAdvanced
/HackerRank/10-days-of-statistics/inter-quartile-range.py
785
4.03125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT # Enter your code here. Read input from STDIN. Print output to STDOUT def median(val_list): n=len(val_list) val_list.sort() if(n%2==0): return (val_list[int(n/2)]+val_list[int(n/2 - 1)])/2 else: return val_list[int(n/...
13b3454db70bdc450b4b7834b83b142f5df074ea
Yu-TingWang/DS_algo
/DS/Heap/binomial/BinomialHeap/union.py
1,925
3.765625
4
from DS.Heap.binomial import BinomialNode as Node from DS.Heap.binomial import BinomialHeap as Heap from DS.Heap.binomial.BinomialHeap import merge def union(h1: Heap, h2: Heap) -> Heap: """ This takes O(log n) time. Creates and returns a new heap that contains all nodes of heaps h1,h2 by : repeatedly mer...
a9640d650c40c67b68f8ac704fce37c197ce1a40
zlzack/langjin
/demo02.py
1,178
3.71875
4
# shuju = {} # while 1>0 : # a = input("请输入账号:") # b= len(a) # if b >=5 and b<=8 and a[0] in "qwertyuiopasdfghjklzxcvbnm": # while 1>0 : # c = input("请输入密码:") # if len(c) >=6 and len(c) <= 12: # print("注册成功!") # shuju.update(a=c) # ...
9ac4837de587d89821c80e76483b73c08bcbeedd
satyabalaram/Metis-Prework
/python/q5_datetime.py
638
3.859375
4
# Hint: use Google to find python function from datetime import datetime def num_days(d1, d2, format): start = datetime.strptime(d1, format) end = datetime.strptime(d2, format) return (end - start).days ####a) date_start = '01-02-2013' date_stop = '07-28-2015' format = '%m-%d-%Y' days = num_days(date_start...
20e2a705d0222128a6702020cbe44c7016a4ba56
t19960524/python-20160504
/ex3.py
362
3.5
4
scores = [60, 73, 81, 95, 34] n = 0 total = 0 nn=0 totalxx=0 totalxxx=0 for x in scores: n += 1 total += x nn=x**2 totalxx += nn avg = total / n nnn=0 for x in scores: n +=1 nnn=(avg-x)**2 totalxxx+=nnn print('total ' + str(total)) print('average ' + str(avg)) print('平方和 '+str(totalxx)...
8bbf2ddee81d3dd910c218048ef0c4431338b991
jd721rogers/bthoRegistration
/datascraping/test scripts/testing csvgrab.py
3,695
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed May 1 10:27:10 2019 @author: Jonathan Rogers """ import os import shutil import csv import sqlite3 # left, mid, and right functions def left(s, amount): return s[:amount] def right(s, amount): return s[-amount:] def mid(s, offset, amount): return s[offset:off...
100956ed06583420f56194bb70ec923a7b0249a7
Clement-Valot/ADSA-Among-us
/Step1 Tournament Organization/main.py
5,297
4.03125
4
from players import * from AVL_tree import * def RandomGames(list_players): random_game=1 AVL, root = CreateAVL(list_players) for i in range (3): #In order to avoid players to play against the same players during the 3 random games, #We chose to separate them thanks to the inorder, preorde...
8ec8a3513d023451792e0eabe23aaabbdb95a0b9
pmorande27/Recommended_Books
/Book.py
1,020
3.8125
4
class Book(object): def __init__(self, name, author, isbn): self.name = name self.author = author self.isbn = isbn def __eq__(self, obj): return isinstance(obj, Book) and obj.name == self.name def __hash__(self): return hash(( 'isbn',...
15b2305bb3c7f8daf0194a554f919b7e084fc883
Aiden-Wei/humanoid_walking_gait
/source/util/point.py
831
3.75
4
from util.geometry import distance_between_2_vertices_in_3d from util.float import is_float_equal class Point(tuple): """ 3D point """ @property def x(self): return self[0] @property def y(self): return self[1] @property def z(self): return self[2] d...
46537c8b000790a223b680d0683bbb96931c0069
Aiden-Wei/humanoid_walking_gait
/source/util/angle.py
758
4.0625
4
from math import degrees, radians def to_degrees(radians_list): converted = list(radians_list) for i, r in enumerate(radians_list): converted[i] = degrees(r) return tuple(converted) def to_radians(degree_list): converted = list(degree_list) for i, d in enumerate(degree_list): con...
95e7adc4004115d72f69cd78aa15fad72b9d7a6c
bwbobbr/AI
/EDA研究/分布式估计算法解决TSP.py
5,614
3.671875
4
import numpy as np import matplotlib.pyplot as plt ''' 参考网站 http://mwangblog.com/?p=1754 该算法主要的就是 训练概率矩阵p的值 ''' def distance(city): ''' 计算距离, 矩阵之间的距离公式 https://blog.csdn.net/frankzd/article/details/80251042 :param city: :return: ''' dists_matrix = np.zeros([len(city),len(city)]) dists...
90fb0d8ba2b00de86f70a202a49bde6ae6c20367
sdcwlfx/TensorflowProjects
/04_Tensorflow_简单案例.py
944
3.5625
4
import tensorflow as tf import numpy as np #使用numpy生成100个随机点 x_data=np.random.rand(100) #一条直线,斜率0.1,截距0.2 y_data=x_data*0.1+0.2 #构造一个线性模型,优化b、k使得接近于上面样本点分布,k、b初始为0.0 b=tf.Variable(0.) k=tf.Variable(0.) y=k*x_data+b #二次代价函数,y_data:真实值;y:预测值,目的是求使得误差平方均值最小的y loss=tf.reduce_mean(tf.square(y_data-y)) #定义一个梯度下降法来进行训练的优化器,...
bf52773bfe3db43ee1c93a38e8de394d9d9a8aad
sdcwlfx/TensorflowProjects
/06_MNIST数据集分类简单版本.py
2,431
3.515625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集,one_hot:将标签转换为只有一位为1,其它为0,会自动从网上下载数据集到当前目录 mnist=input_data.read_data_sets("MNIST_data",one_hot=True) #每个批次的大小 batch_size=100 #计算一共有多少个批次(整除) n_batch=mnist.train.num_examples//batch_size #该神经网络只输入层和输出层,输入层包含784个神经元,输出层包含10个神经元 ...
0d7c52fcaf20f9b872a06e742256c46c5b55a953
sonduong305/project-Euler
/p6.py
689
3.84375
4
""" The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Fi...
2611e754355af25eb27d004d33334f9c719fbb40
wplohrmann/projects
/code_jam2021/qualification_round/reversort_engineering.py
1,691
3.625
4
import numpy as np from itertools import permutations def reverse(l): for i in range(len(l)//2): l[i], l[-i-1] = l[-i-1], l[i] return l def reversort(integers): integers = integers.copy() n = len(integers) cost = 0 for i in range(n-1): j = i+np.argmin(integers[i:]) cost...
375d845bd8d74cc52a913e2fa0bb47bbab49196d
mosesxie/CS1114
/HW #4/hw4q2a.py
361
4.15625
4
userCharacter = input("Enter a character: ") if userCharacter.isupper(): print(userCharacter + " is a upper case letter.") elif userCharacter.islower(): print(userCharacter + " is a lower case letter.") elif userCharacter.isdigit(): print(userCharacter + " is a digit.") else: print(userCharacte...
44faabdf8570eb30550ac08996b636732010d7f0
mosesxie/CS1114
/lab1.3.py
154
3.78125
4
def main(): fah = int (input("Enter the temperature in Fahrenheit")) celsius = (fah -32) * (5/9) print("Celsius: " + str(celsius)) main()
85f51693068fb2bcfe98d54d4f453ff0b5682c7b
mosesxie/CS1114
/Lab #9/q1b.py
110
4
4
n = int(input("Enter a number: ")) lst = [] for i in range(1, n+1): lst.append(2**i) print(lst)
23248820b8ee97b4fcd96f7056564afd8b6f9ed6
mosesxie/CS1114
/HW #10/hw10.py
2,717
3.828125
4
import random def create_permutation(lst): x = len(lst) permutatedList = [] for i in range(x): element = lst.pop(random.randint(0,len(lst)-1)) permutatedList.append(element) return permutatedList def main_q1(): integer = int(input("Enter an integer: ")) ...
248e4edbb2baad9352cb27338bd1a5a5b70ffa6d
mosesxie/CS1114
/HW #9/hw9.py
2,059
3.71875
4
def max_abs_val(lst): absolutevaluelist = [] for element in lst: if element < 0: absolutevaluelist.append(element * -1) else: absolutevaluelist.append(element) maxValue = max(absolutevaluelist) return maxValue def main_q1(): ...
611c079e0a97c4564059461d068e1a75628a12a4
mosesxie/CS1114
/Lab #10/qw2.py
996
3.953125
4
import random def randomgen(): lst=['rock','paper','scissors'] index = random.randint(0,2) computer = lst[index] return computer def winner(user, computer): if user == "paper" and computer == "rock": return "user" elif user == "rock" and computer == "scissors": return "user...
8e6a7d8bb9e81eb252ab2c3e1e1b7f1e99780203
mosesxie/CS1114
/Lab #8/q2c.py
1,440
3.65625
4
def multifind(some_string, substring, start, end): flag = False counter = 1 match = 0 for index in range(0, len(some_string)): if some_string[index] == substring[0]: x = index for index2 in range(1,len(substring)): ...
0573712cf14f4e7fb92107ddee746a70dff5d9e2
mosesxie/CS1114
/Lab #4/q1.py
485
4.125
4
xCoordinate = int(input("Enter a non-zero number for the X-Coordinate: ")) yCoordinate = int(input("Enter a non-zero number for the Y-Coordinate: ")) if xCoordinate > 0 and yCoordinate > 0: print("The point is in the first quadrant") elif xCoordinate < 0 and yCoordinate > 0: print("The point is in the second...
cafa88711e47bec387e990dfd098abbfdb743ce2
mosesxie/CS1114
/lab1.2.py
363
3.96875
4
def main(): firstNumber = int(input("Enter first number")) secondNumber = int(input("Enter second number")) summation = firstNumber + secondNumber dif = firstNumber - secondNumber product = firstNumber * secondNumber print("Sum " + str(summation)) print("Difference " + str(dif)) ...
f67d092efbb3d6247dc78cec8c2325521eb41587
mosesxie/CS1114
/9:14bCSUY.py
253
4.09375
4
# This program read two numbers and prints their sum print("Please enter two numbers in two separate lines: ") number1 = input() number2 = input() print("The sum of " + str(number1) + " and " + str(number2) + " is " + str(int(number1) + int(number2)))
3f8cfad87dc8b275f78317996f95d1ad08480f30
jakegoodman01/MetaKnight
/metaknight/square.py
1,360
3.5625
4
class Square: files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] ranks = ['1', '2', '3', '4', '5', '6', '7', '8'] def __init__(self, coordinates: str): # A Square will have coordinates '00' if it out of bounds (does not exist in the chess board self.file = coordinates[0] self.rank = c...
a4dff9821c8eb740bef612f1a3774e45160c8479
parkALoha/CP3-Ratchata-Punyachonjaroen
/Exercise5_1_Ratchata_P.py
159
3.703125
4
a= int(input("a = ")) b= int(input("b = ")) print((a),"+",(b),"=",(a+b)) print((a),"-",(b),"=",(a-b)) print((a),"*",(b),"=",(a*b)) print((a),"/",(b),"=",(a/b))
9599127aae745ee9f0d7fecdec9de3879d79171c
anupprasad/CodingChallenge
/AddNumViaArray/NumberAdditionArray.py
667
3.53125
4
from numpy.distutils.system_info import numarray_info __author__ = 'Anup' numberList=[1,1,1,1] def addOne(n=1): reversedTempList=[] listLen=len(numberList) carry=0; isFirst=True for i in range(listLen-1,-1,-1): if isFirst: isFirst=False temp=numberList[i]+n+carry ...
953696fee7c305871d90c1293546d3e6e1a4b485
ThDePaula/Exercicios-Python
/ex066.py
274
3.703125
4
quant = soma = 0 print('Finalizar a execução digite [999]') while True: num = int(input('Informe um valor: ')) if num == 999: break quant += 1 soma += num print('='*25) print(f'Números informados: {quant} \nSoma dos valores: {soma}') print('='*25)
e6b4489ba7b6cf47050b1ee303cc69133b6854b3
ThDePaula/Exercicios-Python
/ex053.py
601
3.96875
4
print('='*25) print('A FRASE É UM PALÍNDROMO?') print('='*25) frase = str(input('Digite uma frase: ')).strip().upper() #Lendo sem espaços ínuteis e com tudo em caixa alta. palavras = frase.split() #Separando por frase. frase_junta = ''.join(palavras) #Juntando a frase em uma só palavra. inverso = '' for letra in...
553643f94e780fd87fd2e82e9f519998874a6223
ThDePaula/Exercicios-Python
/ex008.py
98
3.78125
4
m = float(input('Informe a distência em metros: ')) cm = m * 100 print('{:.2f}cm'.format(cm))
27ea14b3e6a1cb6fcc6c7a71e590831d1e10b5b5
ThDePaula/Exercicios-Python
/ex079.py
344
3.9375
4
listNum = list() while True: num = int(input('Informe um valor: ')) if num not in listNum: listNum.append(num) print('Valor adicionado com sucesso...') else: print('Valor duplicado!') resp = str(input('Deseja continuar? [S/n]: ')) if resp in 'Nn': break print(f'Valore...
145856a793d505b0a40ee70dc7d448c991e476e7
ThDePaula/Exercicios-Python
/ex005.py
156
4.09375
4
num = int(input('Digite um número: ')) ant = num - 1 suc = num + 1 print('Antecessor: {} \nNúmero digitado: {} \nSucessor: {}'.format(ant, num, suc))
2231961ff93fbf3be7a142dd873786cd83c48a19
ThDePaula/Exercicios-Python
/ex054.py
386
3.953125
4
from datetime import date maior = 0 menor = 0 for i in range(1, 8): ano = int(input('Ano que a {}ª pessoa nasceu: '.format(i))) idade = int(date.today().year) - ano if idade >= 21: maior += 1 else: menor += 1 print('Quantidade de pessoas na maioridade {}' '\nQuantidade d...
cef13c1e0260df436893f3b340227b43f315253d
ThDePaula/Exercicios-Python
/ex050.py
271
3.640625
4
soma = 0 pares = 0 impares = 0 for i in range(1, 7): num = int(input('Digite o {}º número: '.format(i))) if num % 2 == 0: soma += num pares += 1 print('Números pares informados: {} \nA soma dos números pares: {}'.format(pares, soma))
62ad371b7b3688e75533963c2917f25536a52c60
amarish-kumar/codechef-solutions
/bhopal.py
619
3.890625
4
def jump_a_wall (wallHeight, jumpHeight,offset): required_jumps = 0 while wallHeight > 0: wallHeight = wallHeight-jumpHeight required_jumps+=1 if(wallHeight>0): wallHeight+=offset return required_jumps def GetJumpCount(input1,input2,input3): required_jumps = 0 for wall in input3: required_jumps += ju...
79182a595e92be8e780ccd3dc8905df71fff7765
amarish-kumar/codechef-solutions
/VeryFirstSubmissionATMProblem.py
294
3.578125
4
''' ATM Problem on CodeChef URL ''' cashToWithDraw,cashInAccount = map(float,input().split()) balance = float(cashInAccount)-float(0.50) if(cashToWithDraw%5 == 0 and cashToWithDraw <= balance): balance = balance - cashToWithDraw else: balance = cashInAccount print(format(balance,'.2f'))
4c2e313b7f6fa742356b474e769b83347bab4092
matheusscheu/AED2
/Tabela/Tabela.py
866
3.5
4
class Tabela: def __init__(self,tam): self.tam_max def InsereTabela(self) def BuscaBinaria(self,lista,x): primeiro = 0 ultimo = len(lista)-1 while primeiro <= ultimo: meio = (primeiro + ultimo)//2 if lista[meio] == x: return meio ...
cc117ce0e7708cece036fd0c1d87dfa034dd0381
matheusscheu/AED2
/Pilha/pilhaEncadeada.py
1,450
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class Pilha: def __init__(self): self.top = None self._size = 0 def push(self, data): node = Node(data) node.next = self.top self.top = node self._size += 1 def pop(...
e08fb4acf8e365529c53aaa89d25f0613bc99595
matheusscheu/AED2
/Pilha/pilhaContiguidadeFisica.py
1,056
3.765625
4
class Nodo: def __init__(self): self.info = None class pilha: def __init__(self,maximo): self.elemento = [0]*maximo self.base = 0 self.limite = maximo self.topo = self.base -1 def empilha(self,valor): if self.topo < self.limite: self.topo += ...
4ccfbd3efece488bec435aa31b946e938dfe1021
jayrote/learning
/Data_Type/advance/advance_string.py
375
3.5625
4
# 1. a = 4 b = 4.5 c = a + b print(f" THE ANSWER OF SUM IS = {c}") # 2. x = 2*1.5 print(f" THE ANSWER OF MULTIPLY IS = {x}") # 3. y = 4 - 1.5 print(f" THE ANSWER OF MINUS IS = {y}") # 4. z = 10 / 2 print(f" THE ANSWER OF DIVISION IS = {z}") # 5. user_input = input("enter your name : ") if user_input == ...
940bf6a706d2f435ffc8d21ec01ad5078c42a8cb
DW01/ltp
/a1.py
4,423
4.34375
4
# Assignment 1 (a1.py). """This module is for the first major assignment of UofT's LTC course.""" # These first four functions operate on seconds to retrieve # various forms of time. def seconds_difference(time_1, time_2): """(number, number) -> number Return the number of seconds later that a time in second...
30cd0d3419d46c657d470b2d38b160f048854861
3amrA7med/Thompson-Construction-Algorithm
/utils/validator.py
7,096
3.9375
4
import string OR1 = "|" OR2 = "+" ASTERISK = "*" OPEN_BRACKET = "(" CLOSED_BRACKET = ")" ALPHABET = list(string.ascii_uppercase) def validate_and_parse(regular_expression): """ This function validates the input to be a regular expression and returns list of operations to be done on the graph :return: -...
6fc624ab8e47dd27db43b098054c04859557acfd
adugas28/CMPS-150---Intro-to-Computer-Science
/CMPS 150 Assignments/lab8.py
2,466
3.671875
4
# Author: Austin Dugas # ULID/Section: C00231110/003 # lab8.py #****************** LAB Average ****************** def LabAvg(): infile1 = open("lab8_labGrades.py","r") num = eval(input("How many lab grades are in the file? ")) print("Lab Grades: ", end='') sum = 0 for i i...
32fd0f13ba1b78cf5c0e6c09f25280626f4d3c7d
sirisha-8/Binary-Search-2
/min_sorted_rotated_array.py
799
3.703125
4
#Time Complexity : O(logn) #Space Complexity : O(1) #Did this code successfully run on Leetcode : yes #Any problem you faced while coding this : no class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ l =0 h = len(nums)-1 ...
90b95e8e1bfb117e47642e3240115b329c8c11bb
skarppi/icloud_photo_station
/icloudpd/paths.py
606
3.640625
4
"""Path functions""" import os def local_download_path(media, size, download_dir): """Returns the full download path, including size""" filename = filename_with_size(media, size) download_path = os.path.join(download_dir, filename) return download_path def filename_with_size(media, size): """Ret...
81efe838fdc5fb530f303b0546bdb4e43b86bd82
GustavoVianaN/criptografia-em-python
/tde vilmar.py
5,767
3.8125
4
#vou fazer em inglês com explicação para treinar # siga os passos, primeiro a opção 1 , depois 1 # escreva a mensagem e gere os códigos # depois receba a mensagem pela opção 2 com a alice # depois digite o K_sessão gerado por bob corretamente # depois o código %*#@& que é o primeiro nounce key gerado au...
29ffa2d1f514d46574bcc34f3fe459ff2006a5e6
siwenhongyi/To-do-management-system
/SQLite.py
695
3.921875
4
import sqlite3 #建一个数据库 def create_sql(): sql = sqlite3.connect("user_data.db") sql.execute("create table if not exists user("+ "id varchar(10) primary key,"+ "name varchar(128) not null,"+ "password varchar(128) not null);") sql.close() def event_sql(): sql = sqlite3.connect("user_data.db") sql...
1c4481a9b36187f882c5c7eb59317215a8161549
YUDHPK/Heart
/HeartDisease/problem1.py
3,627
3.765625
4
# Classification of heart disease by labeling the predicted values # in various classes, namely 0 for absence and 1 to 4 for presence and also try # to check the model performance by comparing it against other Classifiers from numpy import genfromtxt import numpy as np import matplotlib matplotlib.use('Agg') impor...
98612114f9f90aa761c9a75921703e0b96f78c5f
apaskulin/euler
/problems.py
1,989
4.15625
4
#!/user/bin/env python2 def problem_01(): # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. sum = 0 for i in range(1, 1000): if i % 3 == 0 or i % 5 == 0: ...
a19089f3ca7e55d583272d95f4bc0a97f9baf9f2
Farah-Amalia/LatihanGit
/day8.py
1,490
3.75
4
x={ 'nama' : 'antonio', 'umur' : 17, 'hobi' : 'memasak', 'makafa' : 'bakso goreng' } # for i,j in x.items(): # space=10-len(i) # print(i,space*' ',j) for i in range(len(x)): print(x[i]) # def lima(): # return 5 # a = lambda x : x * lima() # print(a(10)) # def add(n): # return n...
64d6469fcc388f24cacb5c730420197d679834d3
Farah-Amalia/LatihanGit
/day5.py
313
3.765625
4
# out='' # for i in range(3): # for j in range(3): # out += str(j)+' ' # out += '\n' # print(out) def pertambahan(x,y): total=x+y return total print(pertambahan(7,5)) def lima(): return 5 def kali(x): if(x<3): return 1 else: return(x*lima()) print(kali(5))
4a90f325bb7f0a5d096f41c05b20beede0c09fdf
q6/python-snippets
/windows_shutdown_countdown.py
1,301
3.8125
4
import subprocess import re # 315360000 max secs # max time is 10 years # ask the user how long from now they want to shutdown shutdown_countdown = input('''How long from now would you like to shutdown? Enter in the following format: ##h##m##s Examples of working entries: 12h30m00s 99s55h 31h2s 6m 10s (Enter nothing...
f3b17a13523ea98a94e9fefc1a34d38f785bd40b
rk012/ASCII-Encryption-Utility
/main.py
1,135
3.765625
4
from ascii_encryptor import encrypt, decrypt from symmetric_encryption_util import PUBLIC_KEY, key_gen SHARED_KEY = "" def setup(): global SHARED_KEY print("ASCII Encryption Utility\n") print("Send your public key to recipient:") print(PUBLIC_KEY) print("\nEnter recipient's public key:")...
11ed9cc5099698245d018f5a070ff85dd521135e
DevBaki/DataScienceWithPythonLibraries
/Numpy/Numpy2.py
3,160
4.6875
5
# Welcome to Numpy Examples # Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array. # # It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. # In NumPy dimensions are called axes. The number of axes is rank. # NumPy’s array cl...
6fd9f34ee976576be14c02a6e9aebbd12d504a30
jonathan-durbin/fractal-stuff
/gif.py
1,371
4.125
4
#! /usr/bin/env python3 # gif.py """Function to generate a gif from a numbered list of files in a directory.""" def generate_gif(directory: ("Folder name", "positional"), image_format: ('Image format', 'positional') = '.png', print_file_names=False): """Generate a gif from a numb...
cf24c7bc7a393c8468bd2e40ab8f1abaaec0e1ad
mvictora/ikabot
/ikabot/helpers/varios.py
855
3.5625
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import time from decimal import * getcontext().prec = 30 def addPuntos(num): return '{0:,}'.format(int(num)).replace(',','.') def diasHorasMinutos(segundosTotales): dias = int(segundosTotales / Decimal(86400)) segundosTotales -= dias * Decimal(86400) horas = int(s...
4517f0a310ca73525eca0d864230eb761162efe6
targeton/LeetCode-cn
/Solutions/1790.仅执行一次字符串交换能否使两个字符串相等.py
1,848
3.703125
4
# # @lc app=leetcode.cn id=1790 lang=python3 # # [1790] 仅执行一次字符串交换能否使两个字符串相等 # # https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal/description/ # # algorithms # Easy (66.53%) # Likes: 12 # Dislikes: 0 # Total Accepted: 11.8K # Total Submissions: 17.8K # Testcase Example: '"bank"\n"...
665b63f0df92d4452754fc5ddba20d92fa01e060
targeton/LeetCode-cn
/Solutions/965.单值二叉树.py
1,502
3.8125
4
# # @lc app=leetcode.cn id=965 lang=python3 # # [965] 单值二叉树 # # https://leetcode-cn.com/problems/univalued-binary-tree/description/ # # algorithms # Easy (67.24%) # Likes: 40 # Dislikes: 0 # Total Accepted: 13.1K # Total Submissions: 19.4K # Testcase Example: '[1,1,1,1,1,null,1]' # # 如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二...
66ae18bf92ad0c0b7ac80b8181d85bb3ba28e75b
targeton/LeetCode-cn
/Solutions/671.二叉树中第二小的节点.py
1,906
3.609375
4
# # @lc app=leetcode.cn id=671 lang=python3 # # [671] 二叉树中第二小的节点 # # https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/description/ # # algorithms # Easy (46.19%) # Likes: 183 # Dislikes: 0 # Total Accepted: 37.4K # Total Submissions: 78.7K # Testcase Example: '[2,2,5,null,null,5,7]' # # 给定一个...
773e18762ac843bea538e289ffed784641d0a406
MevlutArslan/neural-networks-from-scratch-book
/main/testing_concepts/activation_functions.py
3,116
3.875
4
import nnfs import numpy as np from nnfs.datasets import spiral_data nnfs.init() class Layer_Dense: # Layer initialization def __init__(self, n_inputs, n_neurons): # Initialize weights and biases self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_n...
3c4369e4d4daa90a61d5431dd16986a80e4fc7a2
hanbing6228/Boot-Camp
/Homework/03-Python/python-challenge/poll.py
2,660
3.796875
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv csvpath = os.path.join('Resources', 'election_data.csv') with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variab...
fec2527df5500e1d891e1d0121736cdacda794e6
PapelRasgado/Uri-1
/Uri/1042.py
197
3.75
4
ListSort1 = [] ListSort2 = [] values = int(input("Digite os valores:").split()) a, b, c = values toString(values) print (ListSort2).sort().split("/n") print("/n") print (ListSort1).split("/n")
f7706c5972c83d89a5b80b2a7102afcb3440f44c
PapelRasgado/Uri-1
/Uri/1012.py
322
3.671875
4
A,B,C = map(float,input().split()) pi = 3.14159 triangulo = (A*C)/2 circulo = pi*(C*C) trapezio = ((A+B)*C)/2 quadrado = B*B retangulo = A*B print ("TRIANGULO: %.3f" %triangulo) print ("CIRCULO: %.3f" %circulo) print ("TRAPEZIO: %.3f" %trapezio) print ("QUADRADO: %.3f" %quadrado) print ("RETANGULO: %.3f" %retangulo) ...
b7362544e275df118f4d35adbdf5cd910c43e7b0
Trelil/exercises
/exercises/objects_in_a_bag/objects_in_a_bag.py
2,189
3.71875
4
from random import shuffle COLORS = [ "transparent", "red", "green", "blue" ] class Item: def __init__( self, name, color, weight ): self.name = name self.color = color self.weight = weight return def getName( self ): return self.name def getColor( self ): return self.color def getWeight( sel...
c70b95e3624ca5dc9d1c88837281836b0bbe6a6f
yuanjunling/UnittestCaseDemo
/Study/function/c1.py
113
3.734375
4
#函数 # a = 1.12386 # result = round(a,3) # print(result) def print1(code): print(code) print1('python')
460703c194a0aac108a39c4759ba0761967002ea
yuanjunling/UnittestCaseDemo
/Study/function/c7.py
403
3.515625
4
#装饰器 import time def decorator(func): def wrapper(*args,**kwargs): print(time.time()) func(*args,**kwargs) return wrapper @decorator def f2(func_name,func_age): print("装饰器"+func_name+func_age) @decorator def f3(func_name,func_age,**kwargs): print("装饰器"+func_name+func_age) print(...
9dd6393101e3a4203add8151e494fcef1bf94436
nontage24/python_basic
/basic3_function.py
202
3.75
4
def addNum(a,b): return a+b def subNum(a,b): return a-b if __name__ == '__main__': a = input("Enter a = ") b = input("Enter b = ") val1 = addNum(int(a),int(b)) print(val1)
cfc67c51a40cbe96a7817f0108e1732a60b0c7bf
ferdyndongo/Text-Generator
/random_text.py
1,256
3.59375
4
#!/usr/bin/env python3 from nltk.util import bigrams import random text = input() words = [] ngrams = {} with open(text, 'r', encoding='utf-8') as corpus: for row in corpus: for word in row.split(): words.append(word) words_ngrams = list(bigrams(words)) for gram in words_ngrams: if gram[...
88a5df8a04c7ed79edef955995b95ede6c43907f
sybrandb/glz_new
/feestdag.py
1,151
3.546875
4
from datetime import datetime class FeestDag(object): """" for every festival specifies three attributes: the day, it's name, and it's color """ l_fieldnames = ['dag','benaming','kleur'] def __init__(self, datum, benaming, kleur='groen'): """ :type self: object """ self....
010fb9b9923482c36309301fc16ea978fb7cd52c
yunusemree55/PythonBTK
/lists/list-comprehension.py
653
4.1875
4
for x in range(10): print(x) numbers = [x for x in range(10)] print(numbers) for x in range(10): print(x**2) numbers = [x**2 for x in range(10)] print(numbers) numbers = [x*x for x in range(10) if x % 3 == 0] print(numbers) myString = "Hello" myList = [letter for letter in myString] print(myList) yea...
7a22e3e835fcfce56a2e701c932a762acb11cae6
yunusemree55/PythonBTK
/if-conditions/if-elif.py
133
3.734375
4
x = 10 y = 30 if x>y: print("x y'den büyük") elif y>x: print("y x'den büyük") else: print("x ve y birbirine eşit")
c982dd14121836aa11c9aa226a665c5b8cfc80ea
yunusemree55/PythonBTK
/otherss/iterators.py
325
4.21875
4
liste = [1,2,3,4,5] iterator = iter(liste) # try: # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) # except StopIteration: # print("Hata ! İndex dışına çıkıldı") print(next(iterator))
d792ca8387a6fef182577146da85e1994e689112
yunusemree55/PythonBTK
/lists/lists.py
343
3.5
4
my_list = [1,2,3] my_list = ["bir",2,True,5.3] # print(my_list) list1 = ["one","two","three"] list2 = ["four","five","six"] numbers = list1 + list2 # print(numbers) # print(len(numbers)) # print(numbers[2]) userA = ["Yunus Emre", 20] userB = ["Enes Emir", 18] users = [userA , userB] # print(users) # print(u...
52e37664e670fe6c7679963fe31cbbb9fddb91ac
btsween/view-matcher
/view_matcher.py
2,940
3.734375
4
""" File name: view_matcher.py Author: Bryan Sweeney The purpose of this project is to allow a user to find matching views from json for user input selectors When running, you will be asked to provide the selectors that you are looking to match. Use the rules below when providing input: For a class, simply enter the...
4b1ef402c1e55707252b8c04d2ea839b34444b32
Zzxxcony0/C109156240
/p13.py
127
3.640625
4
n = input("輸入一字元為:") n0 = str(n) n1 = n0[:] n2 = n0[::-1] if(n1 == n2): print("Yes") else: print("No")
42e7873b89a5b3f320e2003f20949210799a333d
scottwalsh/euler-python
/002.py
206
3.65625
4
last = 1 current = 1 total = 0 while current < 4000000: next = last + current if next % 2 == 0: total = total + next print(next) last = current current = next print(total)
357551b4fb01e35d963b9d0aa5af9580fd4c626e
jainamshroff/DumpYard
/HelloWorld/main.py
158
3.671875
4
# Simple Hello World Program def printhelloworld(): print("Hello World!",end="") print(", This Is My First Python Program.") printhelloworld()
64fece792c5a7af3fb7e8365a9d592f9958f09f8
aprilpaoyin/Lab-6
/SEM 1/Programming/lab 7.py
415
3.890625
4
__author__ = 'd14124009' def gcd(a, b): #finds gcd of 2 numbers if a < b: #swaps a and b so that a > b a, b = b, a while remainder != 0: remainder = a % b if remainder == 0: break str_a = input("Enter a number") a = int(str_a) str_b = input("Enter another nu...
f00458da83829358023a3b48f0568778528f2dfe
LucStrater/RusHourOnAutoPilot
/code/algorithms/depth_first.py
2,254
3.6875
4
class DepthFirst(): """ A depth first approach to solving a rush hour game. This algorithm goes depth first through the entire state space below a maximum number of moves by using a stack, checking each state for the solution. It is guaranteed to find the best solution if it exists within the maximum ...
c55be43b8a7349736cc61a42897cf3dd02ebc4a6
uribench/cryptography
/substitution_ciphers/src/ciphers/deranged_alphabet_cipher.py
469
3.96875
4
"""Substitution cipher using deranged alphabet""" from string import ascii_letters as letters import re import sys def make_cipher(salt): """Create a deranged alphabet cipher using a keyword as salt""" if not salt.isalpha(): print('salt must include only letters {}'.format(salt)) sys.exit(1) ...
b4c1cca40650675f36835cf98a739fb1baca3d20
PanXiebit/text-classification
/model/attention is all your need/Modules.py
10,163
3.515625
4
# the modules of model # position encoding import numpy as np import tensorflow as tf from tensorflow.contrib.layers.python.layers import xavier_initializer """ Embddding and softmax Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of...
86bae9bc7bab98c3d7d4b51daecf05b1cc8dae75
maruichen2004/EPI
/Binary Tree/FindKUnBalancedNode.py
760
3.65625
4
from Util.BinaryTree import TreeNode from Util.BinaryTree import BinaryTree class Solution: # Time: O(n) # Space: O(h) def findKUnBalancedNode(self, root, k): return self.findKUnBalancedNodeHelper(root, k)[0] def findKUnBalancedNodeHelper(self, root, k): if root is None: return (None, 0) ...
eb750eaf654bd348c19a0d07663e73d90f1a54b1
maruichen2004/EPI
/DFS/PowerSets.py
906
3.71875
4
class Solution: # Time: O(2^n) # Space: O(n) def powerSets(self, A): res = [] self.powerSetsHelper(res, [], sorted(A), 0) return res def powerSetsHelper(self, res, cur, A, i): if i == len(A): res.append(cur) if i < len(A): self.powerSetsHelper(res, cur, A, i+1) ...
6e8a49a7b615d68c0a196cd31cad217d3c5b0412
maruichen2004/EPI
/Array/PrimeSieve.py
492
3.703125
4
import math class Solution: # Time: O(nloglogn) # Space: O(n) def primeSieve(self, n): size = int(math.floor(0.5 * (n - 3))) + 1 primes = [2] is_prime = [True] * size for i in range(size): if is_prime[i]: p = (i << 1) + 3 primes.append(p) for...
058e6d649053b8a68e1fc45815b7caa7cddd934f
maruichen2004/EPI
/LinkedList/MergeSortedLists.py
797
4.03125
4
from Util.LinkedList import LinkedList from Util.LinkedList import ListNode class Solution: # Time: O(len(F) + len(L)) # Space: O(1) def mergeTwoSortedLists(self, F, L): dummy = ListNode(0) cur, l1, l2 = dummy, F, L while l1 and l2: if l1.val < l2.val: cur.next = l1 ...