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
a610673e8d519e791c63155a3d1ad728cca8f93b
aaron64/pychic_type
/util/vec3f.py
654
3.796875
4
class vec3f: def __init__(self, x=0, y=0, z=0, vec=None): self.x = x self.y = y self.z = z if vec is not None: self.x = vec.x self.y = vec.y self.z = vec.z def __add__(self, other): return vec3f(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return vec3f(sel...
2faa54753e4d0572a01b0af696fb9354783a9fd5
Lillevang/euler
/20_factorial_digit_sum/solution.py
116
3.734375
4
# Find the sum of the digits in the number 100! import math print(sum([int(c) for c in str(math.factorial(100))]))
7f031a8099e5d036a61a8bb72a3af29e5ffe5b94
tripathyas/Online-Hackathon
/GeeksForGeeks/32_height_of_tree_when_leafnode_are_connected.py
1,168
3.84375
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.right.right = Node(5) root.right.right.right = Node(6) # root.right.right.right.left = root.right.left # root.right.right.right.r...
4eea131ef0d977c5fa508d21122d116f923bf860
tripathyas/Online-Hackathon
/GeeksForGeeks/38_reverse_linklist_of_given_size.py
1,159
4.09375
4
class Node: def __init__(self, value): self.value = value self.next = None node = Node(1) node.next = Node(2) node.next.next = Node(3) node.next.next.next = Node(4) node.next.next.next.next = Node(5) node.next.next.next.next.next = Node(6) node.next.next.next.next.next.next = Node(7) node.n...
a133ce70e9bebfacd72a3ec830c319598a495f7a
tripathyas/Online-Hackathon
/Util/oo_minsweeper.py
2,781
3.546875
4
class UserInput(): def __init__(self, value): self.operation = value.pop(0) remove = set(list(["(", ")" ,","])) temp = [x for x in value if x not in remove] self.x, self.y = int(temp.pop(0)), int(temp.pop(0)) class PlayBoard(): def __init__(self, x, y, matrix): self.x =...
a2d39b6382d66687417e4d335798e25f4762f41c
tripathyas/Online-Hackathon
/codeutility.py
388
3.515625
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 2.7 A.sort() i = 0 num = 1 while i < len(A) and A[i] <= 0: i += 1 while i < len(A): if A[i] == num: num+=1 elif A[i] > num:...
d239595956f2ebdd76d628be8aae6892ba43e352
Andeleisha/dicts-restaurant-ratings
/ratings.py
1,534
4.15625
4
"""Restaurant rating lister.""" # put your code here def build_dict_restaurants(filename, dictionary): """Takes a file and creates a dictionary of restaurants as keys and ratings as values""" with open(filename) as restaurant_ratings: for line in restaurant_ratings: line = line.strip() line = line.split(...
049d8d902ffdcc33b94da4a151b55b55ff46a5d4
priya7up/DigitRecognizer_Kaggle
/shift_image.py
1,894
3.53125
4
import pandas as pd import logging import sys def create_shifted_image(data, to_pixel, from_pixel): """ Helper function to shift image by one column to the left or to the right """ logging.info('Shifting image by one column from %s to %s followed by subsequent columns',from_pixel, to_pixel) #Cr...
fadf78811f212d6db848f557b5dff3df1e064d72
wr950320/python
/test_open_browser.py
1,798
3.5625
4
# encoding=utf8 # 写个小程序示例一下上次学的一些概念 # 这个程序的功能就是: # 根据用户输入的值,来选择打开不同的网站 # 这一句是导入一个别人写好的函数直接来使用 # 导入open函数,它的参数就是网址,功能是调用本地的浏览器打开一个网站 from webbrowser import open # 打印3个选项给用户选择输入 # 定义个函数,里面打印3句话 def print_3_sentence(): print("A: www.baidu.com") print("B: www.jd.com") print("C: www.taobao.com") pr...
0258d37f49569e9120d4755f3b30f81ca58eac96
wr950320/python
/test_for.py
792
3.984375
4
# encoding=utf8 # 循环语句 # 上次讲 数据类型的时候, 最后讲了2个复合类型的,也就是里面有多个值的, # list 和 dict, 记得吧 l1 = [1, 2, 3, 4, 5] m1 = {"name": "xxx", "age": 24, "salary": 10000} # 所谓的 循环, 就是循环这2样东西,把里面的值一项一项的读取一次,直到最后一个 # 循环的写法就是: # for i in xxx: # print(i) # 例子1: 循环打印l1里面的每一项 for i in l1: print(i) # 例子2: 循环打印m1里面的每一项(Key:...
77f5cb0efd5432ab76e35e3521ce3da03cfec5b7
m-w-turnbull/Python
/shift_numbers.py
561
4.0625
4
#!/usr/bin/env python3 # This script takes an array or list and moves list1 to the left while comparing it to the sum of list2 list1 = [1, 2, 3, 12, 9, 9] list2 = [] def shift_nums(): try: list2.append(list1.pop(0)) except IndexError: exit() else: check_sums() def check_sums(): ...
24e3edf2b126e55eeae8c654876249f42c4a0d3b
m-w-turnbull/Python
/sum_array_position2.py
597
3.6875
4
input_array = [1, 2, 4, 5, 6, 27, 92, 14, 28, 75] target = 42 def sum_array_pos(target, input_array): x = 0 y = 0 while y <= len(input_array) and x <= len(input_array): if sum(input_array[x:y]) == target: print(input_array[x:y]) print("Position: ", x + 1) elif sum(i...
9a62a23ba192d29379a130668ce96d8425a7b112
maxenceblanc/perfect-maze
/main.py
13,625
3.671875
4
#! /usr/bin/env python #-*- coding: utf-8 -*- from random import * import sys sys.setrecursionlimit(200000) # augmente le nombre de récursions possibles import time """ TO DO LIST """ """ PROBLEMS """ """ NOTES 0 1 2 3 4 5 6 0 - - - - - - - 1 - - - 2 - - - - - 3 - - 4 - - - - - - - """...
1ab812eefb4045019b6be6ceac1884a07092f4bf
sukritishah15/DS-Algo-Point
/Python/Karatsuba_Algorithm.py
850
3.859375
4
import math def karatsuba(x, y): if x < 10 and y < 10: # base case return x*y n = max(len(str(x)), len(str(y))) m = int(math.ceil(float(n)/2)) x_H = int(math.floor(x/10**m)) # first half of x x_L = int(x % (10**m)) # second half of x y_H = int(math.floor(y/10**m)) # first half of ...
f12370d769339351a1e01eb6189c6e45914fbd67
sukritishah15/DS-Algo-Point
/Python/armstrong_number.py
585
4.1875
4
n = int(input()) l = len(str(n)) s = 0 temp = n while temp > 0: s += (temp%10) ** l temp //= 10 if n == s: print("Armstrong number") else: print("Not an armstrong number") ''' Check whether a number entered by the user is Armstrong or not. A positive integer of n digits is called an Armstrong Number ...
ec34d801bf68c970a600d37ae6cc5a6e04fee1f6
sukritishah15/DS-Algo-Point
/Python/majority_element.py
733
4.375
4
# Python problem to find majority element in an array. def majorityElement(nums, n): nums.sort() for i in range(0, n): if(i+int(n/2)) < n and nums[i] == nums[i+int(n/2)]: return nums[i] return None n = int(input("Enter the total number of elements\n")) print('Enter a list of '+str(n)...
c1d8ba9a81d785d6a77de20d075150f371825ba7
sukritishah15/DS-Algo-Point
/Python/automorphic.py
423
4.125
4
# Automorphic Number: The last digits of thr square of the number is equal to the digit itself n=int(input("Enter the number: ")) sq= n**2 l=len(str(n)) ld=sq%pow(10,l) if (ld==n): print("Automorphic Number") else: print("Not a automorphic number") """ I/O Enter the number: 25 Automorphic Numbe...
d9cfdbf0470e759a95050249cc015fe0549dc776
sukritishah15/DS-Algo-Point
/Python/PancakeSort.py
890
4.03125
4
def flip(array, j): start = 0 while(start<j): temp = array[start] array[start] = array[j] array[j] = temp start = start +1 j -= 1 def findMaxIdx(array, n): mi = 0 for i in range(n): if (array[i] > array[mi]): mi = i return mi n = int(...
ccfe5912c428bbaf377448c3b4961ce2d3c4e838
sukritishah15/DS-Algo-Point
/Python/inordder.py
608
4.28125
4
class Node: def __init__(self,key): self.left = None self.right = None self.val = key def printInorder(root): if root: printInorder(root.left) print(root.val), printInorder(root.right) root = Node(1) root.left = Node(2) root.right = N...
ac8be461bbe4e170da84a1a00459dce4a1db45b4
sukritishah15/DS-Algo-Point
/Python/find_mid_element_in_linked_list.py
3,564
4.125
4
import math class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.size=0 self.head=None self.tail=None def append(self,node): self.size+=1 if(self.head==None): self.head=n...
7036f4e71ed1e3c3548799e56752e3663b8c7cc9
sukritishah15/DS-Algo-Point
/Python/arithmetic.py
926
4.09375
4
# Sum of Arithmetic Progression Series first = int(input("Please Enter First Number of an A.P: : ")) n = int(input("Please Enter the Total Numbers in this A.P: : ")) diff = int(input("Please Enter the Common Difference : ")) total = (n * (2 * first + (n - 1) * diff)) / 2 nth = first + (n - 1) * diff i = first print("...
00d927ab9488e3d8954720d71ee8272394f99739
sukritishah15/DS-Algo-Point
/Python/harmonic.py
372
4.3125
4
# Sum of harmonic series def sumHarmonic(n): i = 1 sum = 0.0 for i in range(1, n+1): sum = sum + 1/i; return sum; n = int(input("First term :")) print("Sum of the Harmonic Series :", sumHarmonic(n)) """" Example: First term : 6 Sum of the Harmonic Series : 2.4499999999999997 ......... Time...
8e9d0b9bdd672f5334d4888f93bac147e93c682e
martinm43/lc_analysis
/find_one_product_in_stores.py
2,515
3.515625
4
""" Search for one item in a set of stores. """ import urllib.request, urllib.error, urllib.parse import json from pprint import pprint import urllib.request, urllib.parse, urllib.error def single_inventory(store,productno): """ Takes store number, product number and returns the quantity of product or lack ther...
b628deb128b13e730eb6cc99e84ac68e1a48fe16
achauhan3/pythonlib
/src/Strings.py
167
3.828125
4
''' Created on 21-Aug-2019 @author: Abhishek ''' str1 = "I AM THE BEST" s1 = str1.capitalize() print(s1) s1 = str1.islower() print(s1) s1 = str1.lower() print(s1)
b367921c50c2a535bfa5ae13966a1d3666101d0f
skitoo/python-introduction
/scripts/prog2.py
377
3.59375
4
# -*- coding: utf-8 -*- # récupération de l'entré utilisateur valeur = raw_input('Saisissez un chiffre :') # on change le typage de la variable en chiffre entier valeur = int(valeur) # on calcule le carré de la valeur et on le stocke dans une variable carre = valeur * valeur # on affiche le carré de la valeur saisi...
b028d0f4ce60c780a16f59e8a5f6d358ffa9570f
prantostic/HackerRank
/Regex/Applications/UK and US Part 2/Solution.py
261
3.734375
4
#!bin/python3 import re n = int(input()) string = '\n'.join(input() for i in range(n)) t = int(input()) for i in range(t): word = input() lst = word.split('our') word = r'\b'+lst[0] + 'ou?r' + lst[1]+r'\b' print(len(re.findall(word, string)))
1d2e33e45d3d2882da1cc66bc7e2420a04de5b3b
richardzzp/windowsCtl
/main.py
549
3.546875
4
from pynput import keyboard, mouse def on_click(x, y, button, pressed): if pressed: print('{}'.format((x, y))) def on_press(key): if key == keyboard.Key.f12: print('==============================================') print('listener stop') return False return True def star...
f27c7559b5c424a9b82b2bfc777b459ced4bd39f
leandrocoding/sudoku
/BASolver2.py
1,457
3.546875
4
class InvaldSudoku(Exception): pass class NoNSolvable(Exception): pass def checksquare(num, i, j, grid): squarerow = i//3 squarecol = j//3 for rown in range(3): for coln in range(3): if grid[int(squarerow*3) + rown][j] == num: return False if grid[i][...
ac1de91984778a09cd17304a0f9768985ce7a3d2
meljean-legaspi/TDDKatasInPython
/WordCounter/word_counter.py
365
3.75
4
import re class WordCounter: @staticmethod def count(words): words_list = re.findall(r'[\w]+', words) word_counter = "" for word in words_list: if word not in word_counter: word_counter += word + ", " + str(words.count(word)) word_counter += ...
3e196daa806fefd28d1cbc257ae7d15cc9bc04ec
tapiolaa/MCOC---Intensivo-de-nivelaci-n
/19082019/000756.py
484
3.625
4
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal. """ #En esta secuencia de codigos se recordo el contenido relacionado con el funcionamiento del condicional If y sus derivados elif y else. #minuto 7:56 a = 1 # definiendo variables b = 2 if a < b: # condicional print('a i...
d8751a02ee3a822d30ccffc36f7774d14284aa92
roblivesinottawa/computer_science_principles
/conditionals/main.py
129
3.984375
4
def check_num(num): if num > 0: return f"{num} is positive." return f"{num} is negative." print(check_num(3))
aabf2577bd44425c702d6a670ba21dcef79c4aa0
dboldt7/PRG105
/Banana revised.py
1,207
4.21875
4
"""" Banana Bread Recipe: 2 cups of flour 1 teaspoon of baking soda 0.25 teaspoons of salt 0.5 cups of butter 0.75 cups of brown sugar 2 eggs 2.33 bananas Recipe produces 12 servings of bread Write a program that asks the user how many servings they want Program displays the ingredients needed to make the ...
034be83f9c793aea7e9ba66f65ca36b537928db4
dboldt7/PRG105
/Trivia Project.py
3,505
3.71875
4
class Question: def __init__(self, question, ans1, ans2, ans3, ans4, answer): self.__question = question self.__ans1 = ans1 self.__ans2 = ans2 self.__ans3 = ans3 self.__ans3 = ans3 self.__ans4 = ans4 self.__answer = answer def get_question(self)...
4d58fd2658087cccd782b2b14f05ed2e5cd138fc
dboldt7/PRG105
/lesson 5.2 logic.py
988
4.25
4
number = int(input("Enter a whole number between 20 and 100 ")) def divide_two(num): if num % 2 == 0: print(num, "is divisible by 2") else: print(num, "is not divisible by 2") def divide_three(num): if num % 3 == 0: print(num, "is divisible by 3") else: ...
ad391c7022ca79370ad1559ac24cc44e74cc8b82
dboldt7/PRG105
/8.3 Assignment/Revised 8.3 Program.py
842
3.59375
4
accounts_list = [] over_list = [] def main_func(): try: file1 = open('accounts.txt', 'r') line = file1.readline() while line != '': accounts_list.append(line.rstrip('\n')) line = file1.readline() file1.close() file2 = open('over90.t...
c3920afa242227c20a26747c5903249ca2fb2687
AliMazhar110/Python-Projects
/Guess-a-number/main.py
1,575
4.1875
4
#Number Guessing Game Objectives: from art import logo import random from os import system # Include an ASCII art logo. # Allow the player to submit a guess for a number between 1 and 100. # Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer. # If they got the answ...
f3d560d665ec9e5d4c0904775d65155509e67170
AliMazhar110/Python-Projects
/higher-lower/main.py
1,226
3.796875
4
from os import system from game_data import data from art import * import random finish = False score=0 while not finish: system('cls') print(logo) print("Current Score =",score) person_one = random.choice(data) while True: person_two = random.choice(data) if(person_one['name'] == p...
4feb8d7807e1818b8509895607463a35692b859e
AliMazhar110/Python-Projects
/Snake-Game/snake.py
1,348
3.984375
4
from turtle import Turtle class Snake: turtles = [] def __init__(self): turtle = Turtle("square") turtle.color("white") turtle.penup() if len(self.turtles) != 0: turtle.goto(self.turtles[-1].pos()) self.turtles.append(turtle) def move_forward(self): ...
2d35fa8c6a6340d2a13fc8059dd35d0818d4ab1c
ChaseSully222/Python-Classes-Exercise
/companiesAndEmployees.py
1,082
4.0625
4
# Create an Employee type that contains information about employees of a company. Each employee must have a name, job title, and employment start date. class Employee: def __init__(self, name, job_title, start_date): self.name = name self.job_title = job_title self.start_date = start_date ...
190c95e03ddc0a44d9e61e51ec62482cfdda17e3
dimdred/epm_trainings
/split&join.py
211
3.5
4
#import string #string join () q = 'td'.join(['1', '2', '3', '4']) q2 = ''.join(['1', '2', '3', '4']) print(q) print(q2) q3 = q.split('td') print(q3) s=''' multi string test ''' print(s) print(s.splitlines())
43e6d6d0aa4753cc84e281834336aab21eb14607
soonest94/Tutorial_Python
/type_complex.py
139
3.796875
4
print("How old" + " are you?") print("I`m " + str(3)) x = 4 #num type y = "4" #string type print(str(x) + y) print(x + int(y))
21e971b3c2377a403493ec4bceb53e4ba748ce79
soonest94/Tutorial_Python
/type_string.py
95
3.5
4
x = "Hello" y = 'Bye' print(x) print(y) z = """ Hola como estas? Hasta pronto! """ print(z)
1b680fbfb84e48590499923339d056885ddc01b0
timmyichen/cspp
/sols/0102-seconds.py
539
3.828125
4
def solution1(sec): mins = int(sec / 60) % 60 hrs = int(sec / 3600) sec = sec % 60 print("{}hr {}m {}s".format(hrs,mins,sec)) def solution2(sec): mins = sec // 60 % 60 hrs = sec // 3600 sec = sec % 60 print("{}hr {}m {}s".format(hrs,mins,sec)) def solution3(sec): hrs = se...
be2f4dd379fecb011733b2c4019a509b04d4c34a
timmyichen/cspp
/sols/detectEnglish.py
2,795
4.0625
4
#Detect English module #To use, type this code: # import detectEnglish # detectEnglish.is_english(someString) #returns true/false #(There must be a dictionary.txt file in this directory with # all english words in it, one per line. You can download # this file from http://invpy.com/dictionary.txt) # a string to ...
4bcae11d1da7b326f23b901e69fed0f2718bf796
dilciabarrios/Curso-Python
/14_Ahorcado/ahorcado.py
2,402
4.09375
4
# Importar Funciones Ahorcado import funcionesahorcado as fa palabra = fa.PalabraAleatoria() vidasRestantes = fa.ElegirDificultad() # Lista de letras usadas, creamos variables letrasAcertadas = [] letrasFalladas = [] seguirJuando = True while seguirJuando: #Mostrar la palabra con huecos en el usuario pal...
29e98b11111eb495b5c71f6e308abcb03881273c
dilciabarrios/Curso-Python
/5_Tipos_datos_avanzados/al_turron1.py
1,478
4.125
4
#Tenemos una lista con nombres de ciudades ciudadesDeEspaña = ['Granada','Cordoba','Santiago de Compostela','Paris','Malagá', 'Barcelona'] otrasCiudades = ['Toledo','Sevilla','Cadiz','Berlin','Alicante'] #Tareas # 1- Quitar de la listas las ciudades que no pertezcan a España (Berlin y Paris) # 2- Unir ambas listas e...
dad220d45f564e9cdc03afef585d6e6f0196a9ea
dilciabarrios/Curso-Python
/11_Ficheros/leer_ficheros.py
417
3.765625
4
# Trabajar con ficheros en Python: # open(nombreDelFichero, modoDeApertura) # r -> Read - Leer # w -> Write - Escribir # a -> Append - Añadir # r+ -> Read+ - Leer y escribir miArchivo = open('mifichero.txt', 'r') # Leo una segunda linea segundaLineaLeida = miArchivo.readline() print(segundaLineaLeida) ...
f3dccd370b40a781ab0854040305fa7415609131
dilciabarrios/Curso-Python
/9_Funciones/al_turron.py
1,698
4.34375
4
#Objetivo: dividir las diferentes operaciones en funciones: #Ademas, añadir: #Una comprobacion que nos diga si el numero par o impar #Una comprobacion que nos diga si el numero es primo o no def ComprobarSiEsPar (numero): if (numero % 2 == 0): return True else: return False def ComprobarMultip...
f621677915b5c94c9764e4cd913d9feb167025eb
dilciabarrios/Curso-Python
/7_Control_flujo_condicionales.py/al_turron.py
2,594
3.9375
4
#Objetivo : decirle al usuario el precio que tendria que pagar por su entrada al museo #las tarifas son: #Niño (hasta 6 años): No paga #Joven (hasta 21 años): 9$ #Adulto: 14$ #Jubilado (a partir de 67 años): 6$ #Además, hemos repartido unos descuentos en el ultimo mes del 10%. Si un usuario tiene un descuento y lo dice...
1147112c2a786e7e1c20436914cbe043db9b97dc
dilciabarrios/Curso-Python
/12_Debug/al_turron.py
986
4.40625
4
print('Bienvenido al sistema de almacenamiento de usuarios.') usuarios = ['Juan','Marta','Miguel','Elisa','Claudia','Jorge','Ana','Pedro'] while(True): print('''--- ¿Qué operación deseas realizar? 1 - Ver una lista de usuarios 2 - Añadir un usuario 3 - Eliminar un usuario X - Salir del programa...
fcbec8cc1282117ba22b94c840945ee989b75177
emmasnashall/shizzle
/basic_maths.py
389
4.0625
4
print(2*3) print(2+3) print(2/3) print(2//3) print(2%3) a=5 b=7 c=a+b print(c) print(a**2) y=float(2) x=float(3) u=float(4) v=float(7) z=y/x print(float(z)) #wiki exercise 1 print(2**2**2**2) #wiki exercise 2 t=(x+y)**u print(t) print(float(t/7)) #wiki exercise 3 q=float(10) p=float(9) r=float(q/p) print(floa...
1212bc9f1568d5e53c46618f91faa55f24b9af46
leofoch/PY
/Practica_Generador.py
284
3.625
4
def generaPares(limite): num=1 while num<limite: yield num*2 num=num+1 devuelvePares=generaPares(10) print(next(devuelvePares)) print("jjjj") print(next(devuelvePares)) print("jjjj") print(next(devuelvePares)) print("jjjj") print(next(devuelvePares))
357c290a2c2ab8f2ce0e8da3552084d3f4218518
leofoch/PY
/ManejoDeCadenas.py
494
4.15625
4
#documentacion en: http://pyspanishdoc.sourceforge.net/lib/module-string.html #nombreUsuario=input("intro nombre: ") #print("El nombre es: ", nombreUsuario.upper()) #print("El nombre es: ", nombreUsuario.capitalize()) edad=input("intro Edad: ") while(edad.isdigit()==False): print("No es numerico") edad=input...
a3b2ee82b0496a2f85550fb08d2af35fe6ba377e
leofoch/PY
/ImfoPermanente.py
2,230
3.546875
4
import pickle class Persona: def __init__(self,nombre,genero,edad): self.nombre=nombre self.genero=genero self.edad=edad print("se creo una persona nueva con el mobre: ", self.nombre) def __str__(self): return "{} {} {}".format(self.nombre,self.genero,self.edad) class...
b333df984026d93ec01411fa04f2214b05c20893
leofoch/PY
/Polimorfismo.py
669
3.53125
4
class Coche(): def desplazamiento(self): print("Me desplazo utilizando 4 ruedas") class Moto(): def desplazamiento(self): print("Me desplazo utilizando 2 ruedas") class Camion(): def desplazamiento(self): print("Me desplazo utilizando 6 ruedas") #miVehiculo=Moto() #miVehiculo.des...
5e4e1e90f4678b7ef758b05959b4582b7f3a749f
hthompson97/advent_of_code_2020
/main.py
8,780
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 10:25:59 2020 @author: 597799 """ #import csv import pandas as pd import re import numpy as np def day1(input): ret = { 'part1' : None, 'part2' : None } #part 1 for num1 in input: for num2 in input: i...
fc639924b4bb0042ad701bd7333777315e913c77
rhgrant10/advent-of-code_python
/aoc/problems/y2017_d12.py
1,158
3.546875
4
# -*- coding: utf-8 -*- import collections def parse_graph(input_): graph = collections.defaultdict(set) for line in input_.strip().splitlines(): node, children = parse_line(line) graph[node] |= set(children) return graph def parse_line(line): node, children = line.split('<->') c...
b5da6869b0f0ef2671518245438265aa55a60b62
svaiyapu/algo
/sort/insertion.py
636
3.921875
4
#!/usr/bin/env python # best case : O(N) # average case : O(N**2) # worst case : O(N**2) # good for mstly sorted data def isort(a): print a if len(a) == 1: return a for i in range(1,len(a)): # insert ith element in it's position insert(a,i) return a def insert(a,i): #...
7a25b0835d88d49aa58d3e3723be0b5945045228
svaiyapu/algo
/search/hash.py
328
3.59375
4
#!/usr/bin/env python # O(1) def build_hash(a): return dict([(v,i) for i,v in enumerate(a)]) def find(e, a): ''' Returns position or None''' h = build_hash(a) if h.has_key(e): return h[e] return None if __name__ == '__main__': print find(1, [0,1,2,3,4,5]) print find(9, [0,1,2,...
d00386c84a11c21315e7adbb35213b5555231e84
ferghodg/portfolio
/python/Queues.py
694
3.78125
4
class Queue: def __init__(self): self.items=[] def add(self, item): self.items.append(item) def delete(self): itemToDelete=self.items[0] del self.items[0] return itemToDelete def size(self): return len(self.items) def report(self): ...
1417ecdc6199776326f1edf9fec22650ab697f9b
MareboinaRavi/python
/FunctionCaching.py
256
3.5625
4
from functools import lru_cache @lru_cache(maxsize = 10) def fibonacci_sequence(n): if n < 2: return n else: return fibonacci_sequence(n - 1) + fibonacci_sequence(n - 2) print(fibonacci_sequence(10)) fibonacci_sequence.cache_clear()
58d4f19b3769525728ccf359cf2b2f554d88ff84
PacktPublishing/-Python-By-Example
/Section 1/Section1/Video4_collections_6_comprehensions_set.py
640
3.75
4
''' Created on Mar 31, 2018 @author: Burkhard A. Meier ''' # list of inventory with different upper and lower case strings inventory = ['car 1', 'CAR 2', 'tree', 'CAR 1', 'tomato PlAnt', 'bucket', 'BUCKET'] print(inventory) # list using for loop inventory_cap = [] for item in inventory: inventory_cap.append(...
db509bc5c514d48ea0dfcfd2b0445bd8879e87a3
PacktPublishing/-Python-By-Example
/Section 1/Section1/Video2_Nesting_Python_dicts_2_vehicles.py
784
4.15625
4
''' Created on Mar 30, 2018 @author: Burkhard A. Meier ''' from pprint import pprint cars = {} car_1 = {'make': 'BMW', 'speed': 'fast'} car_2 = {'make': 'Mercedes', 'speed': 'good'} car_3 = {'make': 'Porsche', 'speed': 'very fast'} cars['car 1'] = car_1 cars['car 2'] = ca...
4b5e15bb79f0a022bb95e2538d55b37970d0207a
SrikarValluri/Software_Engineering_2
/hw7/q2.py
275
3.65625
4
def leapyear(x): if(x % 4 == 0): if(x % 100 == 0): if(x % 400 == 0): return("Leap Year") else: return("Not Leap Year") else: return("Leap Year") else: return("Not Leap Year")
233d0067b828c7d7a12c6fd0d7c8e5f2f3d5476a
Elyseum/python-crash-course
/ch9/car.py
1,512
4.25
4
""" Modifying class state """ class Car(): """ Simple car """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ Formatting a descriptive name """ long_na...
97348bc9b26f1961131ce494df8bf6a079835b2a
Elyseum/python-crash-course
/ch10/division.py
231
4.09375
4
""" Working with exceptions """ try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") try: ANSWER = 5/2 except ZeroDivisionError: print("You can't divide by zero!") else: print(ANSWER)
92eaf41e7093c52216487e96553cb00fb0b17cc5
Elyseum/python-crash-course
/ch8/formatted_name.py
788
4.25
4
""" Return values """ def get_formatted_name(first_name, last_name): """ Returns a full name, neatly formatted""" full_name = first_name + ' ' + last_name return full_name.title() MUSICIAN = get_formatted_name('jimi', 'hendrix') print(MUSICIAN) def get_formatted_name_2(first_name, last_name, middle_n...
78b8a626de1b94ea3872572d04ca9322b2f9aa23
Balakrishnan123745/Python-pentafox
/newfile5.py
228
3.640625
4
import random b=["a1","a2","a3","a4","a5"] b1=[] for i in range(5): s=random.sample(b,5) if s not in b1: b1.append(s) for i in range(5): for j in range(5): print(b1[i][j],end=" ") print()
593548f3a0ec9e6830c219d29624d6a67d6d984c
vitoreticode/python_review
/list_comprehension.py
1,384
3.828125
4
# list comprehension l = [ 2 * num for num in range(0,10)] # list comprehension with condition nums_new = [num for num in range(1, 11) if num % 2 == 0] text = "list COMPREHENSION is A way TO create LISTS" output = [len(word) for word in text.split()] output = [len(word) for word in text.split() if word.islo...
aafede9e119ba4fdd5d148fe5e4d09cbe0fcfdbb
chrisfisch914/AdventOfCode2020
/Day7/day7-2.py
1,074
3.640625
4
def fetch_input(): data = [] with open('input.txt', 'r') as file: data = file.read() return data.split("\n") def parse_input_to_map(input): result = {} for line in input: fields = line.split("contain ") key_values = fields[0].split(" ") key = key_values[0] + " " + ke...
939f29f858f8599afdc37cf78a020d7ee78d870a
chrisfisch914/AdventOfCode2020
/Day4/day4-1.py
768
3.53125
4
def fetch_input(): data = [] with open('input.txt', 'r') as file: data = file.read() data = data.split("\n") input = [] curr = "" for line in data: if len(line) == 0: input.append(curr) curr = "" else: curr += " " curr += li...
d21a870bde6c7df371f90e704ed0d310daa00f54
bridgecrew-perf7/My_Olympic_Model_Deployment
/weight.py
838
3.578125
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression def lift_prediction(bw): data = pd.read_csv('/Users/Francis/Desktop/machinelearning/weightlifting.csv') data = data.drop_duplicates() data = data.dropna() #Chan...
67521e01a85000bdd542ddb878a6bb754040292b
thisum/HackerRank-Python
/com/thisum/hackerrank/CamelCase.py
322
3.890625
4
#!/bin/python3 import math import os import random import re import sys # Complete the camelcase function below. def camelcase(s): count = 0 for x in s: if x.isupper(): count += 1 return count+1 if __name__ == '__main__': s = input() result = camelcase(s) print(result...
b01667fe0a8536291c467a7d5ba8a14ad5d42975
thisum/HackerRank-Python
/com/thisum/hackerrank/ManasaAndStones.py
793
3.5625
4
#!/bin/python3 import math import os import random import re import sys # Complete the stones function below. def stones_loop_method(n, a, b): result = set() for i in range(pow(2,n-1)): final = 0 k = n-2 while k > -1: final += a if (k > 0 and i//pow(2,k) == 0) or (k == 0 a...
f21caae41042f33a4a60ea9ebcc8211b85d62bd2
jormao/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
939
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This module have a function that prints My name is <first name> <last name> prototype: def say_my_name(first_name, last_name=""): """ def say_my_name(first_name, last_name=""): """ function that prints My name is <first name> <last name> first_name and last_nam...
92cea75e2ba95485b3c7266602dc0ff0f6f5f0e0
jormao/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/10-best_score.py
241
3.640625
4
#!/usr/bin/python3 def best_score(a_dictionary): if a_dictionary: a = max(sorted(a_dictionary.values())) for i, v in a_dictionary.items(): if a == v: return (i) else: return (None)
68a8333890e951b7209b5bdafe6b93ccfba0f37a
XACT-RobA/Uni-Cryptology
/python/abmod26.py
127
3.796875
4
for a in range(26): for b in range(26): if (a*b)%26 == 1: print('a: ' + str(a) + ', ' + 'b: ' + str(b))
e4329d230e03c8ee5884fcc5b3117eea0ec96638
avinashsp93/competitive-coding-solutions
/HackerRank/ProjectEuler/19-CountingSundays.py
1,322
3.546875
4
# 19. Counting Sundays # Language: Python 3 # Testcases: 8/8 T = int(input()) while(T > 0): Y1,M1,D1 = [int(i) for i in input().strip().split(' ')] Y2,M2,D2 = [int(j) for j in input().strip().split(' ')] if(D1 != 1): M1+=1 if(M1 < 3): M1+=12 Y1-=1 if(M2 < 3): M2+...
3c951b75e20b2aba8a2d67177320259ebf9447de
KTangg/CS50AI
/project/project0/tictactoe/tictactoe.py
5,156
4.0625
4
""" Tic Tac Toe Player """ import math from copy import deepcopy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Return...
458ac18d04f1216734c59f3eba419b587b80ff07
EddyGiusepe/REGEX_Python
/regex_1.py
1,561
3.796875
4
# O link REGEX é: https://www.youtube.com/watch?v=Jao4VwJCByk&t=135s # Regular Expression HOWTO: https://docs.python.org/3/howto/regex.html # Importando a biblioteca import re print("#######################") print("# CARACTERES NO REGEX #") print("#######################") # . - Entende qualquer valor exceto uma no...
f6714471ab9b63db1b5b6539fbee23ec67e1744d
olikami/Informatics_I-Exercise_6
/task 2/vehicle.py
2,189
3.5
4
import sys class Vehicle(object): vehicle_id = 0 vehicles_sold = [] def __init__(self,year,mileage,purchase_price,serial_number): try: self._year = int(year) self._mileage = int(mileage) self._purchase_price = int(purchase_price) except ValueError as e:...
8cc197d35897df600dc0f74bc48a9cbdf832d936
carlclone/python-concurrent-programming-demo
/co4.py
887
3.671875
4
import asyncio async def worker_1(): print('worker_1 start') await asyncio.sleep(1) # 任务调度点 , cpu闲置 , 调度到其他任务执行 print('worker_1 done') async def worker_2(): print('worker_2 start') await asyncio.sleep(2) # 任务调度点 , cpu闲置 , 调度到其他任务执行 print('worker_2 done') async def main(): task1 ...
37717798d891a8b42e28a716c0ef8d584eb97006
vitor-amartins/methods
/adams_bashforth.py
5,782
4.03125
4
import matplotlib.pyplot import math from decimal import * func = input("Type the function (y'): ") def function(t, y): return eval(func) height = 0 tf = 0 y = []; t = []; #PVI y.append(Decimal(input("Type the y0: "))) t.append(Decimal(input("Type the t0: "))) #Menu options print("1 - Enter height and number of ...
c35795e499207e680378ce6f0fed03951dd67362
yuispeuda/pro-lang
/python/calısma-soruları/matris_calısmaları/kolon.py
208
3.578125
4
def kolon(a,b): liste = [] liste.append(a) liste.append(b) i= 0 for eleman in liste: eleman.append(0) liste[i]= eleman i += 1 print liste kolon([1, 1],[0, 1])
25b39f10b8f5b894f2147b3452eb6961764ea24f
yuispeuda/pro-lang
/python/calısma-soruları/matris_calısmaları/insert_at_end.py
413
3.859375
4
def insert_at_end(value,seq): if type(seq) == list: u = len(seq) liste = [0]*(u+1) for i in range(u): liste[i] = seq[i] liste[-1] = value print liste elif type(seq) == str: seq = seq + value print seq else : seq = seq[:] + (value,) ...
b7296b3ba147572e9ccea8fb02217a9ac353dc1a
yuispeuda/pro-lang
/python/foyler/foy_11/hizli_fibonacci.py
517
3.890625
4
# -*- coding: utf-8 -*- def hizli_fibonacci(n): if n < 0 or type(n) == float:print "Lütfen pozitif bir tam sayi giriniz." else: sozluk = {0:0,1:1,2:1,3:2,4:3,5:5,6:8,7:13,8:21,9:34,10:55} key_listesi = sozluk.keys() kontrol = n in key_listesi if kontrol == True:print sozluk[n] ...
9795c4bca8694d57f43aa69a3ddd8c43ea9a656e
yuispeuda/pro-lang
/veri_yapilari/prefixeval.py
893
3.546875
4
class Stack: def __init__(self): self.liste = [] def isEmpty(self): return self.liste == [] def pop(self): return self.liste.pop() def push(self, item): return self.liste.append(item) def prefixEval(prefixdizi): s = Stack() tokenList = prefixdizi.split() ...
6dd583e8f27058c6a0c7670da464fe41189850f7
yuispeuda/pro-lang
/python/calısma-soruları/matris_calısmaları/icice_max_deger.py
464
3.65625
4
def icice_max_deger(liste): liste1 = [] for i in liste: if type(i) == list: for n in range(len(i)): for j in i: if type(j) == list: for n in range(len(j)): i = j el...
dc287578547ecfda7fd37852174f3d27408809c9
yuispeuda/pro-lang
/veri_yapilari/oncelikli_kuyruk.py
944
3.53125
4
class oncelikli_kuyruk: def __init__(self): self.liste = [] def peek(self): return self.liste[len(self.liste) - 1] def enq(self, item): eleman, oncelik = item if self.isEmpty(): return self.liste.append(item) else: pee = self.peek() ...
9e1910dc07abd3606eb3d46ed75337a78ecf7756
yuispeuda/pro-lang
/python/foyler/foy_08/Lab08_analiz.py.py
461
3.78125
4
# -*- coding: cp1254 -*- def analiz(liste): k,t,f,l,b = 0,0,0,0,0 for i in liste: if type(i) == str: k += 1 elif type(i) == int: t += 1 elif type(i) == float: f += 1 elif type(i) == list: l += 1 else: ...
62f5d3e797c4f305d12a126ed991b93e9741c8fb
yuispeuda/pro-lang
/python/calısma-soruları/matris_calısmaları/my_sort.py
593
4.0625
4
def my_sort(liste): liste1,liste2,liste3 = [],[],[] for ch in liste: m = str(ch) k = ord(m) liste1.append(k) for i in range(len(liste1)): max_ord = max(liste1) liste2.insert(0,chr(max_ord)) liste1.remove(max_ord) for j in liste2: cins = type(j) ...
67b1a46b4b103b8e31814352fe43ba0cb3a3d20c
K10shah/Linear-regression-on-LeToR
/regressionEssentials.py
4,859
3.59375
4
import numpy as np import pandas as pd import scipy.stats as stats import sklearn.cluster as cl from sklearn.metrics import mean_squared_error from math import sqrt import matplotlib.pyplot as plt # Cluster the data into K clusters using KMeans clustering. def calculateM(data, k): # Calculates the number of basis fun...
142d363991cee9effa5cb81733ec7a44f4c23f24
surendrabharathi-velloredakshinamoorthy/hello-world
/day3/palindrome.py
138
4.21875
4
text = input("Enter the string\n") reversetext = text[::-1] if reversetext == text : print("Palindrome") else: print("Not palindrome")
7e75946f9a18a0525d5ff8825c912c97c98f474f
surendrabharathi-velloredakshinamoorthy/hello-world
/day4/sorted_list.py
194
3.90625
4
mylist = [1,2,2] def sorted_list(): for i in range (0,len(mylist)): if (mylist [i] < mylist [i+1]): print("True") return True else: print("False") return False sorted_list()
a2c0951c786bea18660ec0d7809359e3ac88fd65
screaminglordbyron/IDS-project
/Lemmatiser.py
9,603
3.890625
4
import pandas as pd import numpy as np from estnltk import Text from langdetect import detect # Please refer to the readme file for more information about the necessary Python libraries and linguistics-related terminology # Read in the data, appropriately named data = pd.read_csv("data.csv", sep='\t', low_m...
48af3a3a7920e8b0fc67cca325cc3d1305db77d1
PureWater100/DATA-690-WANG
/ass_2/ass2.py
1,413
4.21875
4
# python file for assignment 2 # code from the jupyter notebook user_inputs = [] MAX_TRY = 11 for i in range(1, MAX_TRY): while True: try: user_input = input("Please enter an integer:") in_input = int(user_input) break except: print("Please retry (...
70f0655c193ab0353d8549afecf76a840472d6d1
tinix84/exercism
/python/pangram/pangram.py
298
3.546875
4
from collections import Counter def is_pangram(sentence:str): pangram_sentence = False cnt = Counter(sentence.lower()) char_list = [c for c in list(cnt.keys()) if c.isalpha()] if len(char_list) == 26: pangram_sentence = True return pangram_sentence
323aa65972ca7fbae4ff1846b90bb9ca67d76977
selvendiranj-zz/python-tutorial
/hello-world/file_io.py
2,168
4.03125
4
# ##################################### # Printing to the Screen # ##################################### print "Python is really a great language,", "isn't it?" # ##################################### # Reading Keyboard Input # ##################################### # reads one line from standard input # str = raw_i...
bb7f5649c7f2fd7a02b8a4a0a26e4cd901689932
selvendiranj-zz/python-tutorial
/hello-world/tuples.py
916
3.96875
4
""" Python Tuples A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements...
5c3e03c9ec8a0c41e68d542f959098169adf612f
selvendiranj-zz/python-tutorial
/hello-world/exceptions.py
2,018
4.3125
4
""" Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them Exception Handling Assertions """ def KelvinToFahrenheit(Temperature): assert (Temperature >= 0), "Colder than absolute zero!" return ((Temperature - 273) * 1.8) +...