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
1bb1c0e327300b98526b91d88217cd75360260bf
jfernand196/Ejercicios-Python
/concatenar_lista.py
319
3.53125
4
# simular la funcion join numeros = [2,4,5,77] #opcion 1 #print('juan'.join([str(n) for n in numeros])) #print('juan'.join(numeros)) #opcion 2 def concatenar_listas(lista): resultado= '' for i in lista: resultado +=str(i) return resultado numeros = [2,4,5,77] print(concatenar_listas(numeros))
30163909aeaaa4efaa8d27365f4631b18390aab4
jfernand196/Ejercicios-Python
/operador_not.py
382
3.53125
4
#Operador logico de negacion de verdad: NOT print('Operador logico de negacion de verdad : NOT') llueve = True print('contenido de la variable llueve:', llueve) llueve = not llueve print('contenido de la variable llueve:', llueve) print() edad = 17 resultado = not edad < 18 print('Resultado', resultado) edad ...
7b884b25dd4b1f427e61c8259d7673e9f49706cb
jfernand196/Ejercicios-Python
/makeitreal03.py
390
3.953125
4
# Duplica cada elemento # Escribe una función llamada duplicar que reciba un arreglo de números como parámetro y retorne un # nuevo arreglo con cada elemento duplicado (multiplicado por dos). # duplicar([3, 12, 45, 7]) # retorna [6, 24, 90, 14] # duplicar([8, 5]) # retorna [16, 10] def duplicar(x): return [i*2 f...
42d3e9a30261a005a547a0957c4e53d2a19d5911
jfernand196/Ejercicios-Python
/examen_makeitreal.py
610
4.21875
4
# Temperaturas # Escribe una función llamada `temperaturas` que reciba un arreglo (que representan temperaturas) y # retorne `true` si todas las temperaturas están en el rango normal (entre 18 y 30 grados) o `false` de # lo contrario. # temperaturas([30, 19, 21, 18]) -> true # temperaturas([28, 45, 17, 21,...
661cafb9861064d8006a56dceaf4177a0131bf31
jfernand196/Ejercicios-Python
/gen_num_primos.py
652
3.578125
4
## Generar n cantidad de numeros primos consecutivos # 2, 3, 5, 7, 11 ... def generar_primo(): numero = 2 yield numero while True: temp = numero while True: temp += 1 contador = 1 contador_divisores = 0 while contador <= temp: ...
38b85a7e4050e345f3b1eedadb288fcec5dad51a
jfernand196/Ejercicios-Python
/letcode_1678.py
855
4.09375
4
# You own a Goal Parser that can interpret a string command. The command consists of an alphabet # of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", # "()" as the string "o", and "(al)" as the string "al". The interpreted strings are # then concatenated in the original...
342bd4524146685a04fb5bbc20fe03f51d4baedd
jfernand196/Ejercicios-Python
/try_except_else_finally.py
435
3.921875
4
# Programa que le pide al usuario la edad (edad entero) y comprueba #si ese usuario es mayor de edad (18 años) try: numero = int(input('introduce tu edad: ')) except ValueError: print('no has introduciod un nuemero entero') else: if numero >= 18: print('eres mayo de edad') else: ...
d13db4be9d30a72dbe1edb5af5178d3b897fbf4d
jfernand196/Ejercicios-Python
/area_triangulo.py
466
3.859375
4
## Calcular el area de un triangulo base = None altura = None while True: try: base = float(input('escriba la base del triangulo: ')) break except: print('Debe de escribir un numero.') while True: try: altura = float(input('escriba la altura del triangulo: ')) brea...
2b8f6de2b9ac1a87bbc8a2e27df982fb72bef80f
ChetanVDhawan/PythonDataStructures
/LinkedList.py
2,290
4.03125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.start = None def add(self, data): node = Node(data) if self.start is None: self.start = node return temp = self.start ...
59b2ff13da21c4d38f95749450ba726579c69209
piranna/asi-iesenlaces
/0708/listas/ej234.py
568
3.96875
4
# -*- coding: cp1252 -*- #$Id$ """ Disea un programa que elimine de una lista todos los elementos de valor par y muestre por pantalla el resultado. (Ejemplo: si trabaja con la lista [1, -2, 1, -5, 0, 3] sta pasar a ser [1, 1, -5, 3].) """ # mtodo 1: con while lista = [1, -2, 1, -5, 0, 3] i = 0 while ...
bae04ed2f85dc7b04153764d391fedf3f3148106
piranna/asi-iesenlaces
/0708/examenes/27feb/1234.py
3,292
3.765625
4
# -*- coding: utf-8 -*- def listadoAlumnos(listaAlumnos, curso, grupo=0): """ Entrada: una lista de alumnos como la indicada anteriormente, el nombre de un curso y opcionalmente el número de un grupo. Devuelve una lista con los datos de los alumnos del curso y grupo indicados. Si no se indica grupo, devolv...
4733fe243f4582efe2705f4181188a2920f3f846
piranna/asi-iesenlaces
/0708/repeticiones/ej118.py
989
3.84375
4
# -*- coding: utf-8 -*- """ $Id$ Realiza un programa que proporcione el desglose en billetes y monedas de una cantidad entera de euros. Recuerda que hay billetes de 500, 200, 100, 50, 20, 10 y 5 € y monedas de 2 y 1 €. Debes recorrer los valores de billete y moneda disponibles con uno o más bucles for-in. """ # Prese...
42bb3d5df47e7eb91425f7a92e19872ed16e3483
piranna/asi-iesenlaces
/0708/repeticiones/ej109.py
861
4.21875
4
# -*- coding: utf-8 -*- """ $Id$ Calcula el factorial de un número entero positivo que pedimos por teclado Si tienes dudas de lo que es el factorial, consulta http://es.wikipedia.org/wiki/Factorial """ # Presentación print "*" * 50 print "Programa que calcula el factorial de un número" print "*" * 50 # Petición del n...
ba9b41a053ff6e6ea6df38fae9807cb3ecd49220
piranna/asi-iesenlaces
/0708/examenes/23nov/exa10.py
1,744
4.09375
4
# -*- encoding: utf-8 -*- # $Id$ """ Escribe una función que reciba una lista de nombres y que imprima la lista ordenada. La lista tendrá la siguiente estructura: [ “Ana, Martínez, Blasco”, “Nombre,Apellido1, Apellido2”, ...]. La ordenación se hará según el siguiente criterio: Apellido1 – apellido2 – Nombre. Es de...
597e97399626f74acfdadf7a75811a102fa19ff4
piranna/asi-iesenlaces
/0708/repeticiones/ej129.py
930
3.734375
4
# -*- coding: utf-8 -*- """ $Id$ Haz un programa que calcule el máximo comun divisor (mcd) de dos enteros positivos. El mcd es el número más grande que divide exactamente a ambos numeros. Documentación: http://es.wikipedia.org/wiki/M%C3%A1ximo_com%C3%BAn_divisor """ # Presentación print "*" * 50 print "Programa máxi...
4c4716e3d4b6710d9452f20af531be6c2cd5a9f5
piranna/asi-iesenlaces
/0708/repeticiones/mayormenor.py
756
3.84375
4
# -*- coding: cp1252 -*- """ $Id$ Trabajos con series de nmeros Mayor, menor, media ... Cuidado con los valores no vlidos al procesar una serie """ num = int(raw_input("Introduce un num positivo: ")) mayor = num # candidato el primero menor = num total = 0 veces = 0 while num >=0: if num > ma...
54582356e4fb4257a8066bdcca0f4612837deca9
piranna/asi-iesenlaces
/0708/repeticiones/esprimo.py
564
3.890625
4
# -*- coding: utf-8 -*- """ $Id$ Calcula si un número es primo. Ej. pág 118. Hay que mejorar el algoritmo. """ num = int(raw_input("Introduzca un número: ")) creo_que_es_primo = True for divisor in range (2, num ): if num % divisor == 0: creo_que_es_primo = False # Esta parte necesita una mejora...
3c55d755d5a00cab0e2ef1847d1c90672d6ac23a
zllu2/iMSA_577
/lessons/Module2/notebooks/helper_code/mlplots.py
1,071
3.734375
4
import pandas as pd import numpy as np import seaborn as sns # Convenience function to plot confusion matrix # This method produces a colored heatmap that displays the relationship # between predicted and actual types from a machine learning method. def confusion(test, predict, labels, title='Confusion Matrix'): ...
44a036e4b3d596c701892a3905bb27e369f93018
seanx92/hotel_retrieval
/hotels/search.py
6,175
3.53125
4
import shelve import time import heapq from tokenization import tokenize def search(name, address, onlyOverall=True, tags=["cleanliness", "service", "value", "location", "sleep_quality", "rooms"]): ''' This function is used for finding the conjunctive result by searching by "address" and "name". ''' addre...
c10d96e43b1b728b1f42250686fcae0d9aae2b69
jcguy/AdventOfCode2017
/problem4.py
827
3.703125
4
#!/usr/bin/env python3 # Advent of Code, Problem 4 # James Corder Guy def main(): # Part 1 num_valid = 0 with open("problem4.txt") as f: for line in f: phrase = line.replace("\n", "").split(" ") if sorted(phrase) == sorted(list(set(phrase))): num_valid += 1 ...
795f82845050e500086eea28a79bdfc9654ed8b7
anwenliucityu/atomman
/mep/integrator/rungekutta.py
820
3.5
4
# coding: utf-8 def rungekutta(ratefxn, coord, timestep, **kwargs): """ Performs Runge-Kutta ODE integration for a timestep. Parameters ---------- ratefxn : function The rate function to use. coord : array-like object The coordinate(s) of the last timestep. timestep : f...
f9e60194c6a8df0e7755f45703ca36915db08388
maisha815/Solitaire_Cypher
/cipher.py
2,513
4.03125
4
import c_functions import os.path def validate_file_name(message): """ (str) -> str Prompt user the message to type the name of a file. Keep re-prompting until a valid filename that exists in the same directory as the current code file is supplied. Return the name of the file. """ ...
a7248417ac7f1924cd5db4323c8b3903bdda1047
grimsley217/608-mod1
/range.py
175
4.25
4
#range.py """This prints the range of values from the integers provided.""" x=min(47, 95, 88, 73, 88, 84) y=max(47, 95, 88, 73, 88, 84) print('The range is', x, '-', y, '.')
da79c29a1fa65206d5446bf374974aaef57b09e2
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_8.py
265
3.640625
4
from random import randint s1 = str(input("Digite o 1º texto: ").replace("","")) s2 = str(input("Digite o 2º texto: ").replace("","")) len_s1 = len(s1) len_s2 = len(s2) print(len_s1) menor = len_s1 if(len_s2<menor): menor = len_s2 r = randint(0,menor) print(r)
9a28fbd169078b2133058156d9f7c3c8f86d38ae
luiz-vinicius/IP-UFRPE-EXERCICIOS
/aula_lista_ex_2.py
157
4.09375
4
lista = [] for x in range(10): v = float(input("Digite um valor: ")) lista.append(v) lista.reverse() for i,p in enumerate(lista): print(i+1,"º = ",p)
3323f4d0504f59a298ff413e4e79de25f23f79b0
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista3_ex_8.py
291
3.75
4
nome = str(input("Digite o nome do funcionário: ")) sal = float(input("Digite o salário bruto do funcionário: ")) des = sal *5/100 sal_liq = sal - des print("Nome do funcionário: {} \nSalário Bruto {:.2f} \nDesconto: {:.2f} \nSalário Líquido: {:.2f}".format(nome, sal, des, sal_liq))
03fc80b0a61c1c6a16672f55488287f969f0a0e3
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_9.py
471
3.953125
4
peso = float(input("Digite seu peso: ")) altura = float(input("Digite sua altura: ")) imc = peso/(altura*2) if(imc<20): print("Abaixo do peso") elif(imc>20 and imc<=25): print("Peso ideal") elif(imc>25 and imc<=30): print("Sobrepeso") elif(imc>30 and imc<=35): print("Obesidade Moderada") el...
91e92a5aaf939ad7a970b43c0e9ac2984d8c3c80
luiz-vinicius/IP-UFRPE-EXERCICIOS
/lista4_ex_3.py
109
3.796875
4
nome = str(input("Digite o seu nome completo:")) espaço = nome.split(" ") print(espaço[-1],",",espaço[0])
e7c8dc1d1cf897ec181b2ddf648f0cda2b25af14
luiz-vinicius/IP-UFRPE-EXERCICIOS
/while_ex_1.py
523
3.796875
4
qnt_alunos = 0 qnt_altura = 0 while True: idade = int(input("Digite a idade: ")) if(idade<=100 and idade>0): altura = float(input("Digite a altura: ")) if(altura==0): break if(idade>=13): qnt_alunos +=1 if(altura>=1.5): ...
1cab19115488ffde362ca1a725cf79bce4d17030
luiz-vinicius/IP-UFRPE-EXERCICIOS
/if_ex_7.py
247
4.0625
4
v = input("Digite \nM-Matutino \nV-Vespertino \nN-Noturno \n: ") if(v=='M'or v=='m'): print("Bom dia!") elif(v=='V' or v=='v'): print("Boa Tarde!") elif(v=='N' or v=='n'): print("Boa Noite!") else: print("Valor Inválido!")
56aa08c0b985d4c08aba410e2c6f82ce2908be0a
luiz-vinicius/IP-UFRPE-EXERCICIOS
/for_ex_1.py
596
3.59375
4
c = 0 for i in range(10): qnt = int(input("Digite a quantidade itens vendidos pelo vendedor: ")) if(qnt>0 and qnt<=19): c = qnt*0.10 print("A comissão do {}º vendedor será de: {}%".format(i+1,c)) elif(qnt>=20 and qnt<50): c = qnt*0.15 print("A comissão do {}º vendedor...
de9ed90bb6c7ea52a2e457dfcddbe8014ff15f23
JoelsonSartoriJr/study-astronomy
/Nbody/main.py
2,983
3.578125
4
import numpy as np import matplotlib.pyplot as plt from acceleration import acceleration from energy import energy def main(): """ Init simulation N-body parameters""" N = 100 # Number of particles t = 0 # Time of the simulation tEnd = 10.0 # time at which simula...
efc673e72bf226503ca35988255ae723ce7b9071
keerthanachinna/first
/vowel1.py
176
4.125
4
c=input("enter the character") if(c=='a' or c=='A' or c=='e' or c=='E' or c=='i' or c=='I' or c=='o' or c=='O' or c=='u'or=='U'): print (c+,"vowel") else: print(c+,"consoant")
a7e7e5f0d0d6ea259a65432cfb51d99778ec1aa4
kaviyakaviyarasan98/practice
/factorial.py
86
3.671875
4
num=int(input()) i=1 fact=1 while(i<=5): fact=fact*i i=i+1 print(fact)
c4f579fb11e9282776556fe875783bdc04344f59
kanwar101/Python_Review
/src/Chapter07/parrot.py
265
3.921875
4
prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" active = True while active: message = input ("Do you want to Quit? ") if message != 'quit': print (message) else: active=False
7a932affcbd170fa57dcb114ac972460b47e3b54
kanwar101/Python_Review
/src/Chapter08/pizza.py
242
4.09375
4
def make_pizza(size, *toppings): """Print dynamic list of toppings""" print (f"You ordered {size} pizza with following toppings:") for topping in toppings: print (topping) #make_pizza( size='thin crust','olives', 'peppers','onion')
daacca98ea87613f501c1db9e060948ff3e7d018
kanwar101/Python_Review
/src/Chapter06/aliens.py
436
3.953125
4
aliens_0 = {'color':'green', 'point':5} alient_1 = {'color':'blue', 'point':7} alient_2 = {'color':'white', 'point':10} aliens =[aliens_0,alient_1, alient_2] for alien in aliens: print(alien) print("next item in the list") empty_aliens = [] for value in range(0,10): new_alien = {'color':'Orange', 'points':valu...
d2ab2cc50739a52b7a3fcfac1af26f54a621bb07
kanwar101/Python_Review
/src/Chapter11/test_name_function.py
351
3.5
4
import unittest from name_function import get_formatted_name class NameTestCase (unittest.TestCase): """Test for the name funtion""" def test_first_last_name (self): """testing formatted names""" formatted_name = get_formatted_name('Bob', 'Crow') self.assertEqual ('Bob Crow', formatted_name) if __name__ ...
98379659dbbd937bfc5db774006c392ce352f08d
kanwar101/Python_Review
/src/Chapter06/alien.py
739
3.5625
4
alien_0={'key1':'value1', 'key2':'value2','key3':'value3'} print (alien_0['key1']) alien_0['key4'] = 'value4' print (alien_0) empty_dict={} empty_dict['system'] = 'HP' empty_dict['OS'] = 'Chrome' empty_dict['processor']='intel' print (empty_dict) empty_dict['system']='Dell' print (empty_dict) # if loop with dicti...
ded6b6fb5db245ede155d1ceb4f9a67a4c68e0b9
kanwar101/Python_Review
/src/Chapter11/name_function.py
164
3.84375
4
def get_formatted_name (first, last, middle =''): """Print formatted name""" if middle: return f"{first} {middle} {last}" else: return f"{first} {last}"
2790f8ae5a5e897fa6d95dfafd5008c8169f0b53
kanwar101/Python_Review
/src/Chapter04/slice_list.py
151
3.5
4
players = ['bob','dan','steve','reddy'] print (players[1:3]) print (players[-1:]) print (players[-2:]) for player in players[2:4]: print (player)
b976f86e302748c97bcd5033499a0f2a928bcbdc
taddes/python-blockchain
/data_structures_assignment.py
1,053
4.40625
4
# 1) Create a list of “person” dictionaries with a name, age and list of hobbies for each person. Fill in any data you want. person = [{'name': 'Taddes', 'age': 30, 'hobbies': ['bass', 'coding', 'reading', 'exercise']}, {'name': 'Sarah', 'age': 30, 'hobbies': ['exercise', 'writing', 'crafting']}, ...
8820ec93b9d0c2cffea06dca6d832ac02b53996b
marboh1126/homework
/hw-3.py
326
3.71875
4
class Dog: def __init__(self, name, age): self.name = name self.age = age def bow(self): print('bowbowbow') def sayName(self): print('Name: ' + self.name) def sayAge(self): print('Age: ' + str(self.age)) dog = Dog('Masato', 24) dog.bow() dog.sayName() dog.say...
866b64d7ad1da8e45faed0f702565fa0544e12c1
changfenxia/gb-python
/lesson_1/ex_4.py
558
3.9375
4
''' 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. ''' number = input("Введите целое положительное число: ") max = int(number[0]) x = 0 while x < len(number): if (int(number[x]) > max): max = int(number[x]...
0eea84be3a43149c15164ee857b647d8fc7fd08b
changfenxia/gb-python
/lesson_5/ex_6.py
1,395
3.5
4
''' 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета и ...
e1ddd1d2897462bc6d6831993acdd9b9257554b2
changfenxia/gb-python
/lesson_1/ex_2.py
503
4.3125
4
''' 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. ''' time_seconds = int(input("Enter time in seconds: ")) hours = time_seconds // 3600 minutes = (time_seconds % 3600) // 60 seconds = time_seconds - (hours * 3600) - (...
672968de994d9c62f0edb21db7e9339c8bb2a2dd
felipedelta0/URIOnlineJudge
/1010 - URI Online Judge - Solved.py
1,202
3.953125
4
# -*- coding: utf-8 -*- ''' Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago. Entrada O arquivo de entrada contém duas linhas de dados. Em c...
edd4db95c5ca029c1378e16677318becafac984f
Artamamo/hwsys
/hw.py
1,778
3.75
4
import sys str = sys.argv n=0 uppercase = False EnglishCheck = False NumberCheck = False fail = False Check = False try: n=len(str[1]) except: print("請輸入字串") if n<8: print("長度小於8") sys.exit(0) elif n>16: print("長度大於16") sys.exit(0) list1 =list(str[1]) for i in range...
95cbcc07243fb919699df576b9bb1458637ddd49
sroy8091/daily_coding_problem
/find_missing_positive.py
1,039
3.859375
4
""" This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -...
4d22bc86b5997a8b622aebd80dc81a956863a926
RDH06/Python
/28-07-2018classprogram/Some_Process.py
598
3.546875
4
import os def File_to_Listwrds(fname): if not os.path.isfile(fname): return[] wordlst = [] with open(fname,'r') as fob: wordlst = [] for walk in fob: flst = walk.strip("\n").split() wordlst.extend(flst) return wordl...
f4b1f6480bbe645be84bbfc89b23b224bc87435c
kishannerella/CSE537
/P3/submit.py
4,025
3.625
4
#do not modify the function names #You are given L and M as input #Each of your functions should return the minimum possible L value #Or return -1 if no solution exists for the given L #Your backtracking function implementation import time def isSafe(assignments,marker): assignments[marker] = 1 keys = assign...
920f126b9081a52fd2882375de6a026e29470590
teamroke/tessas_first_program
/Tessa.py
378
3.609375
4
import random def get_name(weather): nickname = input('What is your nickname? ') print(f'That is funny, hello {nickname}') print(f'It is {weather} outside!') return nickname for i in range(1,5): print(f'You rolled a: {random.randint(1,20)}') print('argh!') name = input('What is your name? ') print...
255f6298f6215d04542086661c9fb3c8121d7f76
lhotse-speech/lhotse
/lhotse/parallel.py
2,663
3.71875
4
import queue import threading from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor from typing import Callable, Generator, Iterable def parallel_map( fn: Callable, *iterables: Iterable, num_jobs: int = 1, queue_size: int = 5000, threads: bool = False, ) -> Generator: """ ...
56aeca5ce7c3654160344be4329f5a8b821c16f8
shadowleaves/deep_learning
/cnn/tflayer_text_cnn.py
5,843
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Simple example using convolutional neural network to classify IMDB sentiment dataset. References: - Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng, and Christopher Potts. (2011). Learning Word Vectors for Sentiment Analysis. The 49th...
edf5c327f33d0adac1a3638e4f67ab810ad40c7d
shadowleaves/deep_learning
/mxnet/mxnet_binary.py
8,507
3.515625
4
#!/usr/bin/env python import mxnet as mx import numpy as np from rnn import rnn_unroll, DataIter # from minpy_binary import create_dataset, printSample def create_dataset(nb_samples, sequence_len): """Create a dataset for binary addition and return as input, targets.""" max_int = 2**(sequence_len - 1) # Ma...
3bc0d6c4c609c1b412a9f4cc8d0855519079178a
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica06/programa09.py
216
3.796875
4
#Repetição Infinita (Cuidado, pois se a variavel somatorio for = 1; o programa nunca acaba) somatoria = 0 while True: print(somatoria) somatoria = somatoria + 10 if somatoria == 100: break print("Fim")
67878144c8ee495452dbd731515c0858a040c586
guispecian/FATEC-MECATRONICA-1600792021024-Guilherme
/LTP1-2020-2/Pratica11/programa01.py
478
4.0625
4
#Calculo da area do triangulo #Função para calculo do semiperimetro def semiperimetro(a,b,c): return (a+b+c)/2 #Função para calculo da area def area(a,b,c): s = semiperimetro(a,b,c) return (s*(s-a)*(s-b)*(s-c)) ** 0.5 #Programação Principal #Informe os lados A, B e c a = int(input('Informe o valor do lado A:')...
70c81e53b62d9adcedb92dbec0e4d7a2eb4b46e0
anhtu96/algorithms
/sorting/counting_sort.py
586
3.5
4
def counting_sort_1(arr): maxval = max(arr) sorted_arr = [] L = [None] * (maxval + 1) for i in arr: if L[i]: L[i].append(i) else: L[i] = [i] for i in L: sorted_arr.extend(i) return sorted_arr def counting_sort_2(arr): maxval = max(arr) so...
b699ab088ff08f3c0c5c9f6cbb4d2a1564acd528
anhtu96/algorithms
/graph_algorithms/bfs.py
652
3.9375
4
from collections import deque class BFSResult(object): def __init__(self): self.level = {} self.parent = {} def bfs(g, s): """ Queue-based implementation of BFS. Args: - g: a graph with adjacency list adj s.t g.adj[u] is a list of u's neighbors. - s: source vertex. """ r =...
b5ea314bac79c17cc8ff66f43b999cc6a02ac2fb
EliasKassapis/Deep-Learning
/assignment_1/code/mlp_numpy.py
3,136
4.125
4
""" This module implements a multi-layer perceptron (MLP) in NumPy. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from modules import * class MLP(object): """ This class implements a Multi-layer Pe...
b0a0ec721c9f7571a4f294c1b05aa07b3b82c2eb
marcozpina/DevNet
/AgendaTelefonica.py
1,362
4.09375
4
agenda_telefonica = {} while True: print () print ("-------- .: Menu :. --------\n") print ("1.- Ingresar nuevo contacto\n") print ("2.- Eliminar contacto\n") print ("3.- Consultar contactos\n") print ("4.- Salir del programa\n") select = int (input("Selecciona una opcion: ")) print ()...
0ef332e089b580d4c64f222ea88a6c8c0fb6d52e
arinanda/huffman-code-implementation-webapps
/storage/compressor/huffman/adaptive_huffman/adaptive_huffman.py
1,600
3.625
4
from common.util import Node def insert_node(null, char): char_node = Node(char, 1) empty_node = Node(parent=null.parent, left=null, right=char_node) char_node.parent = empty_node if null.parent: if null is null.parent.left: null.parent.left = empty_node else: n...
30da36f468a59b34608639ecf55725b37457a0a1
daniel-paul/Farm-Simulation
/Agent.py
8,522
3.65625
4
import math import copy import random import time from Simulator import Simulator # Main Agent class class Agent: def __init__(self, size, timeLimit): self.simulator = Simulator(size) # Simulator instance of the farm self.monteCarlo = MonteCarloTreeSearch(size) # Instance of the MonteCarloTreeSe...
a098d9405d28447a47f63db41a3500732cd21cb0
roshna1924/Python
/ICP4/sourcecode/naivebayes.py
962
3.75
4
#----------- Importing dataset -----------# import pandas as pd glass=pd.read_csv("glass.csv") #Preprocessing data X = glass.drop('Type',axis=1) Y = glass['Type'] #----------Splitting Data-----------# # Import train_test_split function from sklearn import model_selection # Split dataset into training set and test se...
7cdaebe77cfb044dfc16e01576311244caae283f
roshna1924/Python
/ICP1/Source Code/operations.py
590
4.125
4
num1 = int(input("Enter first number: ")) num2 = int(input("Enter Second number: ")) operation = int(input("Enter 1 for addition\n" "Enter 2 for Subtraction\n" "Enter 3 for multiplication\n" "Enter 4 for division\n")) def arithmeticOperations(op): switcher = { 1: "Result of addition : " + str(num1 + num2),...
bf98bd690471b14034136df54ebe676bb2e5b920
ryanpjbyrne/coffeecode2
/hello.py
90
3.71875
4
print("hello world") fruits= ["apple", "pear", "oranges"] for i in fruits: print(i)
0909e53fa788ef88debd3a3bceb5226b7e371332
vincentGuerlais/matCutPy
/matCutPy.py
2,116
3.546875
4
#! /usr/bin/env python import os import sys #################### ### Get Help #################### # print the help and exit the programm def getHelp() : print """matCutPy help Usage : python matCutPy.py input_file cutoff matCutPy generate a list of IDs with a total of estimated RNA-Seq ...
8d7937fd6aa3583e7c7937587f550f7809ac5f7a
aghyadalbalkhi-ASAC/Game_of_Greed
/game_of_greed/game_logic.py
2,593
3.5625
4
from abc import abstractmethod, ABC from collections import Counter import random class GameLogic(ABC): def __init__(self): pass @staticmethod def calculate_score(tupleInt): rules={ 1:{1:100,2:200,3:1000,4:2000,5:3000,6:4000}, 2:{1:0,2:0,3:200,4:400,5:600,6...
b314f7dbe6ddf2741b5f782b4abecdb9c6fbc5e9
ColinPLambe/MediumWebScraper
/mediumScraper.py
2,567
3.53125
4
from bs4 import BeautifulSoup import requests import sys import os.path """ Colin Lambe A Webscraper to get the number of words, number of claps, and article text from articles on Medium.com Uses BeatifulSoup4 and Requests """ class MediumScraper: def scrape(self, url, minWords, minClaps): #gets the artic...
b749422d017a275cf98d99062a852942d7bd6178
Mara-d/Prototype-sorting-algorithms-with-numbers
/Prototype-Sorting Algorithms/Sorting Algorithms Proto.py
7,294
3.96875
4
import time import random import tkinter as tk from tkinter import * import threading # This is a prototype, seeing numbers getting sorted in real time helps me visualize the algorithms better, # This program is by far finished, this is just a concept # I plan to have an OOP approach in the future window = tk.Tk(clas...
416b79accfdae13f2df358b5b9636403e75b6f62
CxrlosKenobi/cs50
/pset6/Sentimental/readability.py
694
4.0625
4
from cs50 import get_string letters = 0 words = 1 sentences = 0 text = get_string("Text: ") # Here we count the letters in the string for i in range(len(text)): if (text[i] >= 'a' and text[i] <= 'z') or (text[i] >= 'A' and text[i] <= 'Z'): letters += 1 # Here we count the words in the string if text[i] == ' ': ...
3c839f5ce1fc572fc78255520368ea3ef6952a48
vimleshtech/python_sep2
/oops2.py
389
3.53125
4
class emp: #first argument will take add of object #at least one argument need to recieve def newEmp(self): print(self) self.sid =input('etner data :') self.name =input('enter name :') def show(a): print(a) print(a.sid) ...
4626384e435e06e14c4c69eecd3f760a7c03278f
ivapanic/natprog-2019-2020
/Prijemni/KFC.py
1,280
3.640625
4
import sys def main(): m_meat, s_soy, h_bread = map(float, input().split()) pm_kn, ps_kn = map(float, input().split()) if h_bread == 0: max_earnings = 0 print(max_earnings) elif m_meat == 0 and s_soy == 0: max_earnings = 0 print(max_earnings) else: is_there_...
7aa71ae51a60ec0437058f1dbe26e9c8d070764f
BorisBelovA/Python-Labs
/7.1.py
711
3.796875
4
def makeSurnameDict(): my_file = open("students.csv", encoding='utf8') i = 0 dict = {} while True: line = my_file.readline() if(len(line) != 0): #print(line.split(';')) dict[i] = line.split(';') i+=1 else: break dict.pop(0) ...
bfed59521e007e81c2d062b67feed94de0807a3c
BorisBelovA/Python-Labs
/5.2.py
442
3.8125
4
def makeSurnameArray(): my_file = open("students.csv", encoding='utf8') arr = [] for line in my_file: arr.append(line.split(';')) arr = arr[1::1] for elem in arr: elem[3] = elem[3].replace('\n','') return arr def sortSurname(arr): surnamArr = [] i = 0 while(i<len(ar...
800b7e087ff43e689a00fc75a9bf4a0eb76a490c
BorisBelovA/Python-Labs
/4.2.py
162
3.609375
4
import random i = 0 list = [] while (i<10): list.append(random.randint(0,20)) i+=1 print(list) list = list[2::1] list.append(1) list.append(2) print(list)
cf7b22bbb77b7a208a8573982d2f78e05a01f3a8
arpancodes/100DaysOfCode__Python
/day-9/blind-auction.py
899
3.734375
4
from os import system, name from art import logo # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') print(logo) print("Welcome to the silent auction for 'The best painting'"...
1a50d400abbf33d7692ee73d847c7b90b317ab5d
Mahesh-5/Python
/Tic_Tac_Toe.py
3,959
3.90625
4
import random from itertools import combinations class Board(object): def __init__(self): self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)} def display(self): """ Displays tic tac toe board """ d_board = '\nTIC TAC TOE:\n' for pos, obj in self.board.items(): ...
6cae3ccc0e4287a1ff3225051c788e8a8733ebc0
MaryLivingston21/IndividualProject
/Animal.py
598
3.71875
4
class ANIMAL: def __init__(self, name, breed, age): self.name = name self.breed = breed self.age = age def to_string(self): return self.name + ": a " + str(self.age) + " year old " + self.breed + '\n' def get_name(self): return self.name def get_breed(self): ...
6fe0f6441a3135f71e16c2b276a12c957858ccb5
RyanPeking/tkinter
/贪吃蛇.py
5,763
3.5625
4
import queue import random import threading import time from tkinter import Tk, Button, Canvas class Food(): def __init__(self, queue): self.queue = queue self.new_food() def new_food(self): ''' 功能:产生一个食物 产生一个食物的过程就是随机产生一个食物坐标的过程 :return: ''' #...
fb56b8ce1d1987049f9cc36b48efaf0a445d7ecf
seblogapps/coursera_python
/Part 2 - Week 1/MemoryCardGame.py
3,403
3.625
4
# "Memory Card Game" mini-project # Sebastiano Tognacci import simplegui import random # Define constants (can resize canvas if needed) CANVAS_WIDTH = 800 CANVAS_HEIGHT = 100 CARD_WIDTH = CANVAS_WIDTH / 16.0 CARD_HEIGHT = CANVAS_HEIGHT FONT_SIZE = CARD_WIDTH LINE_WIDTH = CARD_WIDTH - 1 # Define global variables deck...
a9bc7c1de42cf3bc67125581a6c8d402faa70ea9
rfolk/Project-Euler
/problem92.py
1,523
3.8125
4
#! /usr/bin/env python3.3 # Russell Folk # July 9, 2013 # Project Euler #92 # A number chain is created by continuously adding the square of the digits in # a number to form a new number until it has been seen before. # # For example, # 44 → 32 → 13 → 10 → 1 → 1 # 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 # The...
e773f8fe3492f330395e0d2c44900b9b96f75b63
rfolk/Project-Euler
/problem65.py
1,050
3.796875
4
#! /usr/bin/env python3.3 # Russell Folk # December 3, 2012 # Project Euler #65 # http://projecteuler.net/problem=65 import time limit = 100 def digitSum ( n ) : """ Adds the sum of the digits in a given number 'n' """ return sum ( map ( int , str ( n ) ) ) def calceNumerator ( term , numeratorN1 , nume...
7994be2f3282be98f6ff2ad6f63a8e18f39a5833
siukwan/python-programming
/network/chapter1/1_13a_echo_server.py
1,111
3.671875
4
import socket import sys import argparse host = 'localhost' data_payload = 2048 backlog = 5 def echo_server(port): """A simple echo server """ #Create a TCP socket sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Enable reuse address/port sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) #Bind...
49893875d1c65cf248f45912a31f9552042b0bd3
sudhasr/Competitive_Coding_2
/TwoSum.py
401
3.625
4
#One pass solution. Accepted on Leetcode #Time complexity - O(n) #space complexity - O(n) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dict1 = {} for i in range(0,len(nums)): if (target - nums[i]) in dict1: return [i,dict1[target-nu...
989514af8deb8d7d68c51f0a1a0983cf04629656
cwormsl2-zz/2PlayerPongGame
/cwormsl2Pong.py
4,268
3.625
4
from Ball import Ball from Paddle import Paddle from graphics import * from time import sleep """ Caitlin Wormsley 12/14/12 This prgorams runs the game Pong while calling a Ball class and a Paddle class. Along with the minimum requirements, this game has a background and is a two player version. """ class Pong: ...
7b4c2a9f79f8876ab091a03d83e10918d7cf358a
chinaglia-rafa/sorting
/classes/QuickSort.py
906
3.578125
4
from Sorter import * from random import randint def partition(lst, start, end, pivot): lst[pivot], lst[end] = lst[end], lst[pivot] store_index = start for i in range(start, end): if lst[i] < lst[end]: lst[i], lst[store_index] = lst[store_index], lst[i] store_index += 1 l...
b2427bd9bf568696217c5e0dd1db531d8472cb5e
kamadforge/ranking
/algorithms/breadth_first_search.py
441
3.9375
4
BFS(v): Q = Queue() Q.add(v) visited = set() visted.add(v) #Include v in the set of elements already visited while (not IsEmpty(Q)): w = Q.dequeue() #Remove a single element from Q and store it in w for u in w.vertices(): #Go through every node w is adjacent to. if (not u...
26cf949e46bd2bb958eca1241fe25beef76bbb1d
kamadforge/ranking
/algorithms/binary_tree.py
1,273
4.25
4
class Tree: def __init__(self): self.root=None def insert(self, data): if not self.root: self.root=Node(data) else: self.root.insert(data) class Node: def __init__(self, data): self.left = None self.right = None self.data = data ...
a64c513cd683163b5596310bf0c15c39b83e2e3d
remnestal/eppu
/keyboard.py
1,007
4.09375
4
import curses class Keyboard(object): """ Simple keyboard handler """ __key_literals = ['q', 'w', 'e', 'f', 'j', 'i', 'o', 'p'] __panic_button = ' ' def __init__(self, stdscr): self.stdscr = stdscr def next_ascii(self): """ Returns the next ascii code submitted by the user """ ...
2185999943f7891d33a7519159d3d08feba8e14d
tim-jackson/euler-python
/Problem1/multiples.py
356
4.125
4
"""multiples.py: Exercise 1 of project Euler. Calculates the sum of the multiples of 3 or 5, below 1000. """ if __name__ == "__main__": TOTAL = 0 for num in xrange(0, 1000): if num % 5 == 0 or num % 3 == 0: TOTAL += num print "The sum of the multiples between 3 and 5, " \ ...
7588f35f10bea6d457e9058d21b41d8fff329fe9
karthik137/tensorflow
/housing_prices_byprice.py
787
3.75
4
import tensorflow as tensor import numpy as np from tensorflow import keras ''' Housing Price Condition One house cost --> 50K + 50K per bedroom 2 bedroom cost --> 50K + 50 * 2 = 150K 3 bedroom cost --> 50K + 50 * 3 = 200K . . . 7 bedroom cost --> 50K + 50 * 4 = 400K ''' ''' Training set to be given xs = [100,...
ac4244195cf8ecf1330621bd31773f3b211f4d5c
HaNuNa42/pythonDersleri
/python dersleri/tipDonusumleri.py
1,286
4.1875
4
#string to int x = input("1.sayı: ") y = input("2 sayı: ") print(type(x)) print(type(y)) toplam = x + y print(toplam) # ekrana yazdirirken string ifade olarak algiladigindan dolayı sayilari toplamadi yanyana yazdi bu yuzden sonuc yanlis oldu. bu durumu duzeltmek için string'ten int' ve...
74d037e74d7f602d96e5c07931ac5f561eab0359
mehoil1/Lesson-10
/News_json.py
726
3.5625
4
import json def ten_popular_words(): from collections import Counter with open('newsafr.json', encoding='utf-8') as f: data = json.load(f) words = data['rss']['channel']['items'] descriptions = [] for i in words: descriptions.append(i['description'].spli...
c62c8cac3dd6d0f918755eea1d4a28c025a4afac
masterfabela/Estudios
/FRMCode/DI/Exame Python/romaymendezfrancisco/MetodosDB.py
2,337
3.53125
4
import sqlite3 try: """datos conexion""" bbdd = 'frm' conex = sqlite3.connect(bbdd) cur = conex.cursor() print("Base de datos conectada.") except sqlite3.OperationalError as e: print(e) def pechar_conexion(): try: conex.close() print("Pechando conexi...
2afdae0bc871c7651934dedb5a6a72e696fef54f
liuyzGIt/python_datastructure_algorithms
/data_structure_algorithms/code/queue_prio_list.py
1,157
3.8125
4
class PrioQueueError(ValueError): pass class PrioQueue: """小的元素优先""" def __init__(self, elems): self.elems = list(elems) self.elems.sort(reverse=True) def is_empty(self): return not self.elems def enqueue(self, item): i = len(self.elems) -1 ...
68372dfabb4a768815176fd77acbab0dca4cfd68
AngelLiang/python3-stduy-notes-book-one
/ch02/memory.py
635
4.28125
4
"""内存 对于常用的小数字,解释器会在初始化时进行预缓存。 以Python36为例,其预缓存范围是[-5,256]。 >>> a = -5 >>> b = -5 >>> a is b True >>> a = 256 >>> b = 256 >>> a is b True # 如果超出缓存范围,那么每次都要新建对象。 >>> a = -6 >>> b = -6 >>> a is b False >>> a = 257 >>> b = 257 >>> a is b False >>> import psutil >>> def res(): ... m = psutil.Process().memory_info() ...
b83d307111992d4dae35a3769afa7e3a26e7d6a4
Man-lu/100DaysOfCodingMorseCode
/MorseCode/main.py
2,110
3.515625
4
from colorama import Fore from data import morse_dict continue_to_encode_or_decode = True print(f"{Fore.MAGENTA}############## MORSE CODE | ENCODE AND DECODE MESSAGES ##############{Fore.MAGENTA}") def encode_message(): """"Encodes Normal Text, Numbers and Some Punctuation into Morse Code""" message = input...
56dd440b18d46fb27786c94f6ba663d8fd29f284
tomjay1/auth
/authcontproject.py
2,546
4.09375
4
#register #-first name, last name, password, email #-generate useraccount #login #-account number and password #bank operation #initialization process import random database = {} #dictonary def init(): print ('welcome to bankphp') haveaccount = int(input('do you have an accou...
2334036ddc243ed0d3befd33a69d030a0d82c215
klq/euler_project
/euler26.py
1,124
3.84375
4
def euler26(): """ Reciprocal cycles: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find th...