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
1306989599a08f82e68c2f839a8af4e2a299150a
NaheedRayan/Python_programmes
/sudoko_version1.py
1,615
3.90625
4
mat = list() # This is a sudoko and we will solve it mat = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] ...
a02b8954439ef76b78e4d8c4e748e3375cb5880b
Ladydiana/HiraganaToRomaji
/checkers.py
385
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 @author: Culincu Diana Cristina """ import dictionary def isValidHiraganaCharacter(char): if char in dictionary.hiragana_list: return True else: return False def isValidHiraganaWord(word): for i in range(0, len(word)): if isV...
992e1f64575d07deb70d8fa1d5974bbe8993664d
LiuZechu/CS3243-project2
/sudoku/runner.py
1,708
3.703125
4
#!/usr/bin/env python2 import sys import os import subprocess import time """ HOW IT WORKS: ./runner.py <test input num> For example, typing: ./runner.py 1 Translates to executing: python CS3243_P2_Sudoku_13.py public_tests_p2_sudoku/input1.txt output1.txt """ # argv[1] represents input number of test ca...
8561df1885469fd1902784adc04ec1e91d997660
Dededede4/ecole42
/piscines/piscine_python_django/d01/ex00/var.py
611
3.703125
4
def my_var(): a = 42 b = "42" c = "quarante-deux" d = 42.0 e = True f = [42] g = {42:42} h = (42,); i = set() print("%s est de type %s" % (a, type(a))); print("%s est de type %s" % (b, type(b))); print("%s est de type %s" % (c, type(c))); print("%s est de type %s" % ...
4264d1df4df5f75610445146a82d963d1d99931c
Dededede4/ecole42
/piscines/piscine_python_django/d01/ex01/numbers.py
304
3.625
4
def displayline(line): for word in line.split(","): print(word.strip()) if __name__ == '__main__': filename = "numbers.txt" try: with open(filename, 'r') as f: for line in f: displayline(line) except IOError as e: print("Error")
b15c7f66e5d574148dc9ac92344d92440ec0744f
arossouw/study
/python/math/factorial.py
204
4.28125
4
#!/usr/bin/python # recursive function for factorial # factorial example: 4! = 4 * 3 * 2 * 1 = 24 def factorial(n): if n == 0: return 1 return n * factorial(n-1) print factorial(4)
11f84e89c9d45030cd391899a85cd44939ef6c09
BSDNix/notepad
/du.py
336
3.625
4
import os path = input() size = 0 for root, directories, files in os.walk(path, topdown=False): for name in files: print(os.path.join(root, name), end=" ") size += os.path.getsize(path) print(str(size)) for name in directories: print(os.path.join(root, name), end=" ") p...
cf1a8588cac4e15a50c5df787767194735af183c
danielrs975/simulacion
/Problema IX/main.py
9,989
3.9375
4
''' Script de simulacion para el problema 9 ''' from random import random, expovariate, uniform from math import log, sqrt from scipy import stats from collections import deque class Centro: ''' Clase que representa cada centro de trabajo ''' def __init__(self, limite=None): ''' Constru...
88b3a88016343c4d830a05d842c9fbeb7c1689c4
PinataMostGrim/hashutil
/hashutil/core.py
2,390
3.53125
4
"""Calculates hash digests for strings and files using various algorithms.""" import hashlib from pathlib import Path _SUPPORTED_ALGORITHMS = { 'blake2b', 'blake2s', 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'sha512', ...
2b1a436d81ab63509a4e51058cc2f7f01532ba17
ra2003/scripts-2
/split_spreadsheet.py
2,037
3.59375
4
import os import csv import sys import optparse def spreadsheet_length(input_filename): """Number of rows for this spreadsheet """ i = 0 for row in csv.reader(open(input_filename)): i += 1 if i > 0: # don't count header row i -= 1 return i def split_spreadsheet(input_...
8f706ad7567bac9065e6fc4d6d33178f020e770f
os2tux/adventofcode2018
/day2/day2_solution_part1.py
2,232
3.609375
4
import csv import os def retrieve_boxIDs(filepath): with open(filepath, 'r') as boxIDs: reader = csv.reader(boxIDs) file_contents = list(reader) boxID_list = [] for boxID in file_contents: boxID_list.append(boxID[0]) return boxID_list #This solution assumes that there are thr...
4c3ab64521dbad16946bce77ac7f3486a93be25f
cesarbruschetta/analise-appleStore
/analyze_store_data/utils.py
1,747
3.859375
4
""" module to utils methods """ import csv import sqlite3 REPORT_HEAD_LIST = ( "id", "track_name", "n_citacoes", "size_bytes", "price", "prime_genre", ) def parcer_file(filename): """ parcer file csv to dict """ data = [] with open(filename) as f: records = csv.DictReader...
eb75f3946dcded3863c2e6ae4f7ec07abf5e58d6
kle622/EClass
/testing/implementation/unit/Person/Student.py
2,826
3.5
4
class Student(Person): """ Make a series of tests that checks for individual errors in each method and for errors caused by sequential method calls (for the ones that operate on the same values) Testing order: __init__() > SetPermissions(), GetPermissions() > SetPresent(), IsPresent(...
cd0bff01351696cac959f4460a832581a12675b9
eolelake/AdventOfCode
/2020/9/solution.py
1,088
3.765625
4
def find_bad_num(numbers): prei = 0 i = 25 while i < len(numbers): preamble = numbers[prei:i] curr = numbers[i] found = False for x in preamble: for y in preamble: if x != y and x + y == curr: found = True if not found:...
47ded58babbed6a58e5016749dd1a21412ccf991
eolelake/AdventOfCode
/2019/1/solution.py
433
3.515625
4
def calc_fuel(mass): return int(mass/3) - 2 def calculate(): inputs = [] with open('./input.txt', 'rb') as fp: inputs = [int(line.strip()) for line in fp] sum = 0 for i in inputs: fuel = calc_fuel(i) sum += fuel while fuel != 0: fuel = max...
272164aab998c330e7808fa6d757c640a8564fda
ger2383/CSE
/Ger Yang - Items.py
3,096
3.765625
4
class Item(object): def __init__(self, name, value, weight): self.name = name self.value = value self. weight = weight def name(self): print("Jolt") def value(self): print("The % cost 20-90 coins" % self.value) def weight(self): print("The % is about 12...
018be81d6dbd1934dc79ef4e9307cd4bb560a45f
Prajwalnazre/APS-2020
/counterGame.py
733
3.625
4
#!/bin/python3 import math import os import random import re import sys # Complete the counterGame function below. def counterGame(n): count = 0 while n != 1 : if (n & (n - 1)) == 0 : n = n >> 1 count += 1 else : m = bin(n) m2 = int(m[3:],2) ...
99166045a24a0b4fdfe35f6f1865342382cd7859
ellisnguyen79/MonaMoney
/demo.py
2,687
3.671875
4
import matplotlib.pyplot as plt import matplotlib.animation as ani from Tkinter import * fig = plt.figure() ax1 = fig.add_subplot(111) file = "spyQA.txt" arr = [] hold = [] list12 = [] list26 = [] listmacd = [] listsig = [] def calc12(): temp = 0.0 count = 0 count12 = 0 for i in range(12): temp += float(arr[c...
fc5d4c5006f3c9217d58848447a4fd76382a4a72
GravityJack/keyed-merge
/keyed_merge/merge.py
880
4.1875
4
import functools import heapq def merge(*iterables, key=None): """ Merge multiple sorted iterables into a single sorted iterable. Requires each sequence in iterables be already sorted with key, or by value if key not present. :param iterables: Iterable objects to merge :param key: optional, callab...
5a132456690645bf3abcc73bf0dcac4533073159
yuvalsolaz/semi-supervised
/semisuper.py
5,458
3.578125
4
# imports for array-handling and plotting import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # keep our keras backend tensorflow quiet import os os.environ['TF_CPP_MIN_LOG_LEVEL']='3' # keras imports for the dataset and b...
b050b79347336df53d665e9be882b30ca837c9f9
BitwiseSystems/QuickUSB
/Software/QuickUsbDiagPy/PyInstaller1.3/Crypt.py
2,309
3.625
4
#!/usr/bin/env python # Crypt support routines # Copyright (C) 2005, Giovanni Bajo import sys class ArgsError(Exception): pass def gen_random_key(size=32): """ Generate a cryptographically-secure random key. This is done by using Python 2.4's os.urandom, or PyCrypto. """ import os if hasat...
270e8bd8f98d915bb4c3eab7214254d168e6c5af
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex100.py
730
4.1875
4
#Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). #A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar #a soma entre todos os valores pares sorteados pela função anterior. from random import randint numeros = list...
f1a8f4d31bebc4ac16a5398074c3b239b157b57f
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex043.py
988
4.15625
4
#ler a altura e o peso, e diga o IMC da pessoa print('-=-'*15) print(' Tabela IMC') print('-=-'*15) print('''Classifição de IMC: -Abaixo de 18.5: Abaixo do Peso -Entre 18.5 e 25: Peso ideal -25 até 30: Sobrepeso -30 até 40: Obsesidade -Acima de 40: Obesidade Mórbida''') altura = float(input('I...
79bbbe4ccc0ed72472e0afb9ee68195e2987b4a7
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex072.py
767
4.3125
4
#ler um némero entre 0-20 e mostrar ele por extenso ex: 1 - um tupla = ('Zero','um','dois','tres', 'quatro', 'cinco', 'seis', 'sete', 'oito','nove','dez', 'onze','dose','treze','quatorze','quinze','dezesseis', 'dezessete','dezoioto','dezenove','vinte') from time import sleep while True: numero = ' ' whil...
ed09e33964d65415f402260ca22f2f1cb07d9267
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex040.py
441
3.90625
4
#ler 2 notas e falar se esta aprovado, reprovado ou de recuperação. nota1 = float(input('Informe a primeira nota: ')) nota2 = float(input('Informe a segunda nota: ')) if (nota1+nota2)/2 < 5: media = (nota1+nota2)/2 print('Reprovado, sua média é de {}'.format(media)) elif (nota1+nota2)/2 > 7: print('...
a50a905d6ecc0c5255767c3a51a9e77ce825e36f
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex042.py
727
4.09375
4
#formação de triângulos: equilatero, isoceles e escaleno. #equilatero: todos os lados iguais #isoceles: dois lados iguais #escaleno: todos os lados diferentes #condições aninhadas r1 = float(input('Informe o primeiro lado: ')) r2 = float(input('Informe o segundo lado: ')) r3 = float(input('Informe o terceiro lad...
1c6976e5046fe64e8184b4c71021d321e1d47be8
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex038.py
354
4.03125
4
#leia um número, e mostre quem é maior e quem é menor. num = int(input('Informe o primeiro número: ')) num2 = int(input('Informe o segundo número: ')) if num > num2: print('O número {} é maior que {}'.format(num, num2)) elif num2 > num: print('O número {} é maior que {}'.format(num2, num)) else: pr...
6d570493dd09e2f45c0e2de1f7a1dc17c09498b5
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex041.py
580
4
4
print('''CLASSIFICAÇÃO: Até 9 anos: MIRIM Até 14 anos: INFANTIL Até 19 anos: JUINIOR Até 25 anos: Sênior Acima: Master''') idade = int(input('Informe sua idade: ')) if idade <=0: print('Invalido, não é possível classificar!') if idade>0 and idade<= 9: print('Classificação: MIRIM') elif idade > 9 and ...
4215f51f733aee82705cb8c4eef62d371153ab4a
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex016.py
521
4.15625
4
#receber um numero real e converter em inteiro #from math import trunc import math n = float(input('Informe um Número Real: ')) #assim é sem importar nenhuma biblioteca print('O número {} tem a aparte inteira {}.'.format(n, int(n))) #print('O número {} tem a aparte inteira {}.'.format(n, math.tunc(n)))-- usando o...
0ae9854fa9f101ff2544726d2b4a26b7798dfd2e
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex103.py
668
4.15625
4
#Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: #o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, #mesmo que algum dado não tenha sido informado corretamente. #função def ficha(nome = 'Desconhecido', gols = ...
7203f1479f69dca53903cf688afb1e5733215cc0
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex076.py
771
3.765625
4
#Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, #na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular. Tabela = ('Lapís', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Transferidor', 4.20, ...
670e0cdf838b9b91613d24164ac5ec9882e3d96f
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex075.py
540
4.1875
4
#gerar uma tupla aleatoria com 5 números. #mostrar quem é o maior, e quem é o menor. from random import randint numeros = (randint(1,10), randint(1,10), randint(1,10), randint(1,10), randint(1,10)) print('Os números Sorteados foram: ', end = ' ') for n in numeros: print(f'{n}', end = ' ') prin...
91bad61836f1b548a4cde47cabe0ec4fa458d822
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex039.py
601
3.9375
4
#alistamento militar. from datetime import date anon = int(input('Informe o ano em que você nasceu:')) anoatual = date.today().year idade = anoatual - anon if idade < 18: saldo = 18 - idade print('Você Nasceu no ano de {}, possui {} anos e nao pode se alistar tente daqui há {}'.format(anon, idade, saldo...
ce66653d7fff7ecf1b4546c0b1e1bcefe823c01c
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex086.py
624
4.28125
4
#Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. #No final, mostre a matriz na tela, com a formatação correta. from random import randint aleatorio = randint(0,10) matriz = [[0,0,0], [0,0,0], [0,0,0]] for l in range(0,3):#para ler o camando na linha for c in ...
0c2b7e60e247b023a77495b3b67020797aadc5b4
MarcosMaciel-MMRS/Desenvolvimento-python
/Python-desenvolvimento/ex010.py
278
4.03125
4
#Cria um programa que leia o quanto vc tem de dinheiro e converta em dolar #levando em consideração o valor do dolar == 3,27 n = float(input('Quanto de dinehiro vc possui: R$ ')) dolar = n/5.73 print('Você possui R${:.2f}. Em dolar vc teria US${:.2f}'.format(n, dolar))
3cfeb3f4d7c3cb3ef3e4ace6197651c7016acbd5
258292-harsimran/python_258292_daily_commit-main
/python_practice-main/python programming submissions/if_else_03.py
181
3.921875
4
slice=int(input("How many pizza slice you want = ")) if slice%2==0: price=slice*120 print("Total amount =",price) else: price=slice*123 print("Total amount =",price)
59c822bac6fd9baf3c09a8bcede250e4073dbeb6
joyzo14/advent_of_code_2020
/day11_2020.py
3,771
3.59375
4
def solve(input): input = input.splitlines() # creating 2 dimensional list with all positions for i in range(len(input)): input[i] = list(input[i]) while (True): # coordinates for seats have to be occupied coordinatesForNewOccupied = [] # coordinates for...
e829bf772ed0edd59a54458d4a6cd3a206ac8d80
jacquessham/DataStructure
/Sorting/Python/InsertionSort.py
190
3.921875
4
def insertionSort(arr: list) -> list: for i in range(1, len(arr)): temp = arr[i] j = i-1 while (arr[j]> temp and j >= 0): arr[j+1] = arr[j] j -= 1 arr[j+1] = temp return arr
bcf893864c3f332548c13650d28c9960d9b0c771
jacquessham/DataStructure
/Sorting/Python/SortingDriver.py
1,480
3.703125
4
from random import randint from time import time from sys import setrecursionlimit from SelectionSort import selectionSort from BubbleSort import bubbleSort from InsertionSort import insertionSort from MergeSort import mergeSort from QuickSort import quickSort # Set the size of array arr_len = 10000 # Increase Pytho...
ba64deb16fc670c3394a0cf91f2e7ebec0358af0
vuhaibang/projecteuler
/euler9.py
424
3.90625
4
#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, #a2 + b2 = c2 #For example, 32 + 42 = 9 + 16 = 25 = 52. #There exists exactly one Pythagorean triplet for which a + b + c = 1000. #Find the product abc. import time start = time.time() for a in range(1, 250): for b in range(a + 1, 500):...
c851e66a87cd7e7d34d357f73bb33d4317d356b7
sedlmartin/life-is-tough
/shiTtExt.py
402
3.78125
4
from random import randint def main(): print("all credits belong to Lukas Chronc") print("he's indeed better than me") print("enjoy it") text = list(input("Let me FUCK your text: ")) start = 0 end = 3 while end < len(text) - 1: pos = randint(start, end) text[pos] = text[pos].upper() start += 1 end += 1 ...
e28bfdda85356e660b03e2bfb713098553017f94
SLACE93/operativosFS
/DoubleLinkedList.py
2,146
3.921875
4
class Node(object): def __init__(self, data, prev, next): self.data = data self.prev = prev self.next = next class DoubleLinkedList(object): head = None tail = None def append(self, data): new_node = Node(data, None, None) if self.head is None: se...
c42d98a322b0062c2c2e66fc1f00645174de5d88
igoradriano/curso_python_bemol
/Aula_22/aula_22-funcao-lambda.py
742
4.25
4
# Funcoes anonimas soma = lambda a,b : a + b mult = lambda a,b,c : (a+b)*c print((lambda a,b: a - b)(3,44)) # Neste caso nem preciso declar nome, nem chamá-la, ele ja executa # Usando a funcao criada c = soma(1,2) print(c) print(soma(1,2)) print(mult(1,2,3)) # Usando funcoes como parâmetro da funcao lambda r = la...
2b0f4a5969137ba664425b5c5df7ddb9307549d4
igoradriano/curso_python_bemol
/Aula_13/aula_13-input-os-system.py
354
3.90625
4
# Limpar o terminal import os os.system('cls') #Windows #os.system("clear") #Linux nome = input("Digite seu nome: ") print('Olá, ',nome.upper()) input() # continua o programa apenas se voce apertar qualquer coisa num1 = int(input("Digite um numero: ")) num2 = int(input("Digite outro numero: ")) print("A soma dos ...
54e555b2afb71946c9f13e2a396af4021ace853f
igoradriano/curso_python_bemol
/Aula_24/aula_24-classes-met-construtor.py
1,051
3.8125
4
class Carro: vel_max = 0 ligado = False cor = '' def __init__(self,marca,modelo,ano,potencia,n_portas): # parametros obrigatorios na hora da criacao self.marca = marca self.modelo = modelo self.ano = ano self.potencia = potencia self.n_portas = n_portas ...
81d745864719dbe6cc42481b6323683f06a57452
KroegerP/cs3003
/scope_lifetime/referencing_environment.py
1,581
3.8125
4
import inspect def show_referencing_environment(): frame = inspect.currentframe() frame = frame.f_back print("Contents of the referencing environment:") print("\n".join(frame.f_locals.keys())) def testing(): five = 5 pass def outer_function(parameter_one = None, parameter_two = None): outer_local1 = N...
d0cb124d6bd02d64e2bbdeca8373c9e986b491eb
emediato/hello-world-python3-django-flask
/searchlongest.py
4,228
3.734375
4
"""Given an arbitrary unweighted rooted tree which consists of N nodes. The goal of the problem is to find largest distance between two nodes in a tree. Distance between two nodes is a number of edges on a path between the nodes (there will be a unique path between any pair of nodes since it is a tree). The nodes wi...
d2dd1804332c920c5f8c86ecf1213bfb0fb7bdf1
MatthewScholefield/flask-resto
/flask_resto/misc.py
419
4.09375
4
def recursive_merge(a, b): """Returns a generator of a merged dict of a and b""" for k in set(a.keys()) | set(b.keys()): if k in a and k in b: if isinstance(a[k], dict) and isinstance(b[k], dict): yield k, dict(recursive_merge(a[k], b[k])) else: yi...
ca546534d0f6e9b999e466f5a7a03628925c54c9
lucashu1/wildlifeRL
/multiple_defenders - withadversaryNN/number_conversion.py
664
3.9375
4
def convert_decimal(number): str_num = str(number) #REMOVE - SIGN IF ANY if str_num[0]=='-': str_num = str_num[1:] deci_pos = str_num.index('.') #PROCESS THE LEFT SIDE OF THE DECIMAL str_deci_left = str_num[0:deci_pos] deci_left = int(str_deci_left) if deci_left > 0: ...
d1fec0ce50409eb0a6c32075c923cb77e51ca69c
Frederiquee/miniprojecct
/les9/pe9_2.py
997
3.65625
4
import datetime import csv bestand = 'inloggers.csv' #gebruik hier een herhalingslus: naam = input('Wat is je achternaam? ') voorl = input('Wat zijn je voorletters? ') gbdatum = input('Wat is je geboortedatum? ') email = input('Wat is je e-mail adres? ') #wanneer de volgende persoon inlogt is onbekend, dus schrijf m...
ac3717dcb22a321ad811316b536aa7984ea4348b
Frederiquee/miniprojecct
/les.py
108
3.828125
4
for i in range (1,10): print(i, end=" ") print() for i in range (0, 9, 2): print(i, end="") print()
98147363a143fd58071b7d4fe587ac50f2bfb94f
Frederiquee/miniprojecct
/les7/pe7_1.py
268
3.515625
4
getal = eval(input('Geef een getal: ')) aantal_getallen = 0 som = getal while getal != 0: getal = eval(input('Geef een getal: ')) som += getal aantal_getallen += 1 else: print('Er zijn {} getallen ingevoerd, de som is {}'.format(aantal_getallen, som))
cddf153627f26132ef078bf808bee075b9ab1db5
ttinning/karaoke_homework_lab_week_two
/tests/song_test.py
570
3.65625
4
import unittest from src.song import Song class TestSong(unittest.TestCase): def setUp(self): self.song_1 = Song("Rex Orange County, New House") self.song_2 = Song("Tyler, The Creator, EARFQUAKE") def test_song_1_has_song_name(self): expected = "Rex Orange County, New House" ...
d1baf5c3992144960de3152a85d9b7d687e88b6d
msflyee/Learn_python
/code/Chapter7_input&while-recycle.py
3,502
4.46875
4
# Chapter7_input&while-recycle.py # greeter.py prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name?" name = input(prompt); print("\nHello, " + name + "!"); # even_or_odd.py number = input("Enter a number, and I'll tell you if it's even or odd:...
7c918ccd80ec7fd3c45d8233a12a62bd423c7937
msflyee/Learn_python
/code/Chapter4_operations on a list.py
1,062
4.28125
4
# Chapter4-operations on a list magicians = ['Alice','David','Liuqian']; for magician in magicians: #define 'magician' print(magician + '\t'); for value in range(1,5): #define value print(value); numbers = list(range(1,6)); print(numbers); even_numbers = list(range(2,11,2)); #打印偶数,函数range()的第三个参数为 步数 print(...
1a3f812778c37151776107364d9afd5fe653c7ce
azamlerc/interviews
/fourfours/fourfours.py
1,919
3.53125
4
# -*- coding: UTF-8 -*- # Four fours is a mathematical puzzle. The goal is to find a mathematical # expression for every whole number from 1 to 100, using only common # mathematical symbols and the number four four times. # # Problem: https://en.wikipedia.org/wiki/Four_fours # Playground: https://andrewzc.net/fourfours...
28f5bdd0c56c07ac39bf3ec96036c3d7523336a9
x404/CodeSignal
/Arcade/Smooth Sailing/allLongestStrings.py
239
3.5625
4
# Given an array of strings, return another array containing all of its longest strings. # Solution def allLongestStrings(inputArray): m = max(len(s) for s in inputArray) r = [s for s in inputArray if len(s) == m] return r
f7daa02ce9df9ccb2990455c609af0683c7f9284
Ena-Sharma/Meraki_Solution
/List/kbc_part_3.py
1,341
3.703125
4
question=["Ques 1: The weight of diamonds is usually measured in what?","Ques 2: Who of these politicians is this person talking about? ","Ques 3: Which state of India has the shortest coastline?","Ques 4: Vasant, Vinod, Mahasukh, Gautam and Rajesh are brothers related to whih of these business families?","Ques 5: Who ...
ad064647b8c9495bb68af10e0aff7154ea7ccbba
Ena-Sharma/Meraki_Solution
/If-Else/saral_if_solution.py
4,303
3.921875
4
''' #Question-1 Ek number naam ke variable mein ek variable input lo aur usko integer mein type cast kar lo. Agar yeh number 10 se chota hai tab print karo “10 se chota hai”. Agar wo 10 se bada hai aur 20 se chota hai tab print karo “20 se chota hai”. Aur agar 20 se bada hai tab print karo ki “20 se bada hai”. Iss ...
e01a20f31a7ba1e5ccdc5bac381325b54fcfe2f4
Ena-Sharma/Meraki_Solution
/More-Exercise/saral_more_excercise.py
6,532
3.71875
4
''' 1 se 1000 tak saare numbers print karne ka loop likho. Lekin Agar number 3 se divisible hai toh "nav" print karvao. Agar number 7 se divisible hai toh "gurukul" print karvao. Agar number 21 se divisible hai toh "navgurukul" print karvao. ''' i=1 while i<1000: if i%21==0: print(i,"Nav_Gurukul") elif i%7==0: p...
de4d701ae36a4331c35934797b2c30439fff2e34
Ena-Sharma/Meraki_Solution
/Python_Programing_Excercise/Day_2/string_concatination.py
285
3.515625
4
''' Apko ek string di jayegi jahan apko string ke phele 2 aur akhir ke 2 letters print karwana hai lekin agar woh string meh 2 se kaam letters hai toh kuch bi nhi print hoga. Eg: Input: 'string' Output:'stng' ''' string=raw_input('Enter the name:-') print string[0:2]+string[-2:]
6d2b679435af9216e43a07ed9fc811d15193d8ae
Ena-Sharma/Meraki_Solution
/Python_Programing_Excercise/Day_1/perfect_number.py
518
3.5625
4
''' Apko ish sawal me ek program likhna hai jishme ek value di jayegi manlo 1000 toh apko jitne bi number Perfect Number hai 0 se 1000 ke bich me ushe print karna ha. Eg: Input: 1000 Output: 6 28 496 ''' num= int(input("Enter the number for perfect number search: ")) n = 1 while n <= num: sum =...
1af700824832f2e3856c0a27ae0cc706925ac8e5
ratafee1/python_basics
/MachineLearning/day03/14.1exception_if_elif_else.py
659
3.90625
4
#-*- coding: utf-8 -*- # @Time : 2018/9/28 17:43 # @Author : Z # @Email : S # @File : 14.1exception_if_elif_else.py number=60 while True: try: #用户输入猜测数字 guessNumber=input("Please input your guess Number:") #判断 if guessNumber == number: print "Wow" pri...
3259df4ec500a459f2dfe1d235ad7c3b12305d96
rajeshpyne/Work
/SOLID_principle/1_single_responsibility.py
4,021
4.0625
4
# Single Responsibility Principle (aka Separation Of Concerns) # A class should have only one primary responsibility and reason to change ''' Let’s take an example of a Telephone Directory application. We are designing a Telephone Directory and that contains a TelephoneDirectory Class which is supposed to handle prima...
a252f84de72fe91c6b88031219949467e9457ecf
sergzorg/pythonhillel
/DZ_1/2.py
202
3.859375
4
#!/usr/bin/python3 ##by Sergey Zhukanov def gen_even_list(): even_list=[] for x in range(100): if (x+1) % 2 == 0: even_list.append(x+1) return(even_list) print(gen_even_list())
d18a6d21f3724aec20eebda92a7c5f583e87b0e1
zamu5/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
429
3.9375
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) flag = 0 if number < 0: number = number * -1 flag = 1 n = number % 10 if flag: number = number * -1 n = n * -1 if n > 5: print('Last digit of', number, 'is', n, 'and is greater than 5') elif n == 0: print('Last digit of', nu...
d35e1c3a8223ac23165bcce3b0cf5365e5ff6553
zamu5/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
352
4
4
#!/usr/bin/python3 def text_indentation(text): if not isinstance(text, str): raise TypeError("text must be a string") s = text[:] for d in ".?:": list_text = s.split(d) s = "" for i in list_text: i = i.strip(" ") s = i + d if s is "" else s + "\n\n" + ...
cb13da7c0441a6b1ee18c95d4c74078c1b3250ec
zamu5/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
113
3.8125
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): return dict([(y, x*2) for y, x in a_dictionary.items()])
b2b7106f26a73475f98d4d062b552f1acdd7f91b
petersadosky/tp
/cluster/minwise.py
9,023
3.671875
4
""" Input restaurants.csv from clean folder. Use minwise hashing procedure to assign restaurants to clusters based on similarity measures. I made this clustering algorithm prior to this class with support from my advisor, Rebecca Steorts in the stats department. It's a combination of minwise hashing and k-means local...
2a183caad6aa502bede2528ee47dfdf16d75ea2b
aashitarakesh/Python_Challenge
/PyBank/main.py
3,601
4.125
4
# Create a Python script that analyzes the records to calculate each of the following: # * The total number of months included in the dataset # * The net total amount of "Profit/Losses" over the entire period # * Calculate the changes in "Profit/Losses" over the entire period, then find the average of those ch...
6e0bca1aa514fcd9e45b842bea9dc5587493b064
MikeKrueger75/dev101
/lesson5/creice_3.py
1,024
3.84375
4
## Alle Eintraege groesser 10 rausschmeissen Liste =[] def list_info(wert): Liste.append(wert) def less_ten(Liste): elemente = len(Liste) print ("Elemente"+str(elemente)) i=0 while i < elemente: print "Zaehler For Schleife "+str(i)+" wird durchlaufen" print "Altes Listenlement " +str(Liste[i]) if Liste...
a30af1c94b182878674fdcccffe95edbc936942f
MikeKrueger75/dev101
/lesson2/vanessas_script.py
161
4
4
name=raw_input("what's your name? :") age=raw_input("how old are you?") year=2017-int(age)+100 print"hello, " + name + age + " you will turn 100 in "+ str(year)
1e324022307c966cd2595e6cdc4a9e74eaa15136
MikeKrueger75/dev101
/lesson4/caspii_1.py
336
3.625
4
# print "Hello world" # # def add_2_numbers(num1, num2): # new_number = num1 + num2 # return new_number # # print add_2_numbers(90,34) # print add_2_numbers(1,34) # print add_2_numbers(45, -100) def greet(name): print "Hello " + name + ", I hope you are well" return 1 greet('caspar') keks = greet('chr...
5e8b4315ca39fa0c724b80bc871828efacf4fa88
MikeKrueger75/dev101
/lesson4/Karfunkel_1.py
192
3.53125
4
def my_max(a,b,c): if a>b and a>c: return a elif b>a and b>c: return b else: return c print my_max(2,3,4) print my_max(5,6,7) print my_max(8,9,10000000)
d1a36d2450daeccba3f55a7d6926d4e0afacb0ef
chanpham97/advent-of-code
/src/day1.py
1,907
4
4
''' At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet. Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For ex...
ed4945bcf5b5a401bfad25c889ab4670ef194b13
KEERTHANA40/Competitive-Programming
/Week 3/Day2/Repeat_space_edition.py
1,324
3.703125
4
import unittest def find_repeat(the_list): n = len(the_list) i = n j = n while True: print("looking for cycle: i %s j %s" % (i, j)) i = the_list[i - 1] j = the_list[j - 1] j = the_list[j - 1] if i == j: print("cycle found at %s" % ...
f7ca7506e6d541775c6ee8a4851a983298a28a3e
djechlin/network_game_theory
/ngt/game.py
8,297
3.609375
4
# -*- coding: utf-8 -*- """Classes and methods related to the concept of game Todo: * Reaction .. _Google Python Style Guide: http://google.github.io/styleguide/pyguide.html """ import networkx as nx from ngt.rules import ActionSpace, Rules from ngt.increment import Increment from ngt.utils import fetch_adeq...
653e70e5119c47b9165758c7acb0091ca5b20aa7
Mjcanson/TCP-UDP-Centralized-Client-Server-Network
/server/server.py
2,745
3.78125
4
# don't modify this imports. import socket from threading import Thread from client_handler import ClientHandler class Server(object): """ The server class implements a server socket that can handle multiple client connections. It is really important to handle any exceptions that may occur because other cl...
cc12c5f4b743c6283ea2f760f09b8db720c5ae97
whigg/get-geoid-height
/get_geoid_height.py
1,113
3.59375
4
from urllib.request import urlopen import json import argparse geoid_api_baseurl = 'https://vldb.gsi.go.jp/sokuchi/surveycalc/geoid/calcgh/cgi/geoidcalc.pl?select=0&tanni=1&outputType=json' def getGeoidHeight(latitude_degree:float, longitude_degree:float): req_url = geoid_api_baseurl + '&latitude='+str(latitude_de...
3a6afb4865aecc970f3f7da751454b047d8e21bb
AndrewNik/python_course
/less9/task2.py
2,077
3.640625
4
# 2. Закодируйте любую строку по алгоритму Хаффмана. import heapq from collections import Counter from collections import namedtuple class Node(namedtuple("Node", ["left", "right"])): # класс для ветвей дерева - внутренних узлов; у них есть потомки def walk(self, code, acc): self.left.walk(code, acc + "0") # по...
733f3343ec96f97ef4af38c87accc5cda0324999
AndrewNik/python_course
/less7/task2.py
936
4.1875
4
# 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на # промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. import random def merge_sort(arr): def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): ...
c98d023847078fd30d25a08009ce3dea375e598a
AndrewNik/python_course
/less3/task4.py
516
3.90625
4
# 4. Определить, какое число в массиве встречается чаще всего. import random list1 = [random.randint(1, 5) for _ in range(10)] print(list1) most_frq_el = list1[0] max_frq = 1 for idx, el in enumerate(list1): frq = 1 for nested_el in list1[idx + 1:]: if el == nested_el: frq += 1 if frq > max_frq: max_frq =...
60a6ee70d741fa7686b0384abce65d64b6ea0569
AndrewNik/python_course
/less3/task2.py
746
4.0625
4
# 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, # если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5 # (помните, что индексация начинается с нуля), т. к. именно в этих позициях первого массива стоят четные числа. import random list1...
88e44ffb1d4154b49bf421abe4fc88c488896ae0
lishidaup/AdaSegment
/collection/linkedlist/LinkedList.py
4,139
3.84375
4
# !/usr/bin/env python # coding=utf-8 # by lsd 2017-05-18 class Node(object): def __init__(self, data, pnext=None): self.data = data self._next = pnext def __repr__(self): return str(self.data) class LinkedList(object): def __init__(self): self.head = None self.le...
fc6e0f0baa4421f0de86daa88f1085ed6a0a90ca
imdsoho/python
/pattern/template_pattern/abstract_operation.py
1,096
4
4
#-*- coding: utf-8 -*- from abc import abstractmethod, ABCMeta #class AbstractOperation(metaclass=ABCMeta): class AbstractOperation(): __metaclass__ = ABCMeta def __init__(self): self.firstNumber = 0 self.secondNumber = 0 def operate(self): firstNumber = self.getFirstNum...
2d85c93d42a0eaedeb5d1e4915eb87760a2c4d0b
imdsoho/python
/pattern/factory_pattern/code_test.py
1,231
3.75
4
from abc import ABCMeta, abstractmethod class Connector(object): """A client.""" def __init__(self, factory): """factory is a AbstractFactory instance which creates all attributes of a connector according to factory class.""" self.protocol = factory.create_protocol() self.port = factory...
12ebe45459a68ce78152bffa629889e4136d2fef
imdsoho/python
/Function/patial_test.py
448
3.546875
4
from functools import partial print(type(partial)) def add(a, b): return a + b add_one = partial(add, "a") #print(type(add_one)) #print(add_one) print(add_one("b")) class PartialTest(): def __init__(self, name): self.name = name '''def __str__(self): return self.name''' wrap = partial...
4c6867e39d99feef979aec3059cae748b3e1600e
imdsoho/python
/descriptor/decorator_2_descriptor.py
2,954
3.625
4
"""Clean Code in Python - Chapter 6: Descriptors > Using descriptors instead of class decorators """ from datetime import datetime from functools import partial from typing import Any, Callable class BaseFieldTransformation: """Base class to define descriptors that convert values.""" def __init__(self, tra...
4931393cfe7dd8864ab538a922d6afb4bb9f6566
imdsoho/python
/DataStructure/chainMap.py
1,546
3.53125
4
# ChainMap은 매핑을 여러 개 받아서 하나처럼 보이게 한다. # 매핑에 대한 리스트를 유지하면서 리스트를 스캔하도록 일반적인 딕셔너리 동작을 재정의 # 중복키가 있으면 첫번째 매핑의 값을 사용 from collections import ChainMap a = {'x':1, 'z':2} b = {'y':2, 'z':3} c = ChainMap(a, b) #print (len(c)) # 3 values = ChainMap() values['x'] = 1 values['z'] = 7 values = values.new_child() values['x'] = di...
2b1553315201e6521c900fd27bb037fb5dd83bd4
imdsoho/python
/Basic/generator_yield.py
1,450
3.875
4
# [generator] # generator는 iterator 를 생성해 주는 function이다. # iterator 는 next() 메소드를 이용해 데이터에 순차적으로 접근이 가능한 object 이다. # generator는 일반함수와 다르지 않지만 yield가 있다. # [Yield] # generator 함수가 실행 중 yield를 만날 경우, 해당 함수는 그 상태로 정지(frozen)되며, 반환 값을 next()를 호출한 쪽으로 전달한다. # 이후 함수는 일반적인 경우 처럼 종료되는 것이 아니라 그 상태로 유지된다. # "frozen"은 로컬 변수, 명령...
be76552552010a7b03cd364d1bedcd1d49d02b05
imdsoho/python
/pattern/state_pattern/tv.py
631
3.734375
4
from abc import ABCMeta, abstractmethod class State(metaclass=ABCMeta): @abstractmethod def doThis(self): pass class StartState(State): def doThis(self): print("TV On") class StopState(State): def doThis(self): print("TV Off") class TVContext(State): def __init__(self): ...
c0fd8fce12ba7dc0d8dc83e15ccc372b56831d32
kribow21/HW19A
/app.py
1,046
4.09375
4
import addition import subtraction import multiplication import division print("1 : Addition") print("2 : Subtraction") print("3 : Multiplication") print("4 : Division") user_calculation_choice = int(input("Please select an option for the calculation : ")) user_num_one = int(input("Please enter your first number : "))...
30808f5fb665d31421e878ace60502afebf33836
ShaneRandell/Midterm_001
/midterm Part 4.py
867
4.1875
4
## Midterm Exam Part 4 import csv # imports the csv library file = open("book.csv", "a") # Opening a file called book.csv for appending title = input("enter a title: ") # asking the user to enter a title author = input("Enter author: ") # asking the user to enter a author year = input("Enter the year it wa...
065aff05e0876ed0cedeea555109f6147a9d3219
Venkatesh147/60-Python-projects
/60 Python projects/BMI Calculator.py
572
4.28125
4
Height=float(input("Enter your height in centimeters: ")) Weight=float(input("Enter your weight in kg: ")) Height=Height/100 BMI=Weight/(Height*Height) print("your Body Mass Index is: ", BMI) if(BMI>0): if (BMI<=16): print("you are severly underweight") elif (BMI<=18.5): ...
ceb1123621db27d2c558643e62fd0504d27a6c0f
Venkatesh147/60-Python-projects
/60 Python projects/Calendar.py
967
3.9375
4
from tkinter import * import calendar def showcalendar(): gui = Tk() gui.config(background ='grey') gui.title("Calendar for the year") gui.geometry('600x750') year = int(year_field.get()) gui_content=calendar.calendar(year) calyear = Label(gui, text=gui_content, font='Consolas 10 ...
f379c13e423d2052bb6db129e3a5cbf891580e81
Knightbomb8/4-In-A-Line
/board.py
9,071
3.59375
4
import sys from AlphaBetaSearcher import alpha_beta_search import time class Board: def __init__(self, depth=0, board_state=None, board_size=8): if board_state is None: self.board_state = [['-' for i in range(board_size)] for j in range(board_size)] else: self.board_state ...
2b654bfaf67cefdbdff9a1b4b61d4d80af3da5ff
CodecoolBP20172/pbwp-3rd-si-code-comprehension-frnczdvd
/comprehension.py
1,948
4.34375
4
# This program picks a random number between 1-20 and the user has to guess it under 6 times import random # Import Python's built-in random function guessesTaken = 0 # Assign a variable to 0 print('Hello! What is your name?') # Display a given output message myName = input() # Ask for user input number = random.ran...
f97c7326e6be4786e1fda3a5c4a55c61aa6c6f3c
KLKln/Module11
/employee1.py
2,382
4.53125
5
""" Program: employee.py Author: Kelly Klein Last date modified: 7/4/2020 This program will create a class called employee allowing the user to access information about an employee """ import datetime class Employee: def __init__(self, lname, fname, address, phone, start_date, salary): """ use r...
bf4b783eb849d1dc329e12e2b46b3b554156def7
kondrashov-do/hackerrank
/algorithms/sorting/insertion_sort_pt1.py
560
3.96875
4
#!/bin/python3 import math import os import random import re import sys # Complete the insertionSort1 function below. def insertionSort1(n, arr): i = n-1 value_to_sort = arr[i] while arr[i-1] > value_to_sort and i > 0: arr[i] = arr[i-1] print(' '.join([str(el) for el in arr])) i -=...
ad41faba386982ab7db5ff3a9d9ad8858685ba05
kondrashov-do/hackerrank
/crack_interview/bubble_sort.py
447
4
4
def bubble_sort(arr): swap_num = 0 for i in range(0, len(arr)): for j in range(0, len(arr)-1): if arr[j] > arr[j+1]: swap_num += 1 arr[j], arr[j+1] = arr[j+1], arr[j] print('Array is sorted in %d swaps.' % swap_num) print('First Element: %d' % arr[0]) ...