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
f32c2b197598ac6dc6f0a20c70d29980358a4521
Janet-ctrl/python
/Chapter4/try116412.py
336
4.0625
4
pizzas =['pikkant', 'meaty treat', 'three cheese', 'chicken', 'sweet chilli'] friend_pizzas = pizzas[:] pizzas.append('vegi') friend_pizzas.append('hawain') print('My favorite pizzas are:') for pizza in pizzas: print(pizza.title()) print('\nMy Friend\'s favorite pizzas are:') for pizza in friend_pizzas: prin...
b26882901a152805d40a5ba3baab3faa2ce6711d
sheilla13/Korelasi-Jenis-Presensi-Terhadap-Minat-Kehadiran-Mahasiswa
/NaiveBayes.py
968
3.8125
4
# coding: utf-8 # In[1]: #import libraries import random # to randomize the training dataset import math # self-explanatory import pprint # to pretty print our initial non-panda dataset import pandas as pd # to list and do vector manipulation # In[2]: df = pd.read_csv("DataTraining.csv") print df # In[3]: d...
ec6d27a25b48a88cf1c90f3949f3d88d3f954454
NukeWolf/Advent-Of-Code-2020-Nukewolf
/18/order of operations.py
2,411
3.640625
4
import re with open('input.txt','r') as f: lines = f.readlines() lines = [x.strip().replace(" ","") for x in lines] #print(lines) #Part 1 def findEndParen(string): current = 1 for ind,val in enumerate(string): if(val == "("): current +=1 elif(val == ")"): current -=1...
7dd06e09fcd98cbc31e8bde1d16fb7b41bec9266
NukeWolf/Advent-Of-Code-2020-Nukewolf
/21/Allergens.py
1,857
3.640625
4
with open('input.txt','r') as f: lines = f.read().strip().split('\n') allergenList = [] for food in lines: foods = {} split = food.split(' (contains ') foods['ingredients'] = split[0].split(' ') allergy = split[1][:-1].split(', ') foods['allergens'] = allergy allergenList.append(foods) alle...
b2b652acf6f4c5dbd568b6d7ce7cda4286371d59
Resolt/ML_Bootcamp
/LinearRegression/LinearRegressionProject.py
2,334
3.5625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression as LR from sklearn.model_selection import train_test_split from sklearn import metrics plt.style.use('ggplot') # plt.tight_layout() dir = 'Bootcamp/LinearRegression/' df = pd....
499d425b3c3e8a3e3f3381f2f50230f6a76dc8cc
Grissie/Python
/1-Sintaxis/02-tipos-datos.py
560
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 12 19:00:17 2020 @author: Gris """ def main(): x=None y=5*2+4-3*8 z=5/2.0 w="Esto es una cadena" d='Esta es un dicho "Más vale pájaro en mano, que cientos volando"' a="""Esto también es una cadena""" entrada=input("Ingrese su nombre: ") ...
32c15b7519c1bdf963fab88891dc2f9dc29cb6e4
Grissie/Python
/1-Sintaxis/22-funciones-valor-referencia.py
1,022
3.84375
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 20:06:42 2020 @author: Gris """ #Referencia -> Listas def doblarValores(numeros): for i in range(0,len(numeros)-1): numeros[i] *= 2 ns=[2,4,8,10,12,14] print("Lista inicial") print(ns) doblarValores(ns) print("Lista duplicada") print(ns) #Valor def numero(a): a...
08687482497f528b16fbd3d6a7d7270021cf08b9
Grissie/Python
/2-Algoritmos de ordenamiento/4-heapSort.py
1,637
3.765625
4
def heapify(l,i): #Si el nodo tiene dos hijos if 2*i+2<=len(l)-1: #El hijo izquierdo es menor al hijo derecho if l[2*i+1]<= l[2*i+2]: min=2*i+1 #El hijo derecho es el menor else: min=2*i+2 #Comparar el valor del menor de los hijos con el padre, pre...
9a4720d070f056e06b8c73bcee97ca49c7d76049
Grissie/Python
/1-Sintaxis/29-expresiones-regulares.py
1,116
3.625
4
#-*- coding: utf-8 -*- """ Created on Thu Sep 24 21:54:24 2020 @author: Gris """ #Libreria para hacer uso de expresiones regulares import re buscar='no' texto='Este es un texto de ejemplo, el cual no dice nada en concreto. Además sirve para probar el modulo regex de python.' texto2='Nosotros no somos animales, som...
149dd9a37bd79adbc7a909bf6cd63a151a669d8f
bluivy/personal-assistant
/PatriciaParker2.py
1,437
3.546875
4
import speech_recognition as sr from time import ctime import time import os from gtts import gTTS def say(audiostring): print(audiostring) tts=gTTS(text=audiostring,lang='en-uk') tts.save("pcvoice.mp3") os.system("start pcvoice.mp3") def recordaudio(): r=sr.Recognizer() with sr.Micr...
5aeeda32fa924d2cd845a4936b71d98c6dc28885
linuxacademy/content-gui-programming-with-python
/messages.py
1,464
3.640625
4
import tkinter as tk import sys from tkinter import messagebox root = tk.Tk() root.minsize(width=200, height=250) root.resizable(width=False, height=False) def display_message(func_name, **kwargs): def display(): answer = getattr(sys.modules[messagebox.__name__], func_name)(**kwargs) if answer ==...
efffd3b52497bf990f8a02ea00af6f8f360f0270
musatoktas/Numerical_Analysis
/Python/Non-Linear Equations Roots/step_decreasing.py
387
4.125
4
x = float(input("Enter X value:")) h = float(input("Enter H value:")) a = float(input("Enter a value:")) eps = float(input("Enter Epsilon value:")) def my_func(k): import math j = math.sin(k) l = 2*pow(k,3) m = l-j-5 return m while (h>eps): y = my_func(x) z = my_func(x+h) if (y*z>0): ...
2c969e27e178cb286b98b7e320b5bbdcaee3b8f7
ProximaDas/HW06
/HW06_ex09_04.py
1,579
4.53125
5
#!/usr/bin/env python # HW06_ex09_04.py # (1) # Write a function named uses_only that takes a word and a string of letters, # and that returns True if the word contains only letters in the list. # - write uses_only # (2) # Can you make a sentence using only the letters acefhlo? Other than "Hoe # alfalfa?" # - writ...
6c4ecc2e39a5a1a0c59199b506255d7fa8694605
PuffyShoggoth/Competitive
/Fun Math/Prime Factorization.py
207
3.765625
4
import math n=int(input()) for i in range(n): f=int(input()) for k in range(2, int(math.sqrt(f))+2): while f%k==0: print(k, end=" ") f=f//k if f!=1: print(f) else: print()
87c381b53a57865e44be48395d1e7298273d5096
PuffyShoggoth/Competitive
/CCC/CCC '04 J4 - Simple Encryption.py
496
3.8125
4
keyword=input() withsymbols=input() tocode='' for i in range(0, len(withsymbols)): if withsymbols[i].isalpha(): tocode=tocode+withsymbols[i] c={} def lettershift(x, y): if ord(x)+ord(y)-ord('A')>ord('Z'): return chr((ord(x)+ord(y))-ord('Z')-1) else: return chr(ord(x)+ord(y)-ord('A')) for i in range(0, le...
6c44aa1cb893940e31bd557dea89581b8cd90fd2
PuffyShoggoth/Competitive
/Seasonal/Rabbit Girls.py
140
3.703125
4
girls=int(input()) groups=int(input()) h=girls%groups if h==0: print(0) elif girls<groups: print(groups-girls) else: print(min(groups-h, h))
90721da9b3098ef0418361996ed0cbc0757ff048
PuffyShoggoth/Competitive
/Uncategorized/Boolean.py
122
3.8125
4
h=input().split() i=h.count('not') if i%2==0: print(h[len(h)-1]) elif h[len(h)-1]=='False': print(True) else: print(False)
cb78d8ee4206130172f0f32307cec5db7bbea3bc
PuffyShoggoth/Competitive
/CCC/CCC '02 S1 - The Students' Council Breakfast.py
582
3.78125
4
pink=int(input()) green=int(input()) red=int(input()) orange=int(input()) prof=int(input()) combos=0 mintic=prof for a in range(0, prof+1): for b in range(0, prof+1): for c in range(0, prof+1): for d in range(0, prof+1): if a*pink+b*green+c*red+d*orange==prof: print('# of P...
14141a05debe15e7b2e343affc461cb94fc93768
PuffyShoggoth/Competitive
/CCC/CCC '02 S2 - Fraction Action.py
336
3.671875
4
noom=int(input()) denom=int(input()) num=noom//denom fra=noom%denom for i in range(1, denom//2+1): if fra%i==0 and denom%i==0: fra=fra/i denom=denom/i if num==0 and fra==0: print('0') elif num==0: print(str(int(fra))+'/'+str(int(denom))) elif fra==0:print(int(num)) else: print(int(num),str(int(fra))+'/'+...
583535a0c18294a5c8996a07e658bc9b0c0331f4
PuffyShoggoth/Competitive
/CCC/CCC '15 J2 - Happy or Sad.py
278
3.640625
4
stg=str(input()) happy=0 sad=0 for i in range(0, len(stg)): if stg[i:i+3]==':-)': happy=happy+1 if stg[i:i+3]==':-(': sad=sad+1 if sad==0 and happy==0: print('none') elif sad==happy: print('unsure') elif sad>happy: print('sad') else: print('happy')
aac914aab179e655a9af2cbb9bf3a5f3b01d79fe
PuffyShoggoth/Competitive
/GFSSOC/OR-deal.py
65
3.609375
4
n=int(input()) while(n>1): print(1, end="") n=n//2 print(1)
fcdddc65c38a3fef5cd2ea1e24e601a4db05db11
jerrypirkle/Scrapers
/pysrt.py
921
3.84375
4
#!/usr/bin/env python3 """ Creates a list of planets and sorts alphabetically """ __author__ = "jerry pirkle" __version__ = "0.1.0" __license__ = "MIT" def main(): """ Input: Sector text file with items delimited with % Output: Sorted list of planets """ # Should be taken as a command line argument if...
5a4b1df79339104f72a3ee9e9b3041116cbbc219
zxczhkzxc/image-etl
/object_detection_etl/utils/get_color_code.py
2,496
3.546875
4
from sklearn.cluster import KMeans from sklearn import metrics import cv2 # By Adrian Rosebrock import numpy as np import cv2 # Load the image # image = cv2.imread("red.png") image = cv2.imread("blue.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Resize it h, w, _ = image.shape w_new = int(100 * w / max(w, h...
6f434bc4ee40877cec79f70bb58400f90ccbc529
bramvanderzee/advent2019
/day04/4b.py
675
3.6875
4
lower = 353096 upper = 843213 def check(num, lower, upper): numList = sorted([int(x) for x in str(num)]) for i, x in enumerate(numList): if int(num[i]) != int(x): return False foundAdjacent = False for i, x in enumerate(num): if i == 5: break if int(num[i...
9f20edffd433138aae3ecb014c25b55790e122fc
bramvanderzee/advent2019
/day03/3b.py
1,611
3.671875
4
fn = 'input.txt' class Coord: def __init__(self, x, y): self.x = x self.y = y def pathToCoords(path): pointer = Coord(0,0) coords = [] for instruction in path: direction = instruction[0] dist = int(instruction[1:]) if direction == 'R': coords.extend([...
08e4640b17d9b466862ff168e76ef4bb7f39bb36
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio068.py
1,799
3.875
4
# Desafio068 programa que jogue par ou impar. finaliza quando jogador perder, mostrando total de vitorias consecutivas. # importanto a função rondom e a funçãi sleep. from random import randint import time numeropc = randint(0,10) resultadoFinal = str() resultadoFinalN = int() imparParPc = int falaPc = str() contador ...
351efcfee569a265f41fd78b55fbaa4c04f823c3
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio019b.py
200
3.578125
4
#Desafio019b segunda tentativa de criar( aplicação randomica para determinar que aluno vai no quadro. import random al01 = str('joao') al02 = str('paula') al = (al01,al02) print(random.choice(al))
9883f8a50e17c28d9ebfbb9b12b31464910ed2f9
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio049.py
258
3.90625
4
# Desafio049: fazer a tabuada num01 = int(input('insira um numero para saber a tabuada dele ')) ate = int(input('insira até onde quer a tabuada ')) for c in range(0,ate): number = c+1 num00 = number*num01 print(f'{num01} X {number} = {num00}')
a1ba04ea990b1b978940e7bc6ba5ba513a2bf683
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio017.py
248
4.0625
4
# descobre o valor da hypotenuse ( hipotenusa) from math import sqrt n1 = float(input('digite o comprimento do cateto oposto ')) n2 = float(input('digite o comprimento do cateto adjacente ')) print(f'O valor da hipotenusa é {sqrt(n1*n1+n2*n2)}')
369f7919463d3e478996444a97dad645cc9fbf9b
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio084b.py
962
3.90625
4
# Desafio084 ESSE PROGRAMA lê o nome e peso de varias pessoas. no final mostra quantas pessoas foram cadastradas listaTemp = [] namePeso = [] maior = 0 nmaior = '' menor = 0 nmenor = '' print('para sair do programa digite sair no campo nome') while True: listaTemp.append(str(input('Nome: '))) if 'sair' in list...
a2269827a7ec319057a12375b004b0118e6ea809
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/aula010.py
227
4.03125
4
# documentação bla bla bla, trabalahndo com if e else name = str(input('Qual o seu nome seu nome?')) if name == 'marco': print('Que nome de um cara fodelão!!!') else: print('que nome bosta') print(f'seja bem vindo {name}')
8d2569ca35b4e74a34839f736fbd7c47b174f580
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio058c.py
744
4
4
# Desafio058c descobrir numero com quente ou frio from random import randint numeroPc = randint(0,100) print(numeroPc) numeroUser = int() numerotemp = int() numerotemp2 = int() tentativas = int() while not numeroUser == numeroPc: numeroUser = int(input('Advinhe o numero de 0 a 100 que eu estou pensando!')) te...
aa1403aeaa7c51aa6031bd5361a55cb8a796bc78
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio086b.py
423
4.125
4
# Desafio086b criar uma matriz 3*3 e preencher ela com dados. alista = [[0,0,0],[0,0,0],[0,0,0]] for l in range(0,3): for c in range(0,3): alista[l][c] = int(input(f'Insira o numero da posição {l},{c}')) for c in range (0,3): for d in range(0,3): print(f'{alista[c][d]:^5}',end='') print() ...
c826d42f8b5564ced62fef3934aac2eb763030ac
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo3/Desafio104.py
430
4
4
# Desqafio104 o programa possui uma função que verifica se o input é um numero int def leiaInt (num): while True: if num.isnumeric(): return num #print(f'Você digitou {num}') #break else: print(f' {num} Não é um numero, digite um numero') ...
e9b0a04c85342e1b0c613a50fc9b78afea5fb2b3
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio051.py
458
3.859375
4
# Desafio051 fazer um sistema de P.A Progressao arentimetrica nInicial = int(input('Qual o valor inicial? ')) nRazao = int(input('Qual a Razão ? ')) nSquencia =int(input('Qual o tamanha da P.A? ')) sequen = nInicial-nRazao fim = int(0) while fim != nSquencia: sequen = + nRazao + sequen fim += 1 ...
86d68ee779c54c96654a40b6731b56af8f7a61fc
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio033.py
439
3.984375
4
#A aplicação recebe 3 idades e diz quem é mais velho a = int(input('digite a idade da primeira pessoa')) b = int(input('digite a idade da segunda pessoa')) c = int(input('digite a idade da terceira pessoa')) menor = (a) maior = (a) if b<a and b<c: menor = b elif c<a and c < b: menor = c print(f'o menor valor é ...
f8a8333d1f190af23e527f2e695f44d08a2ba184
Marcoakira/Desafios_Python_do_Curso_Guanabara
/Mundo2/Desafio039.py
581
3.78125
4
import datetime datenasc = int(input(f'insert you date of bit ')) atualdate = str(datetime.date.today())[0:4] datestr = int(atualdate) datefinal = datestr - datenasc print(datefinal) if datefinal < 18: print(f'voce esta com {datefinal}Faltam {18-datefinal} pra você se alistar ao exercito hahahah' ) elif datefinal =...
61561fd6a7d4af7158635d8b6a14ef10ff300038
bettalazza99/PCS2-Homework-4
/revp.py
570
3.53125
4
def reverse_complement(s): complements = {'A':'T', 'T':'A', 'G':'C', 'C':'G'} return ''.join([complements[a] for a in reversed(s)]) with open("C:\\Users\\Elisabetta\\Desktop\\rosalind_revp.txt")as dna: dna_str = dna.readlines() seq = "" for line in dna_str: line = line.strip() ...
fc8eb527c2948b443be22f8d8da3d6da81e4ca83
KetchupOnWaffles/sudokuGenerator
/show.py
872
3.65625
4
out = open("out.txt", 'w+') def show(line): li = "" for i in line: for j in i: li += str(j) + " " li += "\n" out.write(li) out.write("\n") showline = " _ _ _ _ _ _ _ _ _\n" showline += " _ _ _ _ _ _ _ _ _\n" showline += "| " counter = 0 counter2 ...
944e2a71557eb18ecf11191d81df48d7272485b7
nileshsingal/aws-practise
/python/Addition/addition.py
126
3.9375
4
a = int(input("Enter First Number: ")) b = int(input("Enter Second Number: ")) addition = a + b print("Sum Is :",addition)
22d26ae10374b19e6fb6718d6fdf57c73ed386e8
jasonxiaohan/DataStructure
/Map/Solution-349.py
804
3.8125
4
#!/usr/bin/env python # encoding: utf-8 """ @author: daixiaohan @license: (C) Copyright 2018, Node Supply Chain Manager Corporation Limited. @contact: jasonxiaohan198@qq.com @file: Solution-349.py @time: 2018/7/22 11:49 @desc: """ from DataStructure.Set.BSTSet import BSTSet class Solution: def intersection(self, ...
87cd59806c49e612324817a83a76c87cdcea4e9e
keshavkant0409/pythonSDET
/array_example4.py
988
4.0625
4
from numpy import * arr=array([4,6,7,8,9]) print(arr) arr=arr+5 print(arr) arr1=array([14,16,17,1,19]) arr3=arr+arr1 print(arr3) print(sin(arr3)) print(cos(arr3)) print(log(arr3)) print(sqrt(arr3)) print(sum(arr3)) print(min(arr3)) print(max(arr3)) print(sort(arr3)) arr4=concatenate([arr1,arr3]) print(arr4,'++++++++...
6b490f58bb97d4d2528c479fc9de5c98f3c22c4e
keshavkant0409/pythonSDET
/function_example1.py
233
3.78125
4
def summation(a,b): add=a+b print(add) summation(4,5) def summation1(a,b): add=a+b return add c=summation1(6,7) print(c) def sum_sub(a,b): add=a+b sub=a-b return sub,add c1,d=sum_sub(9,5) print(c1,d)
aea37d348ee18b8ad849540bd2ee511372c481ca
Fleshwork/100-Days-of-Python
/100 Days of Python/Day Two/Tip Calculator v1.py
437
4.09375
4
priceTotal = float(input("What was the total price of your bill? ")) tipPercent = int(input("How much tip? 10, 12 or 15%? ")) numberOfDiners = int(input("How many people are paying? ")) #pre calc maxTotal = tipPercent /100 * priceTotal + priceTotal #calculation pricePerPerson = maxTotal / numberOfDine...
fd5053556cb49b6580f6319b3b4bdbf416224d6e
KeerthanaPriya-B/ProgramS
/Comparing Strings.py
368
3.5
4
s1 = input() s2 = input() flag,first,second=0,'','' if len(s1)<len(s2): first=s1 second=s2 else: first=s2 second=s1 for j in first: for k in second: if(j==k): print('YES') flag=1 if flag==1: break ...
dd0ff2cd46ecbb046d3c9b341526b87e371f5eb1
KeerthanaPriya-B/ProgramS
/Print the missing alphabets.py
124
3.78125
4
s=input() alpha='abcdefghijklmnopqrstuvwxyz' missing="" for i in alpha: if i not in s: missing+=i print(missing)
78861ffe43fdcf67fdea185ff9efe32bc63b1d64
ehdqoddl6/coding-test
/backjoon/queue/2164.py
193
3.59375
4
from collections import deque n = int(input()) queue = deque(i+1 for i in range(n)) while(len(queue) > 1): queue.popleft() b = queue.popleft() queue.append(b) print(queue[0])
c44353f5a52823e55df8a6d68415b92207973b0b
ehdqoddl6/coding-test
/backjoon/sort/2751.py
360
3.546875
4
import sys input = sys.stdin.readline n = int(input()) num = [] for i in range(n): num.append(int(input())) import heapq def solution(array): h = [] for x in array: heapq.heappush(h, x) result = [] while(h): result.append(heapq.heappop(h)) return result num = sol...
79889a9fd5ef477fdd78c41afe6d530025f2dcb5
ehdqoddl6/coding-test
/backjoon/basicMath/2775.py
607
3.53125
4
#num = int(input()) def solve(k, n): n_list = [i for i in range(1, 15)] last_list = [] for i in range(k): ho_sum = [] sum = 0 if(i == 0): for j in range(n): sum = sum + n_list[j] ho_sum.append(sum) else: ...
35a03d4c5ebb51b272ce284076da59dddd3525ba
hgarciaospina/PythonArrays
/ejerc_2_40.py
3,415
3.875
4
''' 40. El dueño de una cadena de almacenes de artículos deportivos desea controlar sus ventas por medio de una computadora. Los datos de entrada son: a) El número del almacén (1 a 50) b) Un número que indica el deporte del artículo (1 a 20) Hacer un programa que escriba al final del día lo siguiente: 1. Las ventas ...
220fbfe3f19fa9c5a1446af79e821919c0095696
hgarciaospina/PythonArrays
/ejerc_2_1.py
868
3.6875
4
''' 1. Calcular el promedio de 10 valores almacenados en un vector. Determinar además cuantos son mayores que el promedio, imprimir el promedio, el número de datos mayores que el promedio y un listado de los valores que resultaron ser mayores al promedio. ''' vector = [25, 100, 30, 95, 80, 45, 87, 63, 11, 29] mayore...
8e8c0d8c6437ef40b0359ab97572b166a4631443
SahishnuTiwari88/OpenCVPython
/chapter3.py
498
3.59375
4
# Resizing & croping import cv2 img = cv2.imread("C:/Users/Sahishnu/Pictures/Screenshots/ada.png") print(img.shape) # it gives height,width and no. for your channels i.e. BGR i.e. colors imgResize = cv2.resize(img,(300,250)) # used to resize the image into desired height and width (width,height) imgCrop = img[0:...
308a96b56534d587575e0be55f037bdcbeb5c06e
subbul/python_book
/lists.py
2,387
4.53125
5
simple_list = [1,2,3] print "Simple List",simple_list hetero_list = [1,"Helo",[100,200,300]]# can containheterogenous values print "Original List",hetero_list print "Type of object hetero_list",type(hetero_list) # type of object, shows its fundamental data type, for e.g., here it is LIST print "Item at index 0 ...
a860e94cbf066f0b8490329ce4c2bc4d4ec0a3d7
subbul/python_book
/dictionary.py
1,843
4.03125
4
list = [] dictionary = {} # list[0]='hello'// not allowed dictionary[0]='hello' #allowed dictionary["two"]= 2 dictionary["pi"]= 3.14 # literal use of python dictionary english_to_french = {} english_to_french['red'] = 'rouge' english_to_french['blue'] = 'bleu' english_to_french = {'red':'rouge','blue':'bleu','gree...
84abdd28ee4e617cb1c0ffff2fedf7c0e9b1a543
krylov-as/python-project-lvl1
/brain_games/scripts/brain_prime.py
534
3.6875
4
#!/usr/bin/env python3 """Start game brain-prime.""" import brain_games.cli as cli import brain_games.is_prime as is_prime def main(): """Ask name user. Start Brain Games - brain-prime.""" print('Welcome to the Brain Games!') name = cli.welcome_user() print('Answer "yes" if the number is prime. Other...
e2214418b67873b50836766a94f3c3fb2108e683
krylov-as/python-project-lvl1
/brain_games/scripts/brain_calc.py
498
3.546875
4
#!/usr/bin/env python3 """Start game brain-calc.""" import brain_games.cli as cli import brain_games.calc as calc def main(): """Ask name user. Start Brain Games - brain-calc.""" print('Welcome to the Brain Games!') name = cli.welcome_user() print('What is the result of the expression?') check = ...
6ee270b6763c17cce3b67a00e2e5c3f72fd28da8
rkumar2468/AI
/Project-05/ClickStream/Tree.py
1,426
3.625
4
__author__ = 'sri' class Node: #This class represents the tree data structure def __init__(self, val): self.value = val self.children = [] self.distribution = 0 self.parent = None def addDist(self, dist): self.distribution = dist def...
626bcc62f786c5cfb15559748a7cd7005d3e4a01
Josh-Cruz/python-strings-and-list-prac
/PYthon_Dict_basics.py
335
3.796875
4
josh_C = { "name": "Josh", "age": 30, "country": "Murica", "fav_lan": "Python" } def print_info(dict): print "My name is", dict["name"] print "My age is", dict["age"] print "My country of origin is", dict["country"] print "My favorite language to code in is", dict["fav_lan"] print(prin...
5f717d310289edd62d65b001a0f4feb7bd110738
Soumithroy/Internwork
/Soumith.py
1,999
4
4
import time from datetime import datetime, date, time, timedelta import ast def MissingDates(thisdict): #creating list of keys and values keylist = list() valuelist=list() #creating updated list of missing keys and values upkey=list() upvalue=list() #converting keys to d...
dcf9e902db1b5960e4a839f65b6d7679845a9b04
pedrohenrique-hash/Astropython
/Astro.py
366
3.8125
4
x = [2, 6, 8, 9, 10, 11, 12, 13, 14, 15] def median(v): n = len(v) sorted_v = sorted(v) midpoint = n // 2 if n % 2 == 1: return sorted_v[midpoint] else: lo = midpoint - 1 hi = midpoint return (sorted_v[lo] + sorted_v[hi]) / 2 #5 inicio das execuções ...
4ec3c682ef42afd9867983fe58b30c7a2eba70b1
NicolasGomez97/Cientifico-Datos-ISPC
/Programacion-I/13vaSemana/ejercicio9.py
359
3.734375
4
def dicMaterias(): d = {} while True: m = str(input("Ingrese Materia: ")) n = float(input("Ingrese Nota que sacaste: ")) d[m]=n i = str(input('Quiere Seguir ingresando Materias y Notas: \n')) if i == 'no': break for i,y in list(d.items()): if y >= ...
46d71236db28466463bff4f17f6845d862351cbc
jakiiii/Cryptography-with-Python
/CryptographyUsingPython/CeaserCipher/brute_force.py
483
3.6875
4
#!/usr/bin/env python3 message = 'ABCH HKHEL KHJNK DFGAS OFSX' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' for key in range(len(LETTERS)): translated = '' for symbol in message: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) transl...
0ca12599d692b0f7a46966c6603f5b78334df63f
XxTyaftioNxX/LyricalBot
/graph.py
1,684
3.5625
4
#Markov Chain Representation import random #define the graph in terms of vertices class Vertex: def __init__(self, value): self.value = value self.adjacent = {} #nodes that have edge to this vertex self.neighbours = [] self.neighbour_weights = [] def add_edge_to(self, vert...
b1cf4a3e46754ba2a54f0a24699766d18cb7ed35
PedroExt/Mis-Proyectos-Con-Python
/WeekOneHomeWork/Exercise5.py
319
3.59375
4
C=float(input('Ingrese valor de compra:')) n=float(input('Ingrese el nro de cuotas: ')) i=float(input('Ingrese la tasa de interes: ')) VC= C*(i*((1+i)**n)/((1+i)**n-1)) montoTotalIntereses=VC*n-C print('El valor de la cuota es : %.2f'%VC,'soles.') print('Monto total de intereses es: %.2f'%montoTotalIntereses,'soles.')
71c37a7257ee0cdcc82fa4bf62370f89ab5a1a48
nitayke/Rubiks-Cube
/hungary_client.py
5,745
3.5625
4
import socket import copy UP, LEFT, FRONT, RIGHT, BACK, DOWN = range(6) dic = {'U': UP, 'D':DOWN, 'L':LEFT, 'F':FRONT, 'R':RIGHT, 'B':BACK} class Cube: def __init__(self, cube): self.cube = [] if isinstance(cube, list): self.cube = copy.deepcopy(cube) else: for i in...
cba688a4c6ad9f743c93ccf4b40c14fec169f08d
aesdeef/advent-of-code-2020
/day_16/day_16_ticket_translation.py
3,376
3.796875
4
import re from math import prod def parse_input(): """ Parses the input and returns a dict of rules and a list of tickets, starting with your ticket """ rules = {} tickets = [] with open("input_16.txt") as f: for line in f: rule_pattern = r"^([a-z ]+): ([0-9]+)-([0-9]+...
bf156e7b213f6983b47792c94c842dd9bcd7c7ee
aesdeef/advent-of-code-2020
/day_17/part_1.py
1,315
4.03125
4
from functools import lru_cache def parse_input(): """ Parses the input and returns a set of cubes """ cubes = set() with open("input_17.txt") as f: for y, line in enumerate(f): for x, char in enumerate(line): if char == "#": cubes.add((x, y...
a7b576bf5c4fca869c2d238dccce509abd244e69
aesdeef/advent-of-code-2020
/day_12/ship_part_1.py
2,539
4.0625
4
class Ship: def __init__(self): self.x = 0 # east self.y = 0 # north self.direction = "E" self.operations = { "N": self.north, "S": self.south, "E": self.east, "W": self.west, "L": self.turn_left, "R": self.tu...
9774dd4f758bd0b7a97c40acc61cba5a98991d5d
aesdeef/advent-of-code-2020
/day_14/part_2.py
1,029
3.640625
4
def write_to_mem(target, number, mask, mem): """ Writes the given value to all applicable memory addresses """ target = f"{target:036b}" addresses = [""] for t, m in zip(target, mask): if m == "0": addresses = [address + t for address in addresses] elif m == "1": ...
f3bcc1f64a92fa0b2886f77bee03df5996ee9fdd
Edceebee/Python_stuff
/utils.py
280
4.0625
4
def add(digit1: int, digit2: int) -> int: """ a function that adds two numbers""" digit3 = digit1 + digit2 return digit3 def multiply(digit1: int, digit2: int) -> int: """a function that can multiply two numbers""" digit3 = digit1 * digit2 return digit3
4a74e71bc3869350e6e7802404a120fae1ecc304
ryazadd/Algorithms
/сортировка слиянием.py
1,015
4.03125
4
def merge(array, left_index, middle, right_index ): left_copy = array[left_index:middle] right_copy = array[middle:right_index] l = 0 r = 0 k = left_index while l < len(left_copy) and r < len(right_copy): if left_copy[l] <= right_copy[r]: array[k] = left_copy[l] ...
830ac9b40a729f587080b407c1069d7356a9598d
ryazadd/Algorithms
/working_sort_Mihail.py
844
3.890625
4
def merge(arr: list, left: int, mid: int, right: int) -> list: L, R = arr[left:mid], arr[mid:right] N, M = len(L), len(R) i = j = 0 k = left while i < N and j < M: if L[i] <= R[j]: arr[k] = L[i] i += 1 k += 1 else: arr[k] = R[j] ...
1d14b8695c938bed324dc13fee35b1e13d5d334b
chelberserker/mipt_cs_on_python
/lab 7/exA.py
181
3.703125
4
import numpy as np import matplotlib.pyplot as plt def f(x): return x*x-6-x x=np.arange(-10,10,0.01) plt.plot(x, f(x)) for i in x: if -0.01 <= f(i) <= 0.01: print(i) plt.show()
26b569140d5da48f061577958fe48a553741d8ca
evelynnenguyen/HackerrankSolutions
/interview-preparation-kit/dictionaries-and-hashmaps/count-triplets.py
533
3.59375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countTriplets function below. def countTriplets(arr, r, n): t = 0 r = float(r) return t if __name__ == '__main__': k = int(input()) for i in range(k): nr = input().rstrip().split() n = int(nr[0...
9d05234b70c705950a9ff2a5640107b9dde9e092
yangxi5501630/pythonProject
/study/study/re/3_re扩展.py
2,486
3.78125
4
import re #字符串切割 str = "abc123efg456xyz" print(str.split("123")) #不支持正则 str1 = "abc123efg456xyz" print(re.split("\d+",str1)) #可以随意切割 str2 = "hello world zhangsan" print(re.split('\s+', str2)) print(re.split('\s+', str2, 1)) ''' re.finditer函数 原型:finditer(pattern, string, flags=0) 参数: patter: 匹配的正则表达式 string: 要匹配...
3a7fad6b82f2dc1f6065587d1745f67c64b79597
yangxi5501630/pythonProject
/study/study/16_字典.py
1,386
4
4
''' 字典使用:key:value进行数据存储,查找速度极快 注意:字典是无序的,也就是元素位置顺序不固定,用{}扩起来 key特点: 1.字典中的key必须是唯一的 2.key必须是不可变对象,字符串,整数等都是不可变的,可以作为key 3.列表list是可变,不能作为key #和list比较 #1、查找和插入的速度极快,不会随着key-value的增加而变慢 #2、需要占用大量的内存,内存浪费多 #list #1、查找和插入的速度随着数据量的增多而减慢 #2、占用空间小,浪费内存少 ''' #字典描述人的名字和年龄 dict1 = {"zhangsan":22, "lisi":23, "wanger":21} prin...
1bb058c929eb776f52deab7486bcb65c71148d58
yangxi5501630/pythonProject
/study/study/15_元组.py
1,470
4.1875
4
''' tuple下元组本质就是一个有序集合 格式:元组名 = (元组元素1, 元组元素2, ……, 元组元素n) 特点: 1.与列表类似 2.用() 3.一旦初始化就不能修改,这个和字符串一样 ''' #创建空元组 tuple1 = () print(tuple1) #创建带元素的元组 tuple2 = (1,2,"tarena", True) print(tuple2) #定义只有一个元素的元组,记得后面带分割符, tuple3 = (1,) print(tuple3) print(type(tuple3)) #访问元组成员 tuple4 = (1,2,3,4) index = 0 for member in tuple...
17ac35fbdba7dcf0c9d5438b469c9510c46e6b55
yangxi5501630/pythonProject
/study/study/线程/8_线程通信.py
450
3.5
4
import threading, time #事件对象 event = threading.Event() def run(): for i in range(5): # 等待事件出发 print("子进程 start: %d" % (i)) event.wait() # 重置 event.clear() print("子进程 end: %d" % (i)) t = threading.Thread(target=run) t.start() print("主线程开始.") for i in range(5): ...
6a8aa8ce16427dab54ddc650747a5fcb306b86ba
twilliams9397/eng89_python_oop
/python_functions.py
897
4.375
4
# creating a function # syntax def name_of_function(inputs) is used to declare a function # def greeting(): # print("Welcome on board, enjoy your trip!") # # pass can be used to skip without any errors # # greeting() # function must be called to give output # # def greeting(): # return "Welcome on board, enjoy...
7d5593eb3b395dd9b27f75137a1d2c2cd3e56ea7
kvalv/nonogram_solver
/a_star.py
5,795
3.8125
4
import time from abc import ABC, abstractmethod from node import Node class A_Star(ABC): def __init__(self, heuristic_fun, window=None, as_dfs=False): """ heuristic_fun: Node -> float, a function that estimates the remaining length until reaching goal node. as_dfs: Boolean, i...
77643962496f439389d3d55c41df0797d3ed65f3
SimonIyamu/2d-Convex-Hull
/src/incremental/incremental.py
3,781
3.71875
4
''' Find the convex hull of random points using an incremental algorithm ''' import matplotlib.pyplot as plt import numpy as np # import Point.py class from Point import Point # Returns true if point p is left of the line ab def isLeftOf(p,a,b): return (np.sign((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)...
5dfec88ae06aee495998076d0e80777c1e9b408b
Carr1996/Python_file
/Related_exercises/三级菜单.py
2,055
3.703125
4
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, ...
7ccc7606168c9156ef0a2590792e8114cc3d7af1
daviddahl/altcoin-autosell
/exchange_api.py
1,537
3.609375
4
# An exception that any methods in exchange may raise. class ExchangeException(Exception): def __init__(self, exception): message = '[%s] %s' % (type(exception).__name__, exception) Exception.__init__(self, message) # An available market. class Market(object): source_currency_id = None tar...
2dc4e9e0b197084b6c76ebffea23fa75de884849
JonBanes/Happy-Save-The-Bunny-Game
/random_walk.py
619
3.671875
4
import random def random_walk(step, moveset): """ Returns tuple in random 'step' direction of moveset list (square grid clockwise 0 == stay still) """ directions = [(0,0), (0,-1), (1,-1), (1,0), (1,1), (0,1), ...
23b5ab72527d9f6b9469c34865d8e3ed6541e7bd
bnathasingh/recursion
/lab07.py
7,075
4.0625
4
""" A module with several recursive functions YOUR NAME AND NETID HERE THE DATE COMPLETED HERE """ # IMPLEMENT ALL OF THESE FUNCTIONS def sum_list(thelist): """ Returns the sum of the integers in list l. Example: sum_list([34]) is 34 Example: sum_list([7,34,1,2,2]) is 46 Parameter thel...
df1b44df37c7360d4c68579b6076f984cb8a9acb
theexiled1/sscrypt
/sscrypt.py
4,192
3.578125
4
#!/usr/bin/env python "Instagram: @SSploit\nTwitter: @SecuritySploit\nYouTube: Blackhole Security\nGithub: BlackholeSec\n\nSSCrypt (SecSploit Encryption)\nThis Encryption uses custom mathematical algoritms to ensure the privacy of your data whether it be clandestine or merely for privacy" import random import os import...
81eb6bed5384060113082f3368ef063c99d8120a
oshkuk22/repo_2_lesson
/1.py
622
3.875
4
# 1. Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. my_list = [1, 'stroka', 3.6, [5,6],(1,2),{3,4},{'name':'S...
afe3b5d0575470ec875ac55769a7944a92e682be
stockholm44/python_study_2018
/edwith/Chapter 7/1_linear_regression/linear_regression.py
4,956
3.84375
4
# Linear regression with one variable, implemented by numpy. # 1. pyplot, pandas, numpy 로드 import matplotlib.pyplot as plt import pandas as pd import numpy as np # 2. %matplotlib inline ?? 입력 %matplotlib inline # 1) LOAD DATASET # 3. xls 데이터 불려들어오기. C:/study_2018/python_study_2018/edwith/Chapter 7/1_linear_regression...
b1c7b85d81a6a9e6840454854296ed88ee3cb97f
stockholm44/python_study_2018
/Effective_Python_Code/29.py
2,303
3.5
4
class OldResistor(object): def __init__(self,ohms): self._ohms = ohms def get_ohms(self): return self._ohms def set_ohms(self, ohms): self._ohms = ohms r0 = OldResistor(50e3) print('Before: %5r' % r0.get_ohms()) r0.set_ohms(10e3) print('After: %5r' % r0.get_ohms()) r0.set_ohms(r0...
013b2ac2244f256970950dc1cc7cdcae25f5371d
stockholm44/python_study_2018
/wikidocs/06-2.py
737
4.15625
4
# 06-2 3의 배수와 5의 배수를 1-1000사이에 더해주는거. 아니다. 그냥 class로 n을 받자. class Times: def __init__(self, n): self.n = n def three_five_times(self): sum = 0 # return sum = sum + i for i in range(1, self.n) if i % 3 ==0 or i % 5 == 0] # how can i make functional sum of for loop. for i i...
1e0667bd5203e872f1d64f6273d4a124e0617a5e
stockholm44/python_study_2018
/wikidocs/05-1_클래스.py
1,824
3.90625
4
# wikidocs #1 class Calculator: def __init__(self): self.value = 0 def add(self, val): # --> self 넣어야함. self.value += val cal = Calculator() cal.add(3) cal.add(4) print(cal.value) #2 class Calculator: def __init__(self, init_value): self.value = init_value def add(self, val...
73ec6e73f0d84cd6265a02419283a76c05491c59
Cattleman/Feedforward
/nn.py
7,259
3.96875
4
"""Functions and classes for training feedforward neural networks.""" import math import random import numpy as np import scipy.optimize as optim class FeedforwardNN: """A simple feedforward neural network class.""" def __init__(self, sizes, seed=0): self.sizes = list(sizes) self.w, self.b ...
c5910f1116ccfb97578f5c4d0f3f65023e3be1ad
leocjj/0123
/Machine Learning/0_Copilot/test02.py
342
4.21875
4
def calculate_fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return calculate_fibonacci(n-1) + calculate_fibonacci(n-2) def main(): n = int(input("Enter the number of terms: ")) for i in range(n): print(calculate_fibonacci(i), end=" ") if __name__ == ...
071bbc12b2d818a217e5eb364da33d022b1166a7
leocjj/0123
/Machine Learning/ZZ_Census/backup/25-one_hot_decode.py
983
3.6875
4
#!/usr/bin/env python3 """ 0x01. Classification """ import numpy as np def one_hot_decode(one_hot): """ Function that converts a one-hot matrix into a vector of labels. :param one_hot: is a one-hot encoded numpy.ndarray with shape (classes, m) classes is the maximum number of classes m is ...
2b32d798a175be4fbc682ca9b737c5d1231ff989
leocjj/0123
/Python/python_dsa-master/stack/postfix_eval.py
730
4.1875
4
#!/usr/bin/python3 """ Evaluate a postfix string """ from stack import Stack def postfix_eval(string): # Evaluate a postfix string operands = Stack() tokens = string.split() for token in tokens: if token.isdigit(): operands.push(int(token)) else: op2 = operands....
27c6ec9e71d1d1cdd87ae03180937f2d798db4b2
leocjj/0123
/Python/python_dsa-master/recursion/int_to_string.py
393
4.125
4
#!/usr/bin/python3 """ Convert an integer to a string """ def int_to_string(n, base): # Convert an integer to a string convert_string = '0123456789ABCDEF' if n < base: return convert_string[n] else: return int_to_string(n // base, base) + convert_string[n % base] if __name__ == '__mai...
059bfba1640d2d348a08d6764c41c0fc6951fa64
leocjj/0123
/Python/python_dsa-master/search/selection.py
528
4
4
#!/usr/bin/python3 # Implement selection sort # O(n^2) def selection_sort(my_list): # Implement selection sort for passes in range(len(my_list) - 1, 0, -1): pos_max = 0 for i in range(1, passes + 1): if my_list[i] > my_list[pos_max]: pos_max = i my_list[pass...
35eb4eddbc01e1c926e84c1a7d5f5467f4365746
leocjj/0123
/Python/python_dsa-master/recursion/palindrome.py
737
4.21875
4
#!/usr/bin/python3 """ Check if a string is a palindrome """ def remove_white(s): # Remove characters that are not letters new = '' for ch in s: if ord(ch) >= ord('a') and ord(ch) <= ord('z'): new += ch return new def palindrome(s): # Check if a string is a palindrome if ...
30119f22b0adfe7d39baff1ecae0a1fe9a8ffea7
leocjj/0123
/Machine Learning/ZZ_Census/backup/24-one_hot_encode.py
820
3.65625
4
#!/usr/bin/env python3 """ 0x01. Classification """ import numpy as np def one_hot_encode(Y, classes): """ Function that converts a numeric label vector into a one-hot matrix. :param Y: is a np.ndarray with shape (m,) containing numeric class labels. :param classes: is the maximum number of classes fo...
e81c76e31dd827790d6b98e739763201cfc618ab
tlepage/Academic
/Python/longest_repetition.py
1,121
4.21875
4
__author__ = 'tomlepage' # Define a procedure, longest_repetition, that takes as input a # list, and returns the element in the list that has the most # consecutive repetitions. If there are multiple elements that # have the same number of longest repetitions, the result should # be the one that appears first. If the i...