blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
750588e229944a97676dab65285b2c9ca1aa1b38
CCM-Balderas-Pensamiento-Comp/strings
/assignments/06Palindromos/src/exercise.py
287
3.9375
4
def main(): #escribe tu código abajo de esta línea palabra = input() palabra = palabra.lower().replace(" ", "") if palabra == palabra[::-1]: print("Es un palindromo") else: print("NO es un palindromo") if __name__=='__main__': main()
e756d173809f008f2697e262f05b0580fb6073cc
antoniarubell/python-challenge
/PyBank/main.py
1,661
3.796875
4
import os import csv csvpath = os.path.join('budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #print(csvreader) csv_header = next(csvreader) #print(f"CSV Header: {csv_header}") #initialize tracker variables net_profit = 0 row_cou...
0166e63c5d757fc39c836520d32706d663a0dca4
jonathanmonreal/nltk-examples
/chapter 2/c2q17.py
926
3.734375
4
# Jonathan Monreal from __future__ import division import nltk from nltk.corpus import stopwords def freq_nonstop(text): stopword_list = stopwords.words('english') # stores the stopwords # generate the frequency distribution for non-stopwords fdist = nltk.FreqDist([word.lower() for word in text if word.is...
7f0da2d043f0fbc3b655a8d20308a9273da9cd55
jonathanmonreal/nltk-examples
/chapter 3/c3q1-17selections.py
2,164
3.984375
4
# Jonathan Monreal from textwrap import fill s = 'colorless' print '1. s = \'colorless\'' s = s[:4] + 'u' + s[4:] print 's = s[:4] + \'u\' + s[4:]' print 's: ' + s print '\n\n' print '2. \'dishes\'[:-2]: ' + 'dishes'[:-2] print '\'running\'[:-4]: ' + 'running'[:-4] print '\'nationality\'[:-5]: ' + 'nationality'[:-5]...
4116df1e66c029153097a4c38d9eef3459bd384a
uriya16/MEET-YL1
/MEET Conf/Paint program (uriya).py
3,216
3.859375
4
import turtle turtle.hideturtle() turtle.speed(0) color = "white" shape = "square" size = 30 def box(x,y): turtle.penup() turtle.goto(x,y) turtle.pendown() turtle.goto(x,y+50) turtle.goto(x+50,y+50) turtle.goto(x+50,y) turtle.goto(x,y) turtle.penup() def color_box(x,y,color): tur...
063670bffdfa25544a44ab6d3e1c80c317579673
AlexandreInsua/ExerciciosPython
/exercicios_parte07/exercicio05.py
1,098
4
4
# 5) Realiza una función llamada agregar_una_vez() que reciba una lista y un elemento. # La función debe añadir el elemento al final de la lista con la condición de # no repetir ningún elemento. # Además si este elemento ya se encuentra en la lista se debe invocar un error de tipo # ValueError que debes capturar y ...
34f8bc7975b9905230efab2ff7f143d26fe0ecda
AlexandreInsua/ExerciciosPython
/exercicios_parte03/exercicio06.py
1,355
4.375
4
# 6) Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente: # Todos los números del 0 al 10 [0, 1, 2, ..., 10] # Todos los números del -10 al 0 [-10, -9, -8, ..., 0] # Todos los números pares del 0 al 20 [0, 2, 4, ..., 20] # Todos los números impares entre -20 y 0 [-19, -17,...
aa5ae68154e8d3a480bf8aba0900c88f60ce0a01
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio29.py
2,248
4.1875
4
# Ejercicio 29 # Crea un programa en python que sirva para convertir monedas. # * Primero pedirá (mediante un menú) que se indique el tipo de divisa inicial que vas a usar (ej: dólar, euro, libra, …) # * Luego pedirá un valor numérico por pantalla (float), que será la cantidad de esa divisa. # * Por último se pedirá ...
3d292e18c4200a4f2809f1c9668da62a1c54f6c4
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio02.py
281
4.125
4
# Pide constantemente numeros ata que se introduce -1. Logo mostra a súa suma. print("Suma de números (-1 para finalizar)") num = 0 acumulator = 0 while num != -1: num = float(input("Introduza un número: ")) acumulator += num print("A suma dos número é: ", acumulator)
0c341198250d0a1e02f84dfd0eae72c125abc741
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio05.py
671
3.609375
4
# Crea manualmente un fichero llamado numeros.txt # Rellena este fichero con números separados por punto y coma. # Ej:3;5;66;3;456;22;4;2;45;2;5 # Crea un programa en python que lea este fichero y eleve al cuadrado todos los números. # Y guarda el resultado en otro fichero llamado numeros2.txt file = open("number...
c892d4b1f235510f6695392342f8e6a8495fa1c5
AlexandreInsua/ExerciciosPython
/exercicios_parte01/exercicio05.py
856
4.28125
4
#5) La siguiente matriz (o lista con listas anidadas) debe cumplir una condición, # y es que en cada fila, el cuarto elemento siempre debe ser el resultado de sumar los tres primeros. # ¿Eres capaz de modificar las sumas incorrectas utilizando la técnica del slicing? #Ayuda: La función llamada sum(lista) devuelve una ...
92c9a9d6d247507651eb9be5d34d3508b6a144b5
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio23.py
262
4.375
4
# Realiza un programa en python que pida la anchura de un triángulo # y lo pinte en la pantalla (en modo consola) mediante asteriscos. anchura = int(input("inserte a anchura do lado: ")) aux = "*" for i in range(anchura): print(aux) aux = aux + "*"
d3c4297906e7eee347f7b49baa4274c37f6bba6f
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio30.py
1,367
4.34375
4
# Programa (en python) que calcule áreas de: cuadrados(en función de su lado), # rectángulos(en función de sus lados, circunferencias(en función de su radio) y triángulos # rectángulos(en función de su base y su altura). # Primero se pedirá el objeto que se va a calcular(cuadrado, rectángulo, circunferencia o triangul...
16a3b33b584b0e7eff5abdf1b40a2a0225fc43d6
AlexandreInsua/ExerciciosPython
/exercicios_repaso/exercicio07.py
1,406
3.828125
4
# Programa que le no ficheiro e crea tantos obxectos como for necesario # Enche o seu nome engader ao seu array os mensaxes que corresponda class User: def __init__ (self, name, messagesArray): self.name = name self.messagesArray = messagesArray # Métodos para realizar as operacións # Devolve se ...
43ae204a9763e02384afccea818daf81bd723606
parth3033/python-problems
/primenumbersinterval.py
183
3.921875
4
a=int(input('enter number')) count=0 for i in range(2,a//2+1): if a%i==0: count+=1 break if count==0 and a!=1: print('Number is prime',a) else: print('not prime',a)
e8db935600e4c5e04a4303df8cf686dc064615a2
parth3033/python-problems
/near10nonnegative.py
157
3.671875
4
def near_ten(num): if(num % 10 < 3 or num % 10 >=8): return True else: return False print(near_ten(12)) print(near_ten(17)) print(near_ten(19))
46fc28c4bc27a2383e1c96deb2c99b0656834d07
parth3033/python-problems
/simpleinterest.py
140
3.578125
4
p=float(input('')) r=float(input('')) t=float(input('')) SI=(p*r*t)/100 TA=SI+p print('simple interest is',SI) print('total amount is',TA)
1be6adac11649e0eb56b8c797cf663e59bf6b2f6
ANSH-SINGH-2006/C-103
/scatter.py
221
3.71875
4
import pandas as pd import plotly.express as px df=pd.read_csv("data.csv") fig=px.scatter(df, x="Population", y="Per capita", color="Country", title="Per capita income", size="Percentage", size_max=200) fig.show()
530de8ff2ed5d46e819d098591c2deb56e081623
Psuedomonas/Learn-Python-3
/Strings.py
508
4.15625
4
str1 = '''This is a multi-line string. This is the first line. This is the second line. "What's your name?," I asked. He said "Bond, James Bond." ''' str2 = 'What\'s your name?' str3 = "What's your name?" str4 = "This is the first sentence.\ This is the second sentence." str5 = '''Yubba dubba. \n The grass is greener ...
e8b37ca27deb3bc5997c06b9d840ddb5239edc63
reidpat/GeeringUp
/oop.py
809
4.125
4
# creates a class class Dog: # ALL dogs are good good = True # runs when each "Dog" (member of Class) is created def __init__ (self, name, age): self.name = name self.age = age self.fed = False # function exclusive to Dog def bark(self): print(self.name + " starts to bark!") # create a...
0b07faeed17c71745c16e7131ddcc19bca79dd7b
yeeshenhao/Web
/2011-T1 Python/yeesh_p02/yeesh_p02_q06.py
609
4.59375
5
## Filename: yeesh_p02_q06.py ## Name: Yee Shen Hao ## Description: Write a program that sorts three integers. The integers are entered from standard input and ##stored in variables num1, num2, and num3, respectively. The program sorts the numbers ##so that num1 > num2 > num3. The result is displayed as a sorted list i...
8e9e0af3946bed5ace06481213cb5d76aa0ecda3
ConradLIu14/GeekUniversityAlgorithm
/week5/m56.py
576
3.5625
4
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: res = [] intervals = sorted(intervals) curr_start = intervals[0][0] curr_end = intervals[0][1] state = 0 for i in intervals[1:]: if i[0] <= curr_end and i[1] >= curr_...
c3b4bb152fe1aac639fc8c0767a44fae9e119cb8
gusun0/data-structures
/dictionaries.py
352
4.1875
4
mydict = {"name": "max", "age": 28, "city": "New York"} print(mydict) for key, value in mydict.items(): print(key, value) ''' try: print(mydict["lname"]) except: print('error') ''' ''' mydict2 = dict(name="mary", age=27, city="boston") print(mydict2) value = mydict['name'] print(value) mydict["lastname...
f0fb6f0f65c3058673977937b9f1f4bc321aee1c
gusun0/data-structures
/comprension.py
221
3.625
4
lista = [i** 2 for i in range(1,11) if i**2 > 40] string = ['java','py','go'] lista2 = [ len(i) for i in string ] print(lista2) def elevado(n): return 2**n lista = [elevado(i) for i in range(10)] print(lista)
899470febe6449a61f140546340bfde05a301ba0
gusun0/data-structures
/tuples.py
79
3.671875
4
mytuple = ('Max', 28, 'boston') a = (1,2,3,4,5,6,7,8,9) b = a[-2:] print(b)
6d573ca86dcfe3e637f5553da397c0b5e574fce3
BasedOnEvidence/mind-games
/brain_games/games/brain_progression.py
741
3.640625
4
import random GAME_DESCRIPTION = "What number is missing " \ "in the progression?" START_MIN = 0 START_MAX = 20 INC_MIN = 1 INC_MAX = 10 PROGRESSION_LEN_MIN = 5 PROGRESSION_LEN_MAX = 10 def generate_task(): progression_len = random.randint(PROGRESSION_LEN_MIN, PROGRESSION_LEN_MAX) hidden_...
ea590202d7d0ed8a0b740b0dca7c70f8c6ffb86c
temp-name-remember-to-change-later/personal-automation
/charcount.py
802
3.796875
4
#!/usr/bin/env python3 import sys # This script takes in a file and prints out all the characters in that file along with the number of occurrences. # Numbers and letters are included in the list by default, so if they don't occur, the number of occurrences will be reported as 0. f = open(sys.argv[1], 'r') ch = {} nu...
be7ef89fc98705dec40503376edc3596f1a57d07
KevinInGit/products
/products.py
1,768
3.78125
4
# -*- coding:utf-8 -*- # 建立二维列表,即列表中一项中套着另一个列表 import os # 读取文档 def read_file(filename): products = [] with open(filename, 'r', encoding='utf-8') as f: for line in f: if '商品,价格' in line: continue # 继续 name, price = line.strip().split(',') # 用逗号作为分隔符 ...
df1a2a2633f361195c91905c9f37ed7e79d1f437
SRCWS/Soduku-solver
/Full.py
2,827
3.53125
4
import random def check_zero(source): for i in range(len(source)): for j in range(len(source[0])): if source[i][j] == 0: return (i, j) return None def valid(source, number, position): # row for i in range(len(source[0])): if source[position[0]][i] == numb...
8d53a491b5376012ea86f6da82e7eccd667c2a1d
2Clutch/briefcase
/tests/commands/new/test_input_text.py
1,829
3.796875
4
from unittest import mock def test_unvalidated_input(new_command): "If the user enters text and there's no validation, the text is returned" new_command.input = mock.MagicMock(return_value='hello') value = new_command.input_text( intro="Some introduction", variable="my variable", ...
47a0a75f1b3d4403bd273b7308905b4c7b24d4e3
edsonJordan/CodeWars
/Python/6kyu-Playing-with-digits.py
361
3.609375
4
# https://www.codewars.com/kata/5552101f47fc5178b1000050 # Example # dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1 # dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k def dig_pow(n, p): sum=0 for i in list(str(n)): sum+=int(i)**p p+=1 if sum % n == 0...
66a820d90e3225ed508337ca097b8c67c27404db
edsonJordan/CodeWars
/Python/7kyu-Array-Leaders.py
468
3.953125
4
# https://www.codewars.com/kata/array-leaders-array-series-number-3/train/python # An element is leader if it is greater than The Sum all the elements to its right side. #arrayLeaders ({1, 2, 3, 4, 0}) ==> return {4} #arrayLeaders ({16, 17, 4, 3, 5, 2}) ==> return {17, 5, 2} def array_leaders(numbers): leaderLis...
f3463a840f75c31d8f23cc0b702e8177425abbde
edsonJordan/CodeWars
/Python/6kyu-Persistent-Bugger.py
656
3.84375
4
# Write a function, persistence, that takes in a positive parameter num and # returns its multiplicative persistence, which is the number of times you # must multiply the digits in num until you reach a single digit. # For example: # persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4 #...
b7cfb41bfa69e73353eb19a905fc7478bb551ded
edsonJordan/CodeWars
/Python/6kyu-Find-the-odd-int.py
244
3.984375
4
# Given an array, find the int that appears an odd number of times. # There will always be only one integer that appears an odd number of times. def find_it(seq): seqSet=set(seq) for i in seqSet: if seq.count(i) % 2 & 1: return i
624bdcc09138dd886c86fa611a957b9c663f08b1
rensg001/test_scripts
/threads/threads.py
903
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author rsg # import threading import time class MyThread(threading.Thread): def __init__(self, func, *args, **kwargs): super(MyThread, self).__init__() self.func = func self.args = args self.kwargs = kwargs def run(self): ...
1264d54577ebd057058573cc21fcf0c4e2402b66
rensg001/test_scripts
/recursion/access_list.py
302
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author rsg # def access_list(lst): for item in lst: if isinstance(item, list): access_list(item) else: print(item) lst = [1, 1, 2, [5, 2, [8, 2, [443]]]] if __name__ == '__main__': access_list(lst)
44504ac545b145842f98e3a3d38596b9dad8530b
rensg001/test_scripts
/algorithms/quick_sort.py
703
3.828125
4
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import def quickly_sort(lst, left, right): if left > right: return l, r = left, right key = lst[left] while left < right: while left < right and lst[rig...
a26f57626165a2dec8c1ab86e68d862d6e1639f3
UgeneGorelik/Python_Advanced
/ContexManagerStudy.py
1,623
4.40625
4
from sqlite3 import connect #with means in the below example: #open file and close file when done #means with keyword means start with something #and in the end end with something with open('tst.txt') as f: pass #we declare a class that will runn using context manager type implementation class temptable: ...
21bfaa6240946b3c5ce50699240dfdacb95ee653
bullocgr/algorithms
/project/NearestNeighbor.py
4,313
3.515625
4
########################################################################################## #Final Project #Description: This is the final project where we solve for the traveling salesman problem. #We solve this problem through the use of the nearest neighbor algorithm. #Group 46: Grace Bullock, Gabriela Velazquez,...
36eb2a5195317e2affe054ef522c47c22b97d832
babushkinvladimir/mscThesisProject
/searchSequenceNumpy.py
877
3.984375
4
""" Find sequence in an array using NumPy only. Parameters ---------- arr : input 1D array seq : input 1D array Output ------ Output : 1D Array of indices in the input array that satisfy the matching of input sequence in the input array. In case of no match, an empty list is returned. """ import numpy as np d...
3ff9f21153f3611daf98415aaa621eeabe1d3ccc
Squ1cker/Repository
/homework1.py
133
3.796875
4
a=float(input()) b=float(input()) x=float(input()) import math x=(x*math.pi)/180 print(math.sqrt(a**2+b**2-2*a*b*math.cos(x)))
ac6f6d9c3b5bd418e963c63fb77e7e65ec4fddd6
lilirass/Integral_Derivative_code
/auxiliary_differentiation.py
850
4.09375
4
import Func_Analytical_Integral_Derivative def differentiate (a, func, func_params, h=0.1): """ this function will calculate the value of derivative function in one point central difference formula for numerical differentiation: f'(a) = [f(a+h) - f(a-h)]/(2h) func = function a = compute the derivative ...
8934fef224c380e421c6c8259651da3d5ea1cdc1
izzygull/RobotSim
/Controller.py
7,154
3.609375
4
""" Abstract class for a controller. """ import numpy as np import matplotlib.pyplot as plt from abc import ABC, abstractmethod from time import time, sleep from threading import Timer from matplotlib import cm class Controller(ABC): def __init__(self, world, known, pose, vel_change_max=.1, pixel_resolution=10...
5e28de8f0613ba5ae0f50dc0c019c8716e6e4e09
mdimovich/PythonCode
/Old Tutorial Code/pythonTut27 (Recursion).py
602
4.1875
4
# Recursive Functions in Python # Recursive Factorial Function def factorial(num): if num <= 1: return 1 else: result = num * factorial(num-1) return result print(factorial(4)) # 1, 1, 2, 3, 5, 8, 13 # Fibonacci Sequence: Fn = Fn-1 + Fn-2 # Where F0 = 0 and F1 = 1 def fibonacci(num)...
f891e08dcac28ac45c6412100315a0c411f29de9
mdimovich/PythonCode
/pythonTut45(Regex Part 3).py
1,242
3.71875
4
import re # Regex: Match for both cat and cats randStr = "cat cats" regex = re.compile("[cat]+s?") matches = re.findall(regex, randStr) for i in matches: print(i) # Regex: Match for doctor,doctors, and doctor's randStr2 = "doctor doctors doctor's" regex = re.compile("[doctor]+['s]*") matches = re.findall(regex, r...
e0a3095c64fd1e4fddb49f2dff25ef0b1b829e04
mdimovich/PythonCode
/Old Tutorial Code/pythonTut4.py
737
4.34375
4
#Enter Calculation: 5 * 6 # 5*6 = 30 #Store the user input of 2 numbers and the operator of choice num1, operator, num2 = input("Enter Calculation ").split() #Convert the strings into integers num1 = int(num1) num2 = int(num2) # if + then we need to provide output based on addition #Print result if operator == "+": ...
08a7e0b622e0564fe560c0f90ab3204bfa6ec795
mdimovich/PythonCode
/Old Tutorial Code/pythonTut9.py
131
3.6875
4
import random rand_num = random.randrange(1,51) i = 1 while(i != rand_num): i += 1 print("The random value is: ", rand_num)
1730623fc10aa70a47b2e1cc3fe5aa42ac08ee59
mdimovich/PythonCode
/Old Tutorial Code/pythonTut3.py
328
4.25
4
#Problem: Receive Miles and Convert To Kilometers #km = miles * 1.60934 #Enter Miles, Output 5 Miles Equals 8.04 Kilometers miles = input ("Enter Miles: ") #Convert miles to integer miles = int(miles) #Kilometer Equation kilometers = miles * 1.60934 #Data Output print("{} Miles equals {} Kilometers".format(miles, kilo...
4b75f4198103131a071f3ceb6854ca1caa957953
SanjibM99/sorting
/bubble sort.py
230
3.84375
4
def bubble(list): for i in range(len(list)-1,0,-1): for j in range(i): if list[j]>list[j+1]: list[j],list[j+1]=list[j+1],list[j] list=[23,66,1,33,2,565] bubble(list) print(list)
440c455f4b8a97cd4fe48a601ba726a041563b16
Nezbleu/AnalizadorHabitabilidadDeTemperatura
/SimulacionEdificio.py
7,683
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 14 20:35:10 2019 @author: Antonio Listas doblemente enlazadas para la simulacion de los pisos del edificio """ # Clase del piso en general, con los parametros de Conductividad Termica y Resistencia Termica class Piso(object): def __init__(self,NumPiso,Ctermi...
e1b51e7eba71365fd6013c03d25e97dd62c12104
rosannahanly/Airline_Program
/tests/atlas.py
6,199
3.734375
4
''' Created on 4 Apr 2018 @author: rosannahanly ''' from math import sin, cos, radians, asin, sqrt from classes.airport import Airport from classes.aircraft import Aircraft from classes.currencyExchange import CurrencyCode, CurrencyRate from itertools import permutations def greatcircledist(long1, lat1, long2, lat2...
6ed0a3ab8d8175a31f570d4bd71994c1c2a25ba3
t04glovern/automatingPython
/chapter09-organizing-files/fileDelete.py
575
3.765625
4
# Calling os.unlink(path) will delete the file at path. import os for filename in os.listdir('.\\file-working'): if filename.endswith('.rxt'): print(filename) ## Run above first to see what files will be affected for filename in os.listdir('.\\file-working'): if filename.endswith('.rxt'): ...
90490575993215f71854497e372152dca51729f9
alonerez/python
/ex12.py
266
3.875
4
import random def short_list(mylist): # list = [] list = [mylist[0], mylist[-1]] return list a=[] # create the list leng = random.sample(range(1, 15), 1) for i in range(leng[0]): a.append(random.randint(1, 30)) print(a) print(short_list(a))
ba1b4a55126b95ceabaf02f9832caf189e09cd23
alonerez/python
/ex11.py
300
4.0625
4
def check_divisors(my_num): divisors=[] list = range (2,my_num) for x in list : if my_num%x == 0 : divisors.append(x) return divisors num = int(input("enter a number ")) res = check_divisors(num) if not res: print ("Primal") else: print (res) # print (divisors)
e70499e70ef2ffb505795f703964c821776c0987
olivierdarchy/python_lab
/pgcd.py
1,888
3.90625
4
# Made to stay sharp in python: # # Exercice : design an algorithm to evaluate the pgcd of two natural integers # - input: a, b for a, b € N* # - output: pgcd # # by Olivier Darchy # created the 23th of September,2017 def eval_pgcd(a, b) : """ Evaluate and return the greatest comon divisor of two number. ...
83b950a500f45844a0a987682efedb677b6e6c1c
TRoboto/Maha
/maha/cleaners/functions/num2text.py
6,527
3.859375
4
""" Logic for converting numbers to text """ __all__ = [ "numbers_to_text", ] import regex as re import maha.cleaners.functions as functions from maha.constants import TEH_MARBUTA from maha.expressions import EXPRESSION_DECIMAL, EXPRESSION_INTEGER from maha.parsers.utils import convert_to_number_if_possible from ...
db94c3e5116ece588cbb1e2a4c9901daaaeb946b
simonrozsival/advent-of-code
/09/graph.py
459
3.84375
4
class Graph: def __init__(self): self.cities = [] self.distances = {} def getCitiesList(self): return self.cities def addDistance(self, a, b, dist): self.addCity(a) self.addCity(b) self.distances[a][b] = dist self.distances[b][a] = dist def addCity(self, city): if city not in self.cities: self.c...
1b2fa0d9cf48d75fd71a6403da3b15e6ecd91638
simonrozsival/advent-of-code
/12/task.py
897
3.515625
4
import re import json def sumNumbers(data): matches = re.findall(r'(-?\d+)', data, re.M|re.I) result = 0 for num in matches: result += int(num) return result def sumNumbersWithoutRed(data): data = json.loads(data) return getValue(data) def traverseArray(data): result = 0 for item in data: result += getVa...
da8376a467913fc7ed42ea1b47e455e75ebd38f4
AmbikaKoushik/One-time-Pad-Encryption
/src/freqdist.py
1,524
3.96875
4
def freqdist(length, record): #define Frequency Distribution function from keygen import keygen #Importing keygen module from keygen.py import sys #Importing sys module import random #Importing random module f1 = open(record,'a') #Opening the record.txt file in append mode f...
9b5fd62c8eb90a814b5fbdaef4cd39fad0f9f15a
g43l/introPython
/Cours Python/listes.py
423
3.984375
4
###Créer une liste >>>liste = [6,7,3,0] [6,7,3,0] ### >>>liste[2] 3 ###Insert le chiffre 0 à l'index 2 >>>liste.insert(2,0) [6,7,0,3,0] ###Insert le chiffre 8 à la >>>liste.append(8) [6,7,0,3,0,8] ###Concaténation pour ajouter au début >>>liste = [9,7,8] + liste [9,7,8,6,7,0,3,0,8] ###Classer par ordre croissant >...
b7f45e9f8718227c020c3f86b4162453fc852c5f
AdamCottrill/FishNet2DB
/unzip_files.py
1,042
3.5
4
"""Take shameless from here: https://stackoverflow.com/questions/31346790/ """ import os import zipfile ZIP_DIR = "C:/Users/COTTRILLAD/Documents/1work/ScrapBook/AOFRC-334-GEN" #ZIP_DIR = "C:/Users/COTTRILLAD/Desktop/Floppy_Disk_Project/004/LHA" for path, dir_list, file_list in os.walk(ZIP_DIR): for file_name i...
537fce7a1b9ce3530faa8ad72f5afce97970b3a3
mateuszkanabrocki/tests
/oneline.py
309
3.703125
4
with open('sample.txt', 'r', errors='ignore') as file: count = len(['sth' for line in file for letter in line if letter in 'ABCDEFGHIGKLMNOPQRSTUVWXYZ']) # lines are yield - better memory solution # count = len(['sth' for letter in file.read() if letter in 'ABCDEFGHIGKLMNOPQRSTUVWXYZ']) print(count)
b4af09a0c9b88584a03002672129ee0424867b87
Chegeek/IRIS
/RaspberryPi/DataPacket.py
4,828
3.53125
4
''' This file contains the definition of 'DataPacket' object class. A 'DataPacket' is instantiated from the transmitted bytestream from Arduino Mega. The format of the bytestream should be <numPackets>,[<packetId>,<handProximity>,<frontProximity>,<leftProximity>,<rightProximity>,<displacement>,<heading>, <numS...
34001dd7561125ed55311288b8c8b9d3a20744bd
XiaoBaoBao719/ECS32B-Project
/part1master.py
3,267
3.765625
4
import math class Package: def __init__(self, id): self.id = id self.address = "" self.office = "" self.ownerName = "" self.collected = False self.delivered = False """ @parameter id - integer value number that represents the package tracking number table...
188d389aaf9b7e311b1606e8118fc30f077c9abb
JOSETUZ-PUMAS/PYTHON
/SumaCubos.py
400
4.0625
4
print ("--intervalo de la suma de los cubos de los primeros n números--") def intervalo(): final=input("ingrese el final del intervalo") suma =0.0 final2=int(final) lista=[] print (final2) for i in range(1,final2+1): suma=suma+(i**3) lista.append(i**3) print ("lista de numeros a la potencia 3: ", lista) p...
a0bf4c570f5b38e6b3f4cdc6305076361c0f21cd
JOSETUZ-PUMAS/PYTHON
/volumenEsfera.py
149
3.75
4
def volumen(): radio=input("Ingrese el radio") radio=int(radio) volumen = (4/3)*(3.1416*(radio**3)) print ("El volumen es: ", volumen) volumen()
1381b428a282939f5f7cf84f19f805a9ba9e8961
zacksnyder-lsds/Unit3_Sprint1
/Acme/acme_report.py
1,848
3.78125
4
from acme import Product from random import randint, sample, uniform adjective = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] noun = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(num_products=30): ''' Function to randomly generate a given number of products ''' ...
d04f533a1fb66296b49b49c8ab2232293fb428f1
AlexRatnikov/Python_lessons_basic
/lesson04/home_work/hw04_easy.py
1,556
3.84375
4
#coding: utf-8 # Все задачи текущего блока решите с помощью генераторов списков! # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, 0] import random list1 = [random.randint(-10, 10)...
fb5bb2569ab5d12d04be086462e95f37511f33d0
WF-Guo/PythonCode
/各算法的比较/SA_x_y_z.py
5,282
3.828125
4
""" 模拟退火算法: 测试函数在objectFunction里 """ import numpy as np import time from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt class SimulatedAnnealingBase(): """ Parameters ---------------- func : function The func you want to do optimal n_dim : int number of variables...
9415f10ad809d8e045ea6b1696ab027cbb6b6267
galletsophie/dsti-hadoop-spark
/map.py
644
3.71875
4
#!/usr/bin/env python #If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH import sys #input comes from STDIN (standard input) for line in sys.stdin: #remove leading and trailing whitespace line = line.strip() ...
00e1bd5744196a8332636e9ac7a9548cd5376d01
qingshuiqianhe/-blog
/总结/用python写网络爬虫/.idea/编写第一个网络爬虫/一、网络爬虫简介/1.4.4链接爬虫/解析robots.txt.py
902
3.5625
4
'''解析robots.txt >>>import robotparser >>>rp = robotparser.RobotFileParser() >>>rp.set_url('http://example.webscraping.com/robots.txt') >>>rp.read()''' # 将该功能集成到爬虫中,在crawl循环添加该检查 import urlparse def link_crawler(seed_url,link_regex): crawl_queue = [seed_url] seen = set(crawl_queue) while crawl_queue: url = c...
6f1cdd37615c39c214a28e67b655f970e2c7fd1c
qingshuiqianhe/-blog
/总结/小技巧/列表字典操作/liebiao.py
1,897
3.90625
4
'''列表的操作总结''' #1,全数字列表进行排列 1.sort() 由小到大 2.reverse(),倒序排列 3.sorted 创建列表副本进行有大到小排序 a = [3,2,1] a.sort() #sort 对列表元素进行排列 max = a[len(a)-1] min = a[0] a.reverse() c = sorted(a) print(c) # 2添加元素 1:append,在最后一个位置添加,2:extend:逐个添加列表c的元素加入列表a末尾,3.indsert(i,num ) 在制定位置添加某个元素 a=[] for i in range(10,1,-1): a.append(i) ...
664f84761a1c6078535a668f28fcea43ed43a37c
kpprd/ipython-clone
/getchar.py
1,700
4.03125
4
#!/usr/bin/python2 # encoding: utf-8 """Small script for controlling charactor input in more detail. NOTE: This script was provided by the instructors for the course INF3331 To explore what key results in what output, use it interactively. For example: $ ./getchar.py prompt:å repr:"\xc3\xa5" Can also be...
86d826f629c094006175eac27441a97b1332676b
marcosag90/DesignPatterns
/Observer/Observer.py
1,286
3.546875
4
from abc import ABC, abstractmethod class Topic(object): def __init__(self): self.subscribers = [] def register(self, observer): self.subscribers.append(observer) def unregister(self, observer): self.subscribers.remove(observer) def NotifyObservers(self): for susbscriber...
91287653e591395724c9eca213e610084a707ed8
alazalazalaz/demo-python
/base/sys_method/exception.py
652
3.828125
4
# 关于异常处理 # python和php类似一般有两种错误,一个是语法错误,一个是异常 # 语法错误很容易检测,编译的时候会失败并提示 # 异常就是运行的时候会报出来,并且中断程序 # print(10/0) 这样会触发一个异常() # 解决方案 try: print(10/0) except ZeroDivisionError: # 注意这个ZeroDivisionError,此方法中只能用这个error,如果用其他error会捕获不到 print("ZeroDivisionError捕获了除数不能为0的情况") # try: # print(10/0) # except NameError: ...
16de1f595fce3b9cba72da594f3a5897bff11728
twistby/python-project-lvl1
/brain_games/games/brain_gcd.py
827
3.96875
4
"""Brain gcd module.""" import random DESCRIPTION = 'Find the greatest common divisor of given numbers.' MIN_FIRST_NUMBER = 1 MAX_FIRST_NUMBER = 1000 MIN_SECOND_NUMBER = 1 MAX_SECOND_NUMBER = 100 def get_question_and_answer(): """Return GCD of two numbers.""" first_number = random.randint(MIN_FIRST_NUMBER, M...
2e5ceb56e8676d0f8bf56e01a767e68fe152405f
luizfernandorg/forkinrio
/python/day2/livro-parte-3/2.py
1,012
3.71875
4
#coding: utf-8 """ Setup >>> from itertools import islice >>> pp = lambda g, c: list(islice(g,c)) Prime generator expression >>> pp(gx, 19) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] """ # Generator Expression from itertools import count gx = (x for x in count() if is_prime(x)) ...
f42feeb2a735e61fa5a4717237dd04cc268f9e80
mre/gamebox
/uno.py
3,237
3.796875
4
# TODO: # Make a named tuple out of cards from random import shuffle class Player(object): def __init__(self, name, cards): self.name = str(name) self.cards = cards def pretty(self, card): card_color, card_value = card return card_color.capitalize() + " " + str(card_value).capitalize() def pri...
02d7524f62e2ad6bef2307277118e098efb2e7b3
devSubho51347/Python-Ds-Algo-Problems
/Linked list/Remove duplicates from sorted linked list.py
1,065
3.90625
4
class Node: def __init__(self,data): self.data = data self.next = None def create_linked_list(arr): head = None tail = None for ele in arr: newNode = Node(ele) if head is None: head = newNode tail = newNode else: tail.next...
b3615f0ee13be355d2e709a0ee9e011b9038b406
devSubho51347/Python-Ds-Algo-Problems
/Sum of n natural nos using recursion.py
153
3.96875
4
def sum(n): if n == 1: return 1 summation = n + sum(n-1) return summation x = int(input()) print("Sum of n natural nos is", sum(x))
5956dee8f7bd60bfcddd0f74bd487ae132c70547
devSubho51347/Python-Ds-Algo-Problems
/Linked list/Segrate even and odd nodes in a linked list.py
1,884
4.125
4
## Creation of a node of linked list class Node: def __init__(self,data): self.data = data self.next = None # Method to create the linked list def create_linked_list(arr): head = None tail = None for ele in arr: newNode = Node(ele) if head is None: head =...
9932e9f1c44f4d875399955f2257acca9c78404b
devSubho51347/Python-Ds-Algo-Problems
/Binary Tree/check if binary tree is balanced.py
2,306
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import queue class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None # Method to check whether Binary tree is balanced or not def checkBalancedBinaryTree(root,height = 0): if root is None: ...
aeae7d9948ca357f80b8c955e078b3f8dd227677
devSubho51347/Python-Ds-Algo-Problems
/Linked list/AppendLastNToFirst.py
1,644
4.1875
4
# Description ''' You have been given a singly linked list of integer along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. ''' # Solved question using two pointer approach def AppendLastToFirst(head,n): ptr1 = h...
c98a67c653cf3adfad0b2d1274a33f396fc6c8ac
mallikasinha/python-basic-programs
/stringFormatting.py
926
4.21875
4
age = 24 print("My age is" + str(age) + "years")#str convert integer to string print("My age is {0} year".format(age)) #replacement field print("there are {0} days in {1} ,{2} {3} {4}".format(31, "jan", "feb", "march", "may")) print("""Jan: {2} Feb: {0} March: {2} April: {1} June: {1} July: {2} August: {2...
b70b16a78a2137a930d93cb78ac022ac220c4107
mallikasinha/python-basic-programs
/ifProgramFlow.py
752
4.03125
4
# name = input("please enter your name:") # age = int(input("how old are you, {0}?".format(name))) # print ("oh!! so you are {0}".format(age)) # # if age >=18: # print("you are old enough to vote") # print("please put an X in the box") # else: # print("you cant vote.please come in {0} years".format...
d88926237a6b9aadabe227420130ae0a8c617524
Code-Institute-Solutions/directory-based
/03-test_driven_development/asserts.py
441
4.28125
4
def is_even(number): return number % 2 == 0 def even_numbers_of_evens(numbers): evens = sum([1 for n in numbers if is_even(n)]) return False if evens == 0 else is_even(evens) assert even_numbers_of_evens([]) == False, "No numbers" assert even_numbers_of_evens([2, 4]) == True, "Two even numbers" assert ev...
bc8415b95bbd94b0e881020a8422cb272bc2fbc4
nthomson/lolreader
/lolreader/utils.py
314
3.921875
4
def camelcase_to_pythonic(word): char_list = list(word) for counter, c in enumerate(char_list): if(c.isupper()): char_list.insert(counter, '_') if char_list[counter + 1]: char_list[counter + 1] = char_list[counter + 1].lower() return ''.join(char_list)
014371c4a04e6068041efd9f771d424ec0fac017
ChowHome/origin
/python/arr.py
163
3.65625
4
#!/usr/bin/python word = raw_input('User:') arr = [] while word <> 'exit': arr.append(word) word = raw_input('User:') while arr: print arr.pop(0)
c57a3e52a1ec6919cfc4231defe7ea97aa623f84
ParkSanggi/design_patterns_with_python
/singleton/lazy_instantiation.py
684
3.640625
4
class Singleton: __instance = None def __init__(self): if not Singleton.__instance: print("__init__ method called") else: print("Instance already created:", self.get__instance()) @classmethod def get__instance(cls): # 모듈이 임포트 될 때 바로 객체가 필요하지 않은 경우 객체를 생성...
0fd13f2fd4725ae001c1c750e29101aef1228b09
kanglicheng/tutoring_work
/prime_print.py
620
3.953125
4
def ask(): start = int(raw_input("Give me a starting number")) stop = int(raw_input("Give me an ending number")) return[start,stop] #YOU CAN NEVER HAVE A FUNCTION CALLED AS ARGUMENT- ASK IS A NUMBER VALUE BELOW! def prime_print(): array = ask() prime_array = [] i = array[0] j = array[1] while i < (j+1): ...
c077ba5f02eadce096e2a608ad9986b73e7b8568
justin-hackin/play-svg
/playsvg/gradient.py
4,319
3.546875
4
""" #FIXME: gradient lxml conversion CODE INVALID DO NOT USE """ from document import * """Classes for building gradients""" class GradientStop: """a gradient stop that stores color, offset, and opacity""" def __init__(self, color, offset, opacity=1.0): self.color = color self.offset = offset ...
cc58a323e13fa9fcac513251acb3a92e5d828f75
justin-hackin/play-svg
/build/lib.linux-x86_64-2.7/playsvg/element.py
6,888
3.765625
4
""" Functions for constructing SVG elements to be added to a document See `SVG specifications <http://www.w3.org/TR/SVG/>`_ for more information how nodes are structured, including the optional attributes and styles. See `lxml documentation <http://lxml.de/tutorial.html>`_ for clarification on etree usage The elemen...
63ccfbcfcd1ddc696085e6063fff11721f351a5d
dustymeyers/Raspberry-Pi-OOP-Course
/adventure_game/main.py
812
3.59375
4
from room import Room # Room Instances kitchen = Room('Kitchen') kitchen.set_description('A dank and dirty place, buzzing with flies.') ballroom = Room('Ballroom') ballroom.set_description('A large room with ornate golden decorations on each wall.') dining_hall = Room('Dining Hall') dining_hall.set_description('A va...
559618c6a03eb8547eed2891b4ac7ed038e92b3b
KhadijaAbbasi/python-program-to-take-input-from-user-and-add-into-tuple
/tuple.py
244
4.15625
4
tuple_items = () total_items = int(input("Enter the total number of items: ")) for i in range(total_items): user_input = int(input("Enter a number: ")) tuple_items += (user_input,) print(f"Items added to tuple are {tuple_items}")
8e02a557302feb0431ac8a54d816d0afe7f59648
zingsman/python
/ERROR/raise.py
574
3.78125
4
#!/bin/python #Filename: raise.py class ShortException(Exception): ''' A user-defined exception class.''' def __init__(self,length,atleast): Exception.__init__(self) self.length=length self.atleast=atleast try: s=raw_input('Enther something-->') if len(s) < 3 : raise ShortException(len(s),3) # Other work ...
cb6ec3c2e7d8e54fbd63832ace33e4be895ffbd4
zingsman/python
/base/func_default_param.py
542
3.5
4
#/bin/python #filename func_defalt_param.py #只有在形参表末尾的那些参数可以有默认参数值,即你不能在声明函数形参的时候,先声明有 #默认值的形参而后声明没有默认值的形参。 #这是因为赋给形参的值是根据位置而赋值的。例如,def func(a, b=5)是有效的,但是def func #(a=5, b)是 无效 的。 # def sayhello(a='word',b=5): print a*b sayhello() def sayone(a,b=5): print a*b sayone('hello word ') #def sayone(a,b=5) 这样是错误的。详情请看上面...
fa47c0a5c961816e68bc87080d5eba2a32ebe2d1
zingsman/python
/爬虫/test,py.py
229
3.515625
4
#!usr/bin/python header = '车|次 车|站 时|间 历|时 一等 二等 高级软卧 软卧 硬卧 硬座 无座'.split() b = '车|次 车|站 时|间 历|时'.split() print(header) print(b) for a in b: c=a.split("|") print(c)
bef2030e9d5bf64f7b3291e4c5770228c9af2adc
esoergel/dimagi
/set_combination.py
836
4
4
def get_combinations(word_lists): """ generates a list of lists of possible combinations by recursing on the remaining lists (yo dawg...). """ if len(word_lists) == 1: return [ [word] for word in word_lists[0] ] combos = [] sub_combos = get_combinations(word_lists[1:]) for word...
9abcb728c7dbaba2f10609b1bba388c1bbd02ead
monkrobot/test_project
/Coursera/MFTI_Timofei_Hirianov_PythonCourse/Permutations.py
649
3.75
4
#def generate_number(N:int, M:int, prefix=None): # prefix = prefix or [] # if M == 0: # print(prefix) # return # # for i in range(N): # #print("prefix: ", prefix) # prefix.append(i) # generate_number(N, M-1, prefix) # prefix.pop() # # #generate_number(4,4) def genera...
0715a4448d86f2eb1f7e561e6b828d0748870345
monkrobot/test_project
/Coursera/python videocourse/game paper-rock-scissors/paper-rock-scissors.py
1,004
3.953125
4
import random items = ['paper', 'rock', 'scissors'] def user_choice_func(): user_choice_text = input('Your choice: ') try: user_choice = items.index(user_choice_text) return user_choice except: print('No such element, try again') user_choice_func() def computer_choice_func...