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
21863bbc3798446c19b827b7b9c502fdacc7853c
pororodl/LeetCode
/LinkedList/FindNthFromEnd.py
779
3.640625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def findNthFromEnd(self, head: ListNode, n: int) -> int: if head == None or n <= 0: return None i = head j = head for _ in range(n - 1): if i.next!=None: ...
68148f617757ee783edf8eb9f5fba9f872837c81
pororodl/LeetCode
/TREE/preOrderTraversal.py
1,315
3.6875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preOrderTraversal(self,root): ''' 如果栈不空,输出根节点,并出栈并且输出 将右节点压入栈(如果存在) 将左节点压入栈(如果存在) :param root: :return: ''' res = []...
b740b4495f53643e176da4910c120867ec06fa42
pororodl/LeetCode
/34. Find First and Last Position of Element in Sorted Array.py
585
3.578125
4
def searchRange( nums, target: int): l = len(nums) i= 0 count = 0 while i < l: if nums[i]!=target: i += 1 continue elif nums[i]==target: indexp = i break if i==l: return [-1,-1] else: for j in range(indexp+1,l): ...
4dc9a9a838e8fc569111d763353c0aec80056e64
pororodl/LeetCode
/1282. Group the People Given the Group Size They Belong To.py
855
3.59375
4
from typing import List class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: gLen = len(groupSizes) d = {} for i in range(gLen): if groupSizes[i] not in d: d[groupSizes[i]]=[i] # elif groupSizes[i] in d and isFull[i]==T...
fb72542bc2b49c5b500fda386b8651fd8fb49264
arandomsapien/project-euler
/python3/003.py
501
3.953125
4
import math def prime_factors(n): """ return a list prime factors for n """ prime_factors = [] while n % 2 == 0: prime_factors.append(2) n = n / 2 # int(math.sqrt(n))+1 is the max to test for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: ...
76df2546933b3cc6fee1f1a200fc038dd2023f72
AntB95/ML
/Project 1/Projet pote ikram /scripts/implementations.py
16,145
3.890625
4
from scripts.proj1_helpers import * import matplotlib.pyplot as plt def least_squares_GD(y, tx, initial_w, max_iters, gamma): """ :param y: the output of the data :param tx: the input of the data :param initial_w: the initial weight form which we wish to proceed the least squares GD algorithm :pa...
46ceb27aa11e08436fadf783e6a94b9e3dd28ced
Arshitha/HackerRank-30-days-of-Python
/Day28_regex_patterns.py
858
3.546875
4
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict if __name__ == '__main__': N = int(input()) userDict = defaultdict(lambda: ' ') gmailIDs = [] for N_itr in range(N): firstNameEmailID = input().split() # print(firstNameE...
9e709c185281b1954d20aaf1ef9d80a01a243c84
LeijonaNL/J1F1_3_werken_met_condities
/Sollicitatie.py
7,103
3.703125
4
# sollicitatie.py # Gender gender = input('Wat is uw geslacht? ').lower() print('U heeft ' + str(gender) + ' geantwoord.') # Vraag 1 ervaringA = 0 ervaringB = 0 ervaringC = 0 repeat = True while repeat: repeat = False ervaring = input('''Heeft U enkele jaren ervaring met: dierendressuur, jongleren of...
67cf549f5e3ad4935427432d9561de90a1b5e0c7
lauram15a/Fundamentos_de_programacion
/CUADERNOS DE TRABAJO/CUADERNO 5/ej 6 cuaderno 5 cuadrado.py
2,923
4.1875
4
#Laura Mambrilla Moreno #Ej 6 cuaderno 5 """ Implementa una estructura “Cuadrado” que incluya información sobre sus 4 vértices y sobre su punto central, todos los cuales seran del tipo Punto2D. """ #librerías import math #funciones class Punto2D : def __init__ (self, x, y): self.x = x self.y = y ...
df20edb33087526def5c3a292416009ab08a6a4d
lauram15a/Fundamentos_de_programacion
/Útil/matrix.py
619
3.578125
4
#Funciones def crea_matrix(rows, cols): matrix = [0] * rows for i in range(rows): matrix[i] = [0] * cols return matrix def crea_matrix2(rows, cols): matrix = [] for i in range(rows): matrix.append([]) for j in range(cols): matrix[i].append(0) return matrix d...
6bdba93386d8b4f5b4d6662a0f6d774ea195792f
lauram15a/Fundamentos_de_programacion
/CUADERNOS DE TRABAJO/CUADERNO 3/ej 16 cuaderno 3 serie armónica.py
1,837
4.125
4
#LAURA MAMBRILLA MORENO #EJ 16 CUADERNO 3 """ . Escribe un programa que pida un número límite y calcule cuántos términos de la serie armónica son necesarios para que su suma supere dicho límite. Es decir, dado un límite introducido por el usuario (por ejemplo 50) se trata de determinar el menor número n tal que: 1 + 1...
4580997492079b7ebf2ea1fff76ed3ca5397385a
lauram15a/Fundamentos_de_programacion
/Laboratorio/Práctica 3/Ejercicios de clase/Ejercicio_2.py
497
3.921875
4
#Librerías import sys #Funciones def producto(n1, n2): ''' int, int -> int OBJ: Calcula producto sin utilizar *''' prod = 0 for i in range(n2): prod = prod + n1 return prod #Programa principal try: n1 = int(input("Introduce el primer número: ")) n2 = int(input("Introduce el segundo...
90671fd62e3a9a27ddaeccc5cc73c24935e297b7
lauram15a/Fundamentos_de_programacion
/Laboratorio/Práctica 5/registros_recordclass.py
846
3.65625
4
#Registros (mediante recordclass) #Librerias from recordclass import recordclass as Record import copy #Tipos tPoint = Record('tPoint', 'x y') tTriangle = Record('tTriangle', 'point1 point2 point3') #Funciones def copyTriangle(t): p1 = tPoint(t.point1.x, t.point1.y) p2 = tPoint(t.point2.x, t.point2.y) ...
fc819bc1fd471c362999ea00a80e78c87c84973b
lauram15a/Fundamentos_de_programacion
/CUADERNOS DE TRABAJO/CUADERNO 2/ej 13 cuaderno 2 distancia puntos.py
818
4.28125
4
#Ejercicio 13 - Cuaderno 2 #Escribe una función que a partir de las coordenadas 3D de dos puntos en el espacio en formato (x, y, z) calcule la distancia que hay entre dichos puntos.Prueba su función y el resultado por pantalla. import math def distancia (xA, yA, zA, xB, yB, zB): """ float, float, float --...
ea143a37157201f8e852b11d62fcd1fe7b0be58c
lauram15a/Fundamentos_de_programacion
/Laboratorio/Práctica 6/busqueda_binaria.py
543
3.5625
4
#Funciones def busquedaBinaria(lista, item): if len(lista) == 0: return False else: puntoMedio = len(lista)//2 if lista[puntoMedio]==item: return True else: if item<lista[puntoMedio]: return busquedaBinaria(lista[:puntoMedio],item) ...
c24a84a719d4c820a0caa50f158e279be5c246e1
lauram15a/Fundamentos_de_programacion
/Laboratorio/Práctica 1/Solución ejercicios 5, 6, 7/Ejercicio_6.py
683
3.859375
4
''' Cuaderno de trabajo 1.pdf - Ejercicio 6: Descripción: Contabilidad de camiones ''' #Programa principal distancia = float(input('Introduzca la distancia recorrida (km): ')) litros = float(input('Introduzca la cantidad de combustible usada (l): ')) precio = float(input('Introduzca el precio del combustible (€/l): '...
77eb5d2baa36b9b114940e8e7b9b8ae86ea36e60
lauram15a/Fundamentos_de_programacion
/CUADERNOS DE TRABAJO/CUADERNO 5/ej 5 cuaderno 5 distancia.py
859
4.21875
4
#Laura Mambrilla Moreno #Ej 5 cuaderno 5 """ Programa una función distancia_2D que calcule la distancia entre dos puntos. La función retornará un número real según la siguiente fórmula: d=((x2 - x1)**2 + (y2 + y1)**2)**(1/2) """ #librerías import math #funciones class Punto2D : def __init__ (self, x, y): ...
6e20e66735834d1dd5b8f94ecc6f091ee171374d
lauram15a/Fundamentos_de_programacion
/CUADERNOS DE TRABAJO/CUADERNO 3/ej 10 cuaderno 3 del 1 al 12 meses.py
1,803
4.3125
4
#LAURA MAMBRILLA MORENO #EJ 10 CUADERNO 3 """" Codifica un subprograma que reciba un número entero, y si es entre 1 y 12 escriba un mensaje por pantalla indicando el mes a que dicho número corresponde. En caso contrario deberá mostrar un mensaje de error. Valida las entradas utilizando la función del ejercicio 9. """ ...
760c9dafebc7d1fad762015a4d8470e6e89794bd
lauram15a/Fundamentos_de_programacion
/Laboratorio/Práctica 2/Ejercicios de clase/1. funciones.py
585
3.9375
4
#Ejercicio 4 #Librerias import math #Funciones def area_circulo(radio): """ float --> float OBJ: Calcula el area de un circulo PRE: radio >= 0 """ area = math.pi * radio**2 return area def perimetro_circunferencia(radio): """ float --> float OBJ: Calcula el perimetro de una circulferencia...
e3839a0fa8c93f604fe053afaebbcb42db473289
JCULukeM/CP1404-LUKE_PRAC
/Prac_05/colourHex.py
381
4.0625
4
COLOUR_NAMES = {"aliceBlue": "fof8ff", "AntiqueWhite": "fa4bd7", "aquamarine1": "7ffd4", "black": "000000", "chartreuse1": "7fff00", "red": "ff6663", "blue": "ff6ooo"} def main(): colour = input("Choose a colour: ") while colour != "": print("{} is {}".format(colour, COLOUR_NAMES.get(...
f076dc23e144a5cca940d1d097c907bd5b081d3f
JCULukeM/CP1404-LUKE_PRAC
/Prac_04/Quick pick lotter.py
620
3.8125
4
from random import randint def num_generator(lottery_list, number_quick_picks): num = 90 line_len = 6 for i in range(0, number_quick_picks): while line_len > 0: num = randint(1, 45) if num not in lottery_list: lottery_list.append(num) line_le...
802b4224ecbdb32db642f8478562efe3ff2cd9f9
adynmiles/AllergyScanner
/BarcodeRecognition.py
2,825
3.625
4
from pyzbar import pyzbar import argparse import cv2 import image_get # pyzbar is able to recognize barcodes based on the alphanumeric data contained within them # given by the "width" of the black bars making up the barcode. # construct the argument parser and parse the arguments #ap = argparse.ArgumentPars...
12a6f048c0d473b866433d799473c8266935b79a
arueth/python-sandbox
/code/pretty_multi_table.py
1,013
4.0625
4
import os import sys terminal_size = os.get_terminal_size() x = None try: if len(sys.argv) < 2: x = int(input("Input x: ")) else: x = int(sys.argv[1]) except ValueError: print("ERROR: x must be an integer") exit(-1) y = None try: if len(sys.argv) < 3: y = int(input("Input y: ")) else: y ...
89c4436e1ef02eb72a6616b0ea7f1cd2b3c1d9d9
BrooksPatton/grokking_deep_learning
/chapter_4.py
373
3.703125
4
def neural_network(input, weight): return input * weight input = 0.5 weight = 0.2 expected_prediction = 1.5 alpha = 0.01 while True: prediction = neural_network(input, weight) error = (prediction - expected_prediction) ** 2 error_delta = (prediction - expected_prediction) * input weight = weight ...
89375e7d7b95d451996d92870e4b4337c3420450
mtjhartley/data_structures
/pre_vertafore/old_python/circleQueue.py
1,059
3.75
4
class CircleQueue: def __init__(self, capacity): self.queue = [None] * capacity self.capacity = capacity self.front = 0 self.rear = 0 self.isEmpty = True def printQueue(self): print self.queue def enqueue(self, value): if self.rear == self.front and not self.isEmpty: return False self.queue[self....
ddd140fff48bea6af7ba893bfb4b64c5e4bff904
mtjhartley/data_structures
/pre_vertafore/old_python/reverse_list.py
297
4.125
4
test1 = [3,1,6,4,2] test2 = [3,1,6,4] def reverse_list(arr): end = len(arr) - 1 for idx in range(len(arr)/2): temp = arr[idx] arr[idx] = arr[end-idx] arr[end-idx] = temp #print arr return arr print reverse_list(test1) print reverse_list(test2)
b15686c1fe39255b57b6f04af781e942eacb6deb
saurabh3434/datastructures-and-algorithms
/data_structure/array/array_rotation/program_for_array_rotation.py
1,403
3.828125
4
""" Given an unsorted array arr[] of size N, rotate it by D elements (clockwise). Input: The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotati...
59ad9578fb63d6a1a372ecbc9d493954a11c7bdb
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/10. Strings indexing/Буква «Z».py
162
3.90625
4
word = input('Слово:-') num = int(input('Номер буквы? :')) if 0 < num <= len(word): print(word[num - 1]) else: print('ОШИБКА')
f3625c50e6d75dd430c0c2133d1903f4764292d7
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/6. For loop/Число-исключение.py
367
3.828125
4
# Программа перемножает 7 введённых чисел # Кроме числа-исключения i = 1 num_all = 1 num_exc = int(input('Введите число-исключение:')) for i in range(1, 7): num = int(input('Введите число:')) if num != num_exc: num_all *= num i += 1 print(num_all)
36c77b0781336698e327fd0f0b7f343e71352cf8
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/6. For loop/Пирамида.py
290
3.640625
4
height = int(input()) i = 1 a = "M" x = " " count = 0 width = height - 1 for i in range(1, height + 1): print(x * width, end='') if i == 1: print(a * i, end='\n') else: count += 1 print(a * (i + count), end='\n') i += 1 width -= 1
337e10378b53e04903cc5a4f9be69bc106c58870
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/11. Strings Slices/Вредные советы.py
445
3.953125
4
# Вводится кол-во советов и сами советы # Программа выводит вредные советы,удаляя частицу "не" в строчках,при этом сохраняя её как приставку n = int(input()) for i in range(n): s = input() if (1053 == ord(s[0]) or 1085 == ord(s[0])) and 1077 == ord(s[1]) and ' ' == s[2]: s = s[3:] print(s.cap...
cccbcdd1e757dce9d393e230122c5907daf7c25c
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/1. The beginning/RUS/Правильное знакомство.py
344
3.703125
4
print('Привет, пользователь') name = input('Как тебя зовут?') print('Приятно познакомиться,', name) years = input('Cколько тебе лет?') print('Ух ты, мне тоже', years) city = input('А в каком городе ты живешь?') print('Люблю этот город -', сity)
733e66bb7de5899708f16264ea9297378ed2b1ac
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/1. The beginning/ENG/Correct acquaitance.py
250
3.890625
4
print('Hello, user') name = input('What is your name?') print('Nice to meet you,', name) years = input('How old are you?') print('Wow, I am', years, 'years old too') city = input('What city do you live in?') print('I love this city -', сity)
f524c0816e1bc316e23d293738d7b7b55ca30fe9
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/11. Strings Slices/Фильтр.py
851
4
4
# Программа показывает работу какого-то сайта, фильтруещего сообщения по таким методам: # Если строка начинается с символов «%%»,то их выводить не следует # Если строка начинается с сочетания символов «####», то её нужно вообще пропустить. # Ecли строка начинается с симвала «@»,заменить этот символ на "mail.ru." ...
6d001e3b19bc88a744b7288a618b721c2adb91a3
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/2. Сonditional operator/RUS/IQ тест.py
1,521
4.0625
4
a = input('Где Вы живете?') if a == 'Казань' or a == 'Москва' or a == 'Дома': b = input('Кто может поднять и передвинуть и коня, и слона?') if b == 'Силач' or b == 'Никто' or b == 'Шахматист': c = input('Что вчера было «завтра», а завтра будет «вчера»?') if c == 'Не знаю' or c == 'Сегодня' ...
311fba0777ef7a120c51436743d9ceb3e0fd3470
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/4. While-loop/Скидки!.py
550
4.125
4
# Программ считает сумму товаров и делает скидку 5 % на товар,если его стоимость превышает 1000 price = float(input('Введите цену на товар:')) cost = 0 while price >= 0: if price > 1000: cost = cost + (price - 0.05 * price) else: cost = cost + price price = float(input('Введите цену ...
e03defcacb005f5daa03cdf0540ca7411880b98b
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/5. Debugger/Псведоним с ботом - 3 кучки.py
4,197
3.828125
4
import random # По игре Псевдоним c ботом, однако с 3 кучками # Бот выбирает любую из кучек и берет рандомное количество камней из кучки # Вы также можете брать любое корректное количество камней bunch_1 = int(input('Введите изначальное количество камней в 1 кучке:')) bunch_2 = int(input('Введите изначальное колич...
0c8643ec77ec3a9702da7e8202650f7b70c2f486
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/9. Sets/Книги на лето.py
984
4.125
4
# Представьте, что Вам задали читать книги на лето # К счастью, у Вас на компьютере есть текстовый документ, в котором записаны # все книги из его домашней библиотеки в случайном порядке. # Программа определяет, какие книги из списка на лето у Вас есть, а каких нет. M = int(input('Введите кол-во книг на Вашем ком...
77c2bb8c256fdac2fb10db6de77fad174d70116b
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/4. While-loop/Вспомнить все If.py
214
3.65625
4
t = float(input('Введите температуру воздуха сегодня:')) if t > 28: print('ЖАРКО') elif t < 15.5: print('ХОЛОДНО') else: print('НОРМАЛЬНО')
73431a70c0bb3abeb2b68ebbba446f9fdbf3fec4
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/11. Strings Slices/Буквоедство.py
107
3.546875
4
line = input() print(line) line = line[1:-1] while line != '': print(line) line = line[1:-1]
a23213dc2bbb3a554b1cc9d1e13d5be851f966b6
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/8. Nested Loops/А про деление забыли! — 2.py
303
3.78125
4
# Отличие в том, что в данном случае вопроизводится деление на 1 в том числе n_colonna = int(input()) n_line = int(input()) for i in range(1, n_line + 1): for j in range(1, n_colonna + 1): print(j / i, end=' ') print("")
c19f01337bf12fea45fd094be225f74ef3625d28
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/10. Strings indexing/Игра в города — Альфа.py
612
4.28125
4
# Игра в города в один раунд: # Участники вводят поочередно 2 города(1 раз), # так чтобы каждая начальная буква города начиналась с конечной буквы прошлого города, # если второй участник ошибётся - он проиграет # # Города писать в нижнем регистре word_1 = input() word_2 = input() if word_1[len(word_1) - 1] =...
dc7544efbe5ca947c106715a8ddf174048ecdf2c
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/6. For loop/Магические ступеньки.py
146
3.796875
4
height = int(input()) i = 1 a = "_" x = " " for i in range(1, height + 1): print(x * i, end='') print(a * i, end='\n') i += 1
ed13974f9b3fc6725f060c08dc5d2dbd5dde36db
ArseniyCool/Python-YandexLyceum2019-2021
/Основы программирования Python/5. Debugger/Ним-пасьянс - 3 Кучки.py
1,215
3.90625
4
# По игре Ним-пасьянс, однако с 3-мя кучками # Гарантируется, что суммарное количество взятых им камней равно общему количеству камней в куче. stack_1 = int(input('Введите изначальное количество камней в 1 кучке:')) stack_2 = int(input('Введите изначальное количество камней в 2 кучке:')) stack_3 = int(input('Введит...
64dfee4144bf89138df1d56a50a0dd4c06ec2045
SitiNurjanah21/labpy03
/latihan1.py
312
3.5
4
print('|-----------------------------------------------|') print('|LATIHAN 1|') print('|-----------------------------------------------|') print('') import random n = int(input("Masukan nilai N : ")) for i in range(n) : a=random.uniform(0.0,0.5) print ("Data ke : ", i, "=> ", a) print("Selesai")
fc89779a2cf480512ac48b7a21c5d344a30e56d6
Seanie96/ProjectEuler
/python/src/Problem_4.py
1,154
4.34375
4
""" solution to problem 4 """ NUM = 998001.0 def main(): """ main function """ starting_num = NUM while starting_num > 0.0: num = int(starting_num) if palindrome(num): print "palindrome: " + str(num) if two_factors(num): print "largest number: " + str...
9b337072f070888f09d2cbf1d0b5df00c02c478c
D-moe/googlesample
/hello.py
135
3.875
4
print('Hello, this is Python') print('2+ 2 is %d' %(2+2)) def my_function(): '''This will do something not great.''' return 0
5990d326ddb1fded3dda0151f128d3a25e1a69f8
ShiKaiWi/leetcode
/9.py
606
3.640625
4
import math class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False if x == 0: return True l = int(math.floor(math.log10(x))) end = int(math.pow(10, l)) start = 10 ...
06793fc5a6ec3e09be660032582ebf961ce59173
windelbouwman/chronos
/chronos/gui/transform.py
1,993
3.640625
4
import abc import math from ..data import TimeStamp class Transform(metaclass=abc.ABCMeta): def forward(self, value): pass @abc.abstractmethod def backward(self, value): pass def inverse(self, value): return self.backward(value) class TimeTransform(Transform): """ Tran...
bbec983bbf801e65589c444f3814e629b57d249a
windelbouwman/chronos
/chronos/data/timespan.py
697
3.671875
4
from .timestamp import TimeStamp class TimeSpan: """ A timespan is a period of time with fixed start and end dates. """ def __init__(self, begin, end): if not isinstance(begin, TimeStamp): raise ValueError("begin must be TimeStamp") if not isinstance(end, TimeStamp): ...
299f1e19457f2db6c79d7e9859ebd970bb06cf02
dtoakley/rpg
/parse.py
1,756
3.625
4
from verb import * class Parser(object): def __init__(self, player, location): self.player = player self.location = location self.pickup = ["take", "pickup", "get", "grab"] self.lookat = ["lookat", "look", "show", "see", "check"] self.use = ["use", "wield", "hold", "throw"...
f3ffe294d61f07443149d9623cf8b6d78041ef36
tanvi1706/kattis-programming-tutor
/anotherCandy.py
299
3.65625
4
n = int(input()) for test in range(0, n): input() candies = 0 children = (int(input())) for t in range(0, children): candy = int(input()) candies += candy remainder = candies % children if remainder == 0: print('YES') else: print('NO')
ceb1c8d1bace6d2592df64b1ca9f1b7582efb1de
EoinGr3y/codeAbbey
/selectionSort/selectionSort.py
1,738
3.796875
4
numbers = [109, 106, 8, 113, 159, 141, 42, 173, 7, 14, 192, 156, 50, 88, 182, 28, 74, 69, 35, 167, 123, 16, 70, 171, 36, 194, 90, 37, 199, 142, 175, 112, 101, 116, 153, 75, 138, 4, 98, 165, 78, 1, 45, 91, 17, 115, 62, 23, 150, 56, 187, 24, 111, 129, 198, 31, 176, 105, 39, 136, 193, 155, 52, 131, 96, 117, 97, 82, 9, 196...
69690866e9118af508c157e6ef419e547fe686d5
Niira/Coursera-Programming-in-Python
/1 - Diving in Python/Week 3/Tasks/1 - File reading class/Solution/solution.py
349
3.78125
4
import os class FileReader: def __init__(self, path): self._path = path def read(self): if not os.path.exists(self._path): return "" else: with open(self._path, 'r') as f: text = f.read() return text #reader = FileReader("input...
d72abfc23884a4bf1d889ded11c86ea177911137
mauriciotoro/ST0245-Eafit
/laboratorios/lab02/spoiler/python/Lab2_Codigo.py
2,237
3.9375
4
import random import sys import time sys.setrecursionlimit(1000000) myFile = open('Tables.csv','w') def insertionSort(x): """ It orders the array x :param x: array with numbers :returns: nothing """ for i in range(len(x)): j = i while j > 0 and x[j-1]>x[j]: temp = x[j] x[j] = x[j-1] x[j-1] = temp ...
1cf73ab939951fe57eb7b397da9a0f103ea445f5
mauriciotoro/ST0245-Eafit
/codigos-de-clase/2021-2/LISTAS/nodo.py
1,013
3.921875
4
class Nodo: def __init__(self,d): self.__dato__ = d self.__siguiente__ = None class Lista: def __init_(self): self.__primero__ = None def __buscar__(self,nodo,numero): if nodo == None: return False if nodo.__dato__ == numero: return True ...
2bc0b077977319506c3714130f6cfeabbe9ef9c9
mauriciotoro/ST0245-Eafit
/codigos-de-clase/2021-2/RECURSION/contarX.py
543
3.65625
4
def calcularX2(caracteres, i): if(i == len(caracteres)): return 0; if(caracteres[i] == "x"): return 1 + calcularX2(caracteres, i+1) return 0 + calcularX2(caracteres, i+1) def calcularX(caracteres, i, acum): if(i == len(caracteres)): ...
637041fa2afda1d6429bdc67d923297ea2e9a503
NathyPapst/Projetos-em-Python
/Jogo-da-Velha.py
2,882
3.890625
4
def initialize(Mat): for i in range(3): linha=[""]*3 Mat.append(linha) return Mat def printMat(Mat): print("\t0 1 2\n") for j in range(3): print(j,"",end='') for k in range(3): if Mat[j][k]=="": print(" |_|",end=' ') elif Mat[j][k]==1: print(" |X|",end=' ...
4dcbb390b44384b92bc3dc79800e2766f73cd5a2
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex078.py
669
3.6875
4
lista = list() maior = menor = 0 for n in range(0, 5): lista.append(int(input(f'Digite um valor na posição {n}: '))) if n == 0: maior = menor = lista[n] else: if lista[n] > maior: maior = lista[n] if lista[n] < menor: menor = lista[n] print('='*40) print(f'Voc...
0b98e5d70468bda1a80d41c6a917b937c9981395
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex091.py
563
3.53125
4
from random import randint from time import sleep from operator import itemgetter jogos = {'Jogador 1': randint(1, 6), 'Jogador 2': randint(1, 6), 'Jogador 3': randint(1, 6), 'Jogador 4': randint(1, 6)} ranking = [] print('-' * 30) print(f'{"Valores sorteados:":^30}') print('-' * 30) for k, v...
bc63fdbbb8606fa108ef0a1dd6bcdffa7db3c560
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex103.py
304
3.75
4
def ficha(nome='<desconhecido>', gols=0): return print(f'O jogador {nome} fez {gols} gols no campeonato') n = str(input('Nome do Jogador: ')).strip().title() g = str(input('Quantidade de gols: ')) if g.isnumeric(): g = int(g) else: g = 0 if n == '': ficha(gols=g) else: ficha(n, g)
0ca17f940ca9b59f2614a69fb09314465df10fe0
eltonrp/curso_python3_curso_em_video
/01_fundamentos_Python/ex028.py
415
3.78125
4
from random import randint from time import sleep num = randint(0, 5) print('-=-' * 20) print('Estou pensando em um número de 0 a 5, tente adivinhar: ') print('-=-' * 20) adv = int(input('Em que número eu pensei? ')) print('PROCESSANDO...') sleep(3) if num == adv: print('Eu pensei no número: {}. Parabéns, você acer...
01d062aba04548b8e7d89f1e21d56071c4b5485a
eltonrp/curso_python3_curso_em_video
/01_fundamentos_Python/ex007.py
144
3.828125
4
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) print('A média do aluno é: {}!'.format((n1+n2)/2))
7a29cf36b42c9528f77880ff1da776adbcb56612
eltonrp/curso_python3_curso_em_video
/02_estruturas_de_controle/ex054.py
366
3.96875
4
from datetime import date atual = date.today().year maioridade = atual - 21 maior = 0 menor = 0 for c in range(1, 8): ano = int(input('Digite o {}° ano de nascimento: '.format(c))) if ano <= maioridade: maior += 1 else: menor += 1 print('Foram encontrados {} maiores de idade'.format(maior)) ...
7ce8810e4167d633ecd2724e4c1cdb7534e17a0b
eltonrp/curso_python3_curso_em_video
/01_fundamentos_Python/ex020.py
289
3.828125
4
from random import shuffle n1 = input('Primeiro nome: ') n2 = input('Segundo nome: ') n3 = input('Terceiro nome: ') n4 = input('Quarto nome: ') nomes = [n1, n2, n3, n4] print('Ordem fornecida:\n{}'.format(nomes)) shuffle(nomes) print('Ordem sorteada de apresentação:\n{}'.format(nomes))
a1f2816bd8837a690c2577194514ef8d3d935a23
eltonrp/curso_python3_curso_em_video
/01_fundamentos_Python/ex003.py
279
4.0625
4
nome = input('Qual é o seu nome? ').capitalize() idade = input('Qual é a sua idade? ') local = input('Onde vc nasceu? ').capitalize() print('Ok, vc é de(a) {}, tem {} anos e seu nome é {}.' ' Seja Bem vindo, {}!'.format(local, idade, nome, nome)) print(nome.isalpha())
f3ed081fb1ea1eae641d1ce92952e2a93c085f4e
eltonrp/curso_python3_curso_em_video
/03_estruturas_compostas/ex102.py
511
3.84375
4
def fatorial(n, show=False): """ -> Calcula o fatorial de um número. :param n: número a ser calculado. :param show: (opcional) Mostra ou não a conta. :return: Valor do fatorial de n """ f = 1 for c in range(n, 0, -1): if show: if c > 1: print(f'{c} x '...
e9cb8dc96f57fe38d8b34d504b77f1e933611b96
csrudrap/random-coding
/InterviewPrep/NonRepeatingChar.py
578
3.890625
4
# Given a string, return a non-repeating character. def non_repeating(given_string): d = {} for ch in given_string: if ch not in d.keys(): d[ch] = 1 else: d[ch] += 1 for i in d.keys(): if d[i] == 1: return i return None # NOTE: The following i...
95eb8f40f40eed4eebfa1e13dcb0117b80cb6832
mamare-matc/Intro_to_pyhton2021
/week3_strings.py
1,347
4.5
4
#!/usr/bin/python3 #week 3 srting formating assignment varRed = "Red" varGreen = "Green" varBlue = "Blue" varName = "Timmy" varLoot = 10.4516295 # 1 print a formatted version of varName print(f"'Hello {varName}") # 2 print multiple strings connecting with hyphon print(f"'{varRed}-{varGreen}-{varBlue}'") # 3 print...
89862390adaa963296049085ce05566d16a1410b
mamare-matc/Intro_to_pyhton2021
/midterm-if.py
694
3.796875
4
#!/usr/bin/env python3 print(f'Name: Mahlet Amare') Total = 0 linenumber = 0 #3.1 Read file and create Total variable and loop to extract the line number of the string add the number lines in Total with open("Midterm-if.txt","r") as hFile: for line in hFile: linenumber += 1 if "gmeach18@ed.gov" in...
9ad10c9a944aae48461f9da8b9b141f290206a68
mamare-matc/Intro_to_pyhton2021
/week9tempconversion.py
563
3.875
4
#!/usr/bin/env python3 from c2f import celsius_to_fahrenheit from f2c import fahrenheit_to_celsius #Ask the user to enter the temprature and measure source_temp = float(input("Enter the temprature: ")) measure = input("select (F) for fahrenheit or (C) for celsius: " ) #Evaluate user inut and call the functions from ...
4facc64848ef3a9e5e9325131639c3161aa3ed02
shivajivarma/codebase
/PYTHON/canItFormPalindrome.py
319
3.953125
4
''' Can one of the permutation of given string, forms a palindrome or not? Eg: ssm It can be resolved to sms, which is a palindrome. ''' def canItFormPalindrome(str): odd = 0 while(len(str)>0): if(str.count(str[0])%2==1): odd = odd + 1 if(odd > 1): return False str = str.replace(str[0],"") return True
4064d2ce11da3aabb9756b618cec87ef60f5a855
srinivasdasu24/Programming
/Python_certified/find_a_word.py
995
3.609375
4
''' Level of difficulty Medium Objectives improving the student's skills in operating with strings; using the find() method for searching strings. Scenario Let's play a game. We will give you two strings: one being a word (e.g., "dog") and the second being a combination of any characters. Your task is to ...
371f260c86651ae5ab2661cc17e01382602adc53
srinivasdasu24/Programming
/GUI Programming/controlling_keyboard.py
772
3.515625
4
""" Controlling keyboard using python """ import pyautogui pyautogui.click(100,100) # setting the position of the mouse to write pyautogui.typewrite("Hello world!", intervel=0.2) # gives gap 0.2 seconds between every character typing pyautogui.typewrite(['a','b','left','left','X','Y'], interval=1) # prints each ...
79c191ef4624ab1ae72eb550e3ff2ac3ccdb0738
srinivasdasu24/Programming
/File_operations/Excel_file_operations.py
985
3.8125
4
""" Explains how to edit, read ,write and do operations on xls sheets """ import openpyxl import os workbook=openpyxl.load_workbook("work_book location") type(workbook) sheet=workbook.get_sheet_by_name("sheet_name") # if we don;t know sheet names workbook.get_sheet_names() # gives list of sheet names cell=sheet...
999eb60081d178c863aaf231906767cdd6327b5d
srinivasdasu24/Programming
/Interviewquestions/Linkedlist/binary_to_decimal_inLL.py
1,028
3.75
4
''' Author: Dasu Srinivas Description: Given a binary number in a linked list, give its equivalent decimal number as output ''' import Interviewquestions.Linkedlist.Loopinalinkedlist as LL def getDecimal(binary): '''decimal = '' while binary: decimal += str(binary.data) binary = b...
c3d647a772bd73e06315ec4a4dab1c003fbd10fd
srinivasdasu24/Programming
/Interviewquestions/Stack and queue/stack using double linked list.py
1,555
3.921875
4
''' Author: Dasu Srinivas Description: Implement a stack using double linked list ''' class Node: def __init__(self, value): self.value = value self.next = None self.prev = None class Stack: def __init__(self): self.head = None def push(self, data): if se...
c2e9b05734369c855e7af25c8d281c70be9aaaf8
srinivasdasu24/Programming
/Interviewquestions/Sorting and Searching/Counting sort.py
432
4.0625
4
''' Author : Dasu Srinivas Description: Given an array with elements from 1 to n, sort the given array using count sort ''' def count_sort(arr): i=0 while i < len(arr): if 0 < arr[i] <= len(arr): if arr[arr[i]-1] != arr[i]: arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] ...
e8e4b75977fa6ef653772204c557fe3ffacf7d82
battle-test/basic-algorithm
/best_pratice/algorithm/pow.py
362
3.75
4
import time def pow(a, n): if n == 1: return a return pow(a, n - 1) * a def pow_1(a, n): if n ==0: return 1 elif n % 2 == 1: return pow(a,n-1)*a else: return pow(a**2,n//2) a = int(str(input())) n = int(str(input())) print(time.time()) print(pow(a,n)) print(time....
cd21e893b48d106b791d822b6fded66542924661
a12590/LeetCode_My
/100-149/link_preoder(stack)_flatten.py
1,798
4.1875
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ 非递归先序遍历,注意rtype void要求 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def flatten(self, root): """ :type root:...
d061cadba0be11769e2997d77e9f13f9ce5b40d0
a12590/LeetCode_My
/100-149/list_count_idea_candy.py
740
3.609375
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ 画图,x-1 x x+1、左遍历,右遍历 """ class Solution(object): def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ size = len(ratings) candies = [1] * size for x in range(1,size): if ratings[x] >...
5e5e40da4b1e5f55393ea1aaf4a86c63444d3595
a12590/LeetCode_My
/150-199/stack_(back-expression)_evalRPN.py
1,687
3.625
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ 对字符串的处理,Python: int(),C++/C: atoi(),Java: Integer.parseInt()。 需要注意的是 Python 的 / 操作。 例如,在Java中,6 / (-132) == 0(Java使用的是截断), 而在Python中,6 / (-132) == -1(Python使用的是floor)。 因此对除法的处理可以采用:int(float(x) / y),即可与Java的结果保持一致。 """ class Solution: # @param tokens, a list of string #...
4ce2ab2ec6f50095d49203d167d7774ef793a258
a12590/LeetCode_My
/150-199/link_tradition_getIntersectionNode.py
2,444
3.71875
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param two ListNodes # @return the intersected ListNode def getIntersectionNode(self, headA, headB): len...
70902c9e80507d1d66be204ddaca389232810086
a12590/LeetCode_My
/150-199/array_dynamic_maxProduct.py
2,347
3.546875
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ 动态规划:核心是存储+更新 这里更机智:不再考虑正负,就比较可能的最值。如果是负号的最大(小)值和如果是正号的最大(小)值 prevMax = fmax; fmax = Math.max(Math.max(nums[i] * prevMax, nums[i]), nums[i] * fmin); fmin = Math.min(Math.min(nums[i] * prevMax, nums[i]), nums[i] * fmin); # 就一句行的 ans = Math.max(ans, fmax); """ class Solutio...
58556adab3ec97f24dc5d1ba1eb4b6f1c2d403e4
a12590/LeetCode_My
/others/find_once_str.py
583
3.546875
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ public static int find(String str){ if(str==null||str.length()==0){ return -1; } int len = str.length(); char[] letter = str.toCharArray(); int[] count = new int[26]; for (int i = 0; i < len ; i++){ c...
b3a9b8a5bb76174334a2c9a6b6ca68a765f49cf5
a12590/LeetCode_My
/650_699/dict_isPossible.py
829
3.703125
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ """ Map + PriorityQueue 思路类似于排列扑克牌,优先将数字排在长度较小的扑克牌队列后面 Map<Integer, PriorityQueue<Integer>> dmap的key为扑克牌队列的末尾,value为优先队列,存储扑克牌队列的长度 """ import collections class Solution(object): def isPossible(self, nums): """ :type nums: List[int] :rtype: bool ...
56db6680ee71ac028d80721be24dff5e9c844f06
BrunoPessi/lista-exercicios-python
/ex7.py
897
4.1875
4
# 7 - Escreva um algoritmo que leia 10 números informados pelo usuário e, depois, informe o menor, número, # o maior número, a soma dos números informados e a média aritmética dos números informados. def maior (numeros): print("O maior numero digitado foi:",max(numeros)) def menor (numeros): print("O menor n...
8002e75ad6a2bddaf3ce57ca4a82e16bf0353339
BrunoPessi/lista-exercicios-python
/ex3.py
699
4.21875
4
# 3 - Crie uma classe calculadora com as quatro operações básicas (soma, subtração, multiplicação e divisão). O # usuário deve informar dois números e o programa deve fazer as quatro operações. (modifique para calcular tudo no # mesmo método, somando 1 ao resultado de cada operação). def calculadora (n1,n2): soma ...
b1d32d75b8867e786f58e3d771267549c5f70707
BrunoPessi/lista-exercicios-python
/ex17.py
268
4
4
# 17 - Cria uma lista para armazenar 5 nomes fixos. Após inserir os 5 nome da lista mostre-os no console (utilize um # for). def lista(): nomes = [] for i in range (5): n = (input("Digite um nome:")) nomes.append(n) print(nomes) lista()
cf396319e9e5bc74c7b56457ed61f8f3edb88f1c
keyurbsq/Consultadd
/Additional Task/ex9.py
399
3.84375
4
# Write a program to find out the occurrence of a specific character from an alphanumeric string k = "12abcbacbaba344ab" a = list(k) alpha = [] for i in a: if i not in alpha: if i.isalpha(): alpha.append(i) c = 0 for j in range(len(a)): if i ==...
32461c4739db2e7600c7ca1e77dcf28d8ae03c3e
keyurbsq/Consultadd
/Task3/ex5.py
241
3.96875
4
# Create a new list which contains the specified numbers after removing the even numbers from a predefined list. mylist = [4, 5, 3, 9, 1, 2] result = [] for x in mylist: if x % 2 != 0: result.append(x) print(result)
0717228de9ce2574cc9c097ea6456ea918e2f775
keyurbsq/Consultadd
/Task4/ex11.py
251
3.921875
4
# Write a program which uses map() and filter() to make a list whose elements are squares of even # numbers in [1,2,3,4,5,6,7,8,9,10]. lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, lst))))
da3eda512f68dd20b24f21ea61727640a02ae45d
keyurbsq/Consultadd
/Task3/ex9.py
244
3.90625
4
# Create a dictionary that contain numbers in the form(x:x*x) where x takes all the values between 1 and n(both 1 and n included). n = int(input("Please enter number: ")) d = {} for x in range(1, n + 1): d[x] = x * x print(d)
46bb311f095818ae38a85f8b0d1148e55ee71849
keyurbsq/Consultadd
/Task5/ex6.py
339
3.96875
4
""" Read doc.txt file using Python File handling concept and return only the even length string from the file """ with open('doc.txt', 'r') as file: # reading each line for line in file: # reading each word for word in line.split(): if len(word) % 2 == 0: ...
9f12786f688abb908c333b2249be6fb18bdcd1d6
keyurbsq/Consultadd
/Additional Task/ex6.py
258
4.4375
4
#Write a program in Python to iterate through the string “hello my name is abcde” and print the #string which is having an even length. k = 'hello my name is abcde' p = k.split(" ") print(p) for i in p: if len(i) % 2 == 0: print(i)
d63d46c893052f76ea6f0906dd7166af5793a27b
keyurbsq/Consultadd
/Additional Task/ex4.py
245
4.3125
4
#Write a program in Python to iterate through the list of numbers in the range of 1,100 and print #the number which is divisible by 3 and is a multiple of 2. a = range(1, 101) for i in a: if i%3 == 0 and i%2==0: print(i)
5ed9db1214745bf3920f99042148ae437025d48c
Acronymz/OG11_Python
/dictionaries.py
666
3.984375
4
def firstDict(a, b): return{a: b} a = input("Введите ключ для первого словаря:") b = input("Введите значение для первого словаря:") firstDictReady = firstDict(a, b) def secondDict(c, d): return{c: d} c = input("Введите ключ для второго словаря: ") d = input("Введите значение для второго словаря: ") secondDictR...
a4740e5ce0effbe14f8e20f0cabd797ea1692c8f
Alimobinifar/solve-650-python-Question
/650Pproblem/session1_P1.py
193
4.125
4
base =float(input('Please enter length of base :')) #get base height=float(input('Please Enter measurmnet of height :')) # get height result=base*height print('area is : {}'.format(result))
1a18c9f3a18e73817215ca072c9b3bdb93cd107d
futurulus/coop-nets
/third-party/stanza/stanza/research/iterators.py
5,270
3.984375
4
from itertools import islice, chain from six.moves import map as imap def iter_batches(iterable, batch_size): ''' Given a sequence or iterable, yield batches from that iterable until it runs out. Note that this function returns a generator, and also each batch will be a generator. :param iterable...
da83ffdd1873d70f4f5321c09c0a3ff1fb1ffc85
r0meroh/CSE_CLUB_cpp_to_python_workshop
/people_main.py
1,580
4.25
4
from person import * from worker import * import functions as fun def main(): # create list of both types of objects people = [] workers = [] # prompt user answer = input("adding a Person, worker? Or type exit to stop\n") answer = answer.upper() while answer != 'EXIT': # if an...