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
a0e9066d4433c69851768c7cb3ea5db081199361
koalamadness/intro_git2
/prueba.py
164
3.734375
4
nombre = "" edad = 0 print("Hola Mundo") nombre = input("Nombre completo: ") print("Hola " + nombre) edad = int(input("Edad: ")) print("Vas a cumplir " + str(edad + 1))
6261a0f25df405ad1dc4bae93dc8a6eb8e424791
bizkanta/exam-python-2016-06-27
/test_third.py
755
3.71875
4
import unittest from third import count_letter_in_string class TestCountLetters(unittest.TestCase): def test_empty_string(self): self.assertEqual(count_letter_in_string('', 'a'), (0)) def test_string_letter_in_it(self): self.assertEqual(count_letter_in_string('apple', 'p'), (2)) def test...
b5ddc484b3470d3b751fff6abb6f1a9654bb33e9
rubalravinder/ML_3_Oana_Marie
/notebook/kmeans.py
2,756
3.53125
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np import random import math class KMeans: def __init__(self, k): self.k = k # On attribue des coordonnées aléatoires aux centroids qu'on veut def coord_aleatoires_centroids(self,X,k): '''On génère des coordonnées de...
3cba82c53ab1cf2446947788e91467099adde062
StingzLD/Codecademy
/Computer_Science_Career_Path/CS102/7.Recursion/13.palindrome.py
308
4.0625
4
def is_palindrome(str): if len(str) < 2: return True if str[0] != str[-1]: return False return is_palindrome(str[1:-1]) # test cases print(is_palindrome("abba") == True) print(is_palindrome("abcba") == True) print(is_palindrome("") == True) print(is_palindrome("abcd") == False)
a2ee288db39c26a0d2a982dee6988fc3a3a08a24
StingzLD/Codecademy
/Python3/Code_Challenges/DictionariesAdvanced.py
3,219
4.40625
4
""" 1. Word Length Dict Write a function named word_length_dictionary that takes a list of strings named words as a parameter. The function should return a dictionary of key/value pairs where every key is a word in words and every value is the length of that word. """ # Write your word_length_dictionary function here:...
4a2a5b3377a51d072f79cc6a3866d5e964921fb4
rapomerantz/python_practice
/main.py
5,965
3.828125
4
#Read and Write Files ''' fw = open('sample.txt', 'w') #<--Create an object file & prepare to write to it fw.write('Writing some stuff in my txt file\n') fw.write('Heres a new line') fw.close() #<-- close it (save memory) fr = open('sample.txt', 'r') #<--Create an object that opens a file and reads it text = fr.read()...
d335a2a50a14cd2a6bff8f50eb114473a9f5a3dc
lumo95/python_projects
/word_counter.py
1,238
4.09375
4
# Name: Word Counter # Created By: Luke Molloy # Date: 23/08/16 # Desc: A program that reads a txt file and counts the number of words # then outputs the amount of times a word is used import operator def start(file_name): word_list = [] with open(file_name, "r") as search_file: content = str(search_...
7075fc027419cd12675190b48b59a039bd6e2038
clarasaisse/PI-UFABC
/Processamento da informaçao 2021/semana 2/triangulo.py
611
4.09375
4
import math triangulo = input("Digite os lados do triangulo:") triangulo_split = triangulo.split(' ') lado1 = float(triangulo_split[0]) lado2 = float(triangulo_split[1]) lado3 = float(triangulo_split[2]) if (lado1 + lado2 < lado3) or (lado1 + lado3 < lado2) or (lado2 + lado3 < lado1) or (lado1 + lado2 + lado3 == 0)...
b7424c24bf5a2c018104aac4329855c00d79341d
SubhoBasak/DataStructure
/11_Undirected_Graph/Undirected_graph.py
1,598
3.9375
4
class Vertex: def __init__(self, name, value = None): self.name = name self.value = value self.neighbours = [] def add_neighbours(self, V): if V not in self.neighbours: self.neighbours.append(V) class Graph: def __init__(self): self.vertices = {} de...
23609753606719ed24c2d7ed0bb8f8df54dabc81
SubhoBasak/DataStructure
/01_Singly_Linked_List/Singly_Linked_List.py
13,217
4.21875
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # Node class class node: def __init__(self, value = None): self.value = value self.nxt_node = None # Main linked list class class linked_list: def __init__(self): self.head = None #=================================== ADD ================...
55abc095d625391968f1d764565963db2e1b55ca
ggchappell/AdventOfCode2020
/day22/solve-22b.py
3,086
4.0625
4
#!/usr/bin/env python3 # Advent of Code 2020 # Glenn G. Chappell import sys # .stdin import re # .search # ====================================================================== # HELPER FUNCTIONS # ====================================================================== # A deck is a list in top-...
2b486773466a0a09d71621134fcd8deb1782ab71
ggchappell/AdventOfCode2020
/day20/solve-20b.py
7,391
3.796875
4
#!/usr/bin/env python3 # Advent of Code 2020 # Glenn G. Chappell import sys # .stdin import re # .search import itertools # .product # ====================================================================== # HELPER FUNCTIONS # ====================================================================...
46f68db9b7af033f7267bc6e039fd3029ce93b5e
ggchappell/AdventOfCode2020
/day16/solve-16a.py
2,614
3.96875
4
#!/usr/bin/env python3 # Advent of Code 2020 # Glenn G. Chappell import sys # .stdin import re # .search # ====================================================================== # HELPER FUNCTIONS # ====================================================================== def does_rule_allow_num(ru...
cf9e1e5275751e24a5de9f746a05165a0d4c1c67
Joao-Quinta/Uni3eme_2
/dataMining/TP2_kNN/k_nearest_neighbor.py
3,275
4.15625
4
import numpy as np from distances import * from statistics import mode class KNearestNeighbor(object): """ a kNN classifier with L2 distance """ def __init__(self): pass def train(self, X, y): """ Train the classifier. For k-nearest neighbors this is just memorizing the ...
327a023b058706f7621027cb3ed621e779751523
LHW99/tkinter_test
/images.py
576
3.578125
4
from tkinter import * # to import other image types for python to read from PIL import Image, ImageTk root = Tk() root.title('Image Viewer') # creates a top corner icon. different file types might break img = PhotoImage(file='/home/haiduk/Desktop/prime.png') root.tk.call('wm', 'iconphoto', root._w, img) # adding imag...
3f8c9c1afe9f9cbf86836c6f2e33129af7a1e262
DevKheder/PythonCrashCourse
/introducing-lists/3-4 guest-list.py
539
3.96875
4
# creating a list of guests guests = ["modar", "sara", "samer", "ahmed", "mouhammed"] # printing a message for each item print("Howdyy, " + guests[0].title() + " I would like to invite you for a dinner") print("Howdyy, " + guests[1].title() + " I would like to invite you for a dinner") print("Howdyy, " + guests[2].t...
c29a35afa05fc820ab0e87814494516db38e94a6
Deninc/algorithms
/w8/max_space_clustering.py
2,852
3.8125
4
from collections import defaultdict class DisjointSet(): """Support Union/Find""" def __init__(self, n): """id: list of vertices * note: assuming vertices are numbered between 1 to n size[i]: number of vertices in the tree root i count: number of disjoint sets (tree) ""...
89a55032338f6872b581bbabdfa13670f9520666
Derin-Wilson/Numerical-Methods
/bisection_.py
998
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 4 19:12:56 2020 @author: esha """ # Python program for implementation # of Bisection Method for # solving equations # An example function whose # solution is determined using # Bisection Method. # The function is x^3 - x^2 + 2 def f...
26f6a2e8a2eb6df2c808a014af9973c9b2e2bbde
xingY97/cs-12-intro-to-data-structures-xingY97
/class_worksheet.py
1,159
4.09375
4
#the rooms names and their tempratures rooms = {"Golden Gate":70, "Great Hall":55, "Times Square":40, "Stonehenge":19} def heat_up(room): #it will increase the temp of the room by 5 degrees #find the room in the dictionary, if it's there #add 5 to temp for that room #else return an error #option...
fd13af603b1bb241f989cc0d013aab77014e2f9a
yanzewu/pycsl
/pycsl/util/ioutil.py
1,452
3.640625
4
import sys class StrReader: """ Simple wrapper of string. """ def __init__(self, src): self.obj = src self.ptr = 0 def pos(self): return self.ptr def forward(self, c): self.ptr += c def backward(self, c): self.ptr -= c def seek(self, p): ...
7ecf04e49add86f2b50d4112642bf539e7f43409
boyan13/hackbg-python-101
/week01/03.Fri (Even More Python)/04. Matrix Bombing/task4.py
787
3.71875
4
#Matrix Bombing def build_matrix(rows, cols): matrix = [] n = 1 for i in range(rows): row = [] for j in range(cols): row.append(n) n += 1 else: matrix.append(row) return matrix def matrix_bombing_plan(m): di = {} buf = 0 N = len(m) M = len(m[0]) #or any other index for p in range(N): for...
cb30edd312e386c1234533c3c3c12137f58cfb61
boyan13/hackbg-python-101
/week01/01.Mon (Python Intro)/task9.py
338
3.640625
4
#Sum Numbers in Matrix def sum_matrix(m): msum = 0 for i in range(len(m)): for j in range(len(m[0])): msum += m[i][j] return msum m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] m2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] m3 = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] print( sum_matrix(m1) ) print( sum_matrix(m2) ) print...
f2e9a879e4d54517ca540c06faafefa70324861e
boyan13/hackbg-python-101
/week02/03.Fri (Function Arguments)/03. Collect Fractions/add_fractions.py
1,888
4.03125
4
#Add Fractions from math import gcd #Least Common Multiple def lcm(a, b): if type(a) is not int or type(b) is not int: raise Exception("Non-integer type.") return (a * b) // gcd(a, b) #we want a list with fractions represented by tuples with no more than 2 members def validate_add_fractions_arguments(fractions =...
bcab9c5caf4eda5204d8334f5c375816f657f3f8
antbertrand/ecoclassifier
/classifier_1input/classify.py
1,161
3.734375
4
from keras.models import load_model import numpy as np from keras.preprocessing import image def classify(im, model): """Classifies an image (np array or keras array) See here for difference: https://stackoverflow.com/questions/53718409/numpy-array-vs-img-to-array Parameters: im: nummpy a...
71cce2f350d99d83cfa067dd777b09b0ac26fca5
flxclm/Processos_FelixAlvarez
/Practica4_Debugger/Practica5.py
2,226
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys; class llista_primers: """ Aquest programa és una llista on s'hi afegiràn els nombres prims. L'usuari introduïrà un número i a continuació es mostrarà el nombre de números indicats per l'usuari. TEST: >>> llista_primers(5).llista [2...
ab523e8c9a704bb1ae8072c96332e831dfa7eb6e
annisarac/Python-Projects7-Protek
/latihan/latihan4.py
244
3.796875
4
def shuffleString(x, n): import random for i in range(n): a = list(random.sample(x,len(x))) b = ''.join(a) c = b.split() print(c) shuffleString('aku', 2) shuffleString('aku', 3) shuffleString('aku', 3)
3dd293dcad461e0d14c346d1a0512dcbb2ef6389
Samriddhakc/Algorithms_1
/merge_sort_without_sentinel.py
1,589
3.515625
4
from __future__ import division import math def merge(main_list,lower_bound,mid_point,upper_bound): first_half=main_list[lower_bound:mid_point] second_half=main_list[mid_point:upper_bound+1] #first_half.append(1000000) #second_half.append(1000000) i=0 j=0 counter=0 for running_inde...
afd5deac8b4cd6319611c1170c46338ca049f99a
Samriddhakc/Algorithms_1
/Graph Algorithms /tree.py
2,159
4.0625
4
import time class node: '''a node for any tree ''' def __init__(self,cur_val,right=None,left=None): self.val=cur_val self.right=right self.left=left def get_val(self): return self.val def set_left(self,node_left): self.left=node_left def set_right(self, node_right): self.right=node_right def ge...
62b27a6207f9518fa892b000081947cfd8f24f72
joeryan/MOOC-learn-to-program
/assign1/test_num_buses.py
600
3.703125
4
import a1 import unittest class TestNumBuses(unittest.TestCase): """ Test class for function a1.num_buses. """ def test_less_than_1_bus(self): expect_buses = 1 buses = a1.num_buses(49) self.assertEqual(expect_buses, buses) def test_exactly1_bus(self): expect_buses = 1 ...
c20f3dc3f8e20e8a6339b83b7ba33a314932cb82
dtran-fullstack/Python
/OOP/Store_Products/store.py
1,169
3.703125
4
from product import Product class Store: def __init__(self, name): self.store_name = name self.products = [] #takes a product and adds it to the store def add_product(self, new_product): self.products.append(new_product) return self #remove the product from the store's...
47718ad5817d6945ff8a63c3ee946d114b6457d7
dtran-fullstack/Python
/OOP/TDD/intro_tdd.py
1,871
4.09375
4
# import the python testing framework import unittest # our "unit" # this is what we are running our test on def reverseList(list): for i in range (int(len(list)/2)): list[i], list[len(list) - 1 - i] = list[len(list) - 1 - i], list[i] return list def isPalindrome(word): for i in range (int(len(wor...
b04dee090d6f39bb7ad5a6f31f8a1ad99ada9234
clhking/lpthw
/ex4.py
1,277
4.28125
4
# Set a variable for the number of cars cars = 100 # Set a variable (using a float) for space in each car space_in_a_car = 4 # Set a variable with number of drivers drivers = 30 # Set a variable with number of passengers passengers = 90 # Set up the variable for cars not driven being # of cars minus number of drivers c...
0b4c8d8e9e6e6fb5d5de4526d9a4092cd17770b2
TerrayTM/pytimize
/pytimize/utilities/_disjoint.py
1,498
4.0625
4
from typing import List class DisjointSet: def __init__(self, items: List[str]) -> None: if not len(items) == len(set(items)): raise ValueError("The collection must not contain duplicates.") self._rank = {} self._set = {} for item in items: self._set.setde...
fa34ead8007b433d4396c2f3a4087f4d73dd99e7
TerrayTM/pytimize
/pytimize/formulations/tests/linear/test_variable.py
2,440
3.6875
4
from unittest import TestCase, main from ...linear import variables, x from ...linear._constraint import VariableConstraint from ...linear._equation import LinearEquation from ...linear._variable import Variable class TestVariable(TestCase): def test_variable(self) -> None: a = x[1] b = x[2] ...
ce52c7f03ffa8c860cead0a915cad08e2472dde1
TerrayTM/pytimize
/pytimize/programs/tests/linear/test_verify_infeasibility.py
2,550
3.640625
4
from itertools import product from unittest import TestCase, main import numpy as np from ... import LinearProgram # Test cases for verify_infeasibility (Farkas' Lemma testing) class TestVerifyFeasibility(TestCase): def setUp(self): self.A = np.array([[-2, -1, 0, -1, 0], [1, 1, 2, 0, -1]]) self....
0f72715be7cf314ba7deec8de6f67d16b38d49bd
mhelmih/tubes-daspro
/function/cariRarity.py
1,463
3.859375
4
# Program CariRarity # berisi prosedur untuk melakukan pencarian gadget sesuai rarity def cariRarity(data): def isFound(x): # fungsi IsFound menghasilkan True jika menemukan barang sesuai rarity yang dicari found = False i = 1 while i < len(data) and not found: if data[i]["r...
dc60739f2a1dfc1e09eed18eeb1c3259f871349b
mhelmih/tubes-daspro
/function/validasiTahundanJumlah.py
1,314
3.703125
4
def tahunvalid(tahun): tahuninteger = False tahunstring = str(tahun) panjangtahun = len(tahun) if panjangtahun<=4: i = 0 while i < panjangtahun and not tahuninteger: if tahun[i] not in "1234567890": tahuninteger = True else: i += 1 ...
a88e7a03aa31419e149aca89025e23e7cb4dc007
mhelmih/tubes-daspro
/function/login.py
1,896
3.578125
4
from function.hashing import hash # pylint: disable=import-error def cekSama(nama, listKamus, data): # untuk memeriksa apakah suatu nama sama dengan sebuah value dari data pada array of dictionary count = 0 for i in range (1,len(listKamus)): if (nama == listKamus[i][data]): count += 1 ...
a14e5dad2d88aafc14e3f4e69b0cdcc2071986b1
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 15 (do while)/Desafio 070 (Estatistica em produto).py
1,080
3.8125
4
# Crie um programa que leia o nome e o preço de vários produtos. # O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre: # A) qual é o total gasto na compra. print("{:=^30}".format('MERCADÃO DO ERISU')) soma = maisdemil = maisbarato = c = 0 nomemaisbarato = '' while True: nomeprod = str(i...
3d7c45fb38fd221bca8a9cb22f7509d0106fca65
EricksonSiqueira/curso-em-video-python-3
/Mundo 3 estruturas de dados/Aula 16 (tuplas)/Desafio 074(maior e menor).py
808
4.1875
4
# Crie um programa que vai gerar cinco números aleatório # e colocar em uma tupla. Depois disso, mostre a listagem de números # gerados e também indique o menor e o maior valor que estão na tupla. from random import randint numeros = (randint(0, 20), randint(0, 20), randint(0, 20), randint(0, 20), randint(0, 20)) menor...
d2351e16da03f78e5a8c5d9edcaec95b1e163adb
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 15 (do while)/Desafio 067 (Tabuada v3).py
438
3.96875
4
# Faça um programa que mostre a tabuada de vários números, # um de cada vez, para cada valor digitado pelo usuário. # O programa será interrompido quando o número solicitado for negativo. print('-='*7, 'Tabuada', '-='*7) while True: v = int(input("Deseja ver a tuabuada de qual valor? ")) if v < 0: br...
aacd71d0a5725c4784f9d6e54336c54ed6d4d2eb
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 12 (condições aninhadas)/Desafio 040 (média).py
624
3.90625
4
# Crie um programa que leia duas notas de um aluno e calcule sua média, # mostrando uma mensagem no final, de acordo com a média atingida: # Média abaixo de 5.0: REPROVADO # Média entre 5.0 e 6.9: RECUPERAÇÃO # Média 7.0 ou superior: APROVADO n1 = float(input("Digite sua primeira nota:")) n2 = float(input("Digite sua s...
8a55c35f58b0e598cb6e544df24dcdb02048824c
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 15 (do while)/Desafio 071 (Caixa eletronico).py
1,134
4.21875
4
# Crie um programa que simule o funcionamento de um caixa eletrônico. # No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e # o programa vai informar quantas cédulas de cada valor serão entregues. # OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. print("{:=^34}".form...
906d4238eda704289808ee8c99a5388d10f4c948
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 14 (while)/Desafio 065 (Maior e Menor).py
762
4.15625
4
# Crie um programa que leia vários números inteiros pelo teclado. No final da # execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. r = 's' s = 0 media = 0 maior = 0 menor = 0 c = 0 while r !=...
881fe19ccc18fb6878bd011108403afdd4ec3685
EricksonSiqueira/curso-em-video-python-3
/Mundo 1 fundamentos basicos/Aula 10 (condições 1)/Desafio 033.py
692
3.90625
4
# Faça um programa que leia três números e mostre qual é o maior e qual é o menor. co = {'li': '\033[m', 'vd': '\033[32m', 'vm': '\033[31m', 'az': '\033[34m'} n1 =int(input(f"{co['az']}Digite um número{co['li']}: ")) n2 =int(input(f"{co['az']}Digite um número{co['li']}: ")) n3 =int(input(f"{co['az']}...
31eb6884302b47e19259aa67630937aba75bd76b
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 15 (do while)/Desafio 069 (Analise de dados).py
1,089
4.03125
4
# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, # o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: # A) quantas pessoas tem mais de 18 anos. # B) quantos homens foram cadastrados. # C) quantas mulheres tem menos de 20 anos. maiordeidade = mascul...
0c2143dabcd622319d75a22f5ad725d55d5a9ef4
EricksonSiqueira/curso-em-video-python-3
/Mundo 1 fundamentos basicos/Aula 10 (condições 1)/Desafio 028.py
843
4
4
# Escreva um programa que faça o computador "pensar" em um número inteiro # entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido # pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. from random import randint import pygame pygame.mixer.init() co = {'li': '\033...
b9592d2db51ff82b78534e7b20ed262f63301dd1
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 13 (for)/Desafio 047 (Contagem de pares).py
254
3.75
4
# Crie um programa que mostre na tela todos os números # pares que estão no intervalo entre 1 e 50. i = 0 print('-='*5 + 'Tabela de pares' + '-='*5) for c in range(0, 51, 2): if c > 0: i += 1 print(f"Par[{i}] = {c}") print('=-'*15)
5964ce6a2d6ecff631fc3e07d06a3cdd15078d33
EricksonSiqueira/curso-em-video-python-3
/Mundo 2 estruturas condicionais e de repeticoes/Aula 13 (for)/Desafio 054(Grupo de maioridade).py
517
3.953125
4
# Crie um programa que leia o ano de nascimento de sete pessoas. No final, # mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores. import datetime maior = 0 menor = 0 anoatual = datetime.date.today().year for c in range(0, 7): idade = int(input(f"Digite a idade da {c+1}° pessoa: ")) ...
f796467b2daeaeb9aaf12fe666a0cb7ae611deeb
joelhrobinson/Python_Code
/try_else.py
434
3.75
4
s='hello world' x=2 y=3.5 try: x*y except TypeError: print("An exception was raised") else: print("Thank God, no exceptions were raised.") try: s*y # can't multiply a string times a real # s*1.34 # can't multiply a string times a real # except TypeError: print("An except...
5a693ea54065d8ee521cddb8be003f7f357813bb
joelhrobinson/Python_Code
/object types.py
668
4.25
4
########################## # this is a list mylist = [1, "joel", 2, 'henry', 3, 'Robinson', 4, "Brenda"] print ('mylist=',mylist) mydict = {"mykey":"value", "Name":"Frankie"} print ('mydictionary=',mydict) mytuple = tuple(mylist) print ('mytuple=',mytuple) print (type(mytuple)) ###############################...
eb5ee992c02861ab50546ee49c5c2df18b58bce5
joelhrobinson/Python_Code
/Udemy try_except.py
313
3.984375
4
print ('start') # the the "try" block to handle the exception try: my_list = [] while True: my_list.append(int(input('enter integer: else=stop '))) # if input is not-integer, exit loop and print the list except: print('you entered:', my_list) print ('graceful ending')
cad22588ff6105cf40c18a69f08d6b7affbd077b
baldimort/Trojans-Lucy-Mission
/SAVEFIG.py
892
3.765625
4
import matplotlib.pyplot as plt import time """ This module was used to simplify saving of figures from matplotlib If wou wish to use it, comment out the nulled main() function, uncomment the function below, edit the file path in function to the desired location. When SAVEFIG.main() is called, the two arguments requi...
e9a7f4c9a67e895bfd6fad2aeaee2ffa4426874a
SergioOrtegaMartin/Programacion-Python
/Repaso python segundo/Ej 3 Lista balanza solucion 2.py
226
3.515625
4
def balanza(lista): for i in range(1,len(lista)): if sum(lista[:i]) == sum(lista[i+1:]): return i return None numeros = [9,2,4,1,1,2,1,0] print("Posición central: ", balanza(numeros))
c7796becfd43fdc5339bf2b707390c090a2ed8c9
SergioOrtegaMartin/Programacion-Python
/3er Trimestre/Ej 11/Ej 11.py
2,537
4.15625
4
'''a)Hacer un ejercicio donde se crea una agenda en formato csv Para ello el usuario introduce 3 valores (nombre, tel, email) hasta que el nombre sea una cadena vacia Esta función debe ser un archivo csv que guardaremos como ‘agenda.csv’''' '''b)crear otra funcion (carga)que le paso el nombre de la agenda y me l...
16fdef7bc8914cecdeb0509a9e40dd82ebfe133c
SergioOrtegaMartin/Programacion-Python
/3er Trimestre/Ej 1.py
1,537
4.0625
4
'''Captura de notas por alumnos''' numero_modulos = int(input('¿Cuántos módulos dais? ')) numero_alumnos = int(input('¿Cuántos alumnos hay en clase? ')) def entrada_notas (): lista_total = [] for i in range (numero_alumnos): lista_alumno = [] for j in range(numero_modulos): ...
bf68986ab2b6a70d1ad8c18fe9585c65913eb38c
SergioOrtegaMartin/Programacion-Python
/1er Trimestre/programa_24_dado.py
2,478
3.984375
4
'''definir la funcion dado esta funcion devuelve un numero comprendido entre 1 y 6 b. simular una tirada de dos dados de un jugador de la maquina el programa tiene que decir la tirada de la maquina de los dos dados y la suma maquina: 5 y 5 total: 10 pulsa enter para tirar (enter) jugador: 5 y 6 total: 11 y...
2e76ab58f91e07b538a9f82c477eb321bff33b5c
SergioOrtegaMartin/Programacion-Python
/1er Trimestre/programa_4.py
284
3.984375
4
''' escribir un programa que pida un texto al usuario escriba letra a letra todo los caracteres del texto''' entrada = input('Escribe un texto: ') cadena = entrada contador = 0 while contador < len(cadena): print(cadena[contador]) contador = contador + 1
80398398b0862dc7d9fb257eb0dd29f176606996
SergioOrtegaMartin/Programacion-Python
/1er Trimestre/programa_3.py
238
3.890625
4
''' progrma 3 nos pide un numero escriba los 1000 primeros multiplos de ese numero''' entrada = input('escribe un numero: ') numero = int(entrada) cont = 1 while cont <=10: print(numero*cont) cont = cont + 1
32e92a2d71e59ee5cb00450d745e7bea3d55d937
liamh95/2018_2019
/Spring 19/235C/qmatrix.py
4,632
3.640625
4
from fractions import Fraction class QMatrix: def __init__(self, matrix): good = True n = len(matrix[0]) for row in matrix: if len(row) is not n: good = False break assert good self.shape = (len(matrix), n) self.matrix =...
e82a0d351645c38a97eb004714aae9ab377e13f4
vaelentine/CoolClubProjects
/mags/codewars/get_middle_char.py
1,231
4.3125
4
""" Get the middle character From codewars https://www.codewars.com/kata/56747fd5cb988479af000028/train/python You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 cha...
64a76f211cdbbaa4b04920c3a39606c3ebc1c5d4
ssuhanov/PythonTasks
/Task1.py
263
3.703125
4
a = "First Red Second Green" print(a.split()) print([a[0], a[6], a[10], a[17]]) print(a[-1]) print(a[6:9]) print(a[:5]) print(a[17:]) print(a.find("Second")) print(a[a.find("Second"):]) b = a[::2] print("b = ", b) c = a[1::2] print("c = ", c) print(a[::-1])
902ed3651b3d8b5fb15f43a2d2b299b47c941c85
femkepiepers/Informatica5
/06- Condities/Trolly.py
418
3.953125
4
# invoer hendel_trekken = input('Trek aan de hendel van de wissel? (ja/nee) ') man_van_brug = input('Man van brug duwen? (ja/nee) ') # uitvoer if hendel_trekken == 'ja' and man_van_brug == 'ja': print('2') if hendel_trekken == 'ja' and man_van_brug == 'nee': print('1') if hendel_trekken == 'nee' and man_van_...
feb2b0a9c85d1dd6e9048ea9ad53a664e9044538
femkepiepers/Informatica5
/07a-Iteraties-For-lus/De rij van Fibonacci.py
456
3.796875
4
# invoer getal = int(input('Getal uit de rij van Fibonacci: ')) getal_1, getal_2, = 1, 1 if getal > 2: for i in range(3, getal + 1): getal_3 = getal_1 + getal_2 getal_1 = getal_2 getal_2 = getal_3 print(getal_3) elif getal == 1 or getal ==2: print('1') n = int(input('Hoeveelste...
412d34c0b28f18fe1196280d826c0918806bb65b
femkepiepers/Informatica5
/05- EenvoudigeFuncties/Sommetjes.py
892
3.53125
4
# invoer a = float(input('a: ')) b = float(input('b: ')) from random import random, randint, seed # berekening getal_1 = (10 ** 0) * a getal_2 = (10 ** 0) * b getal_3 = getal_1 + getal_2 getal_4 = (10 ** 1) * a getal_5 = (10 ** 1) * b getal_6 = getal_4 + getal_5 getal_7 = (10 ** 2) * a getal_8 = (10 ** 2) * b getal_...
6042e347ec96bc2e2e640865d588b8d7d70780ee
tthmmts/diff_excel
/diff_excel/helpers.py
1,726
3.546875
4
import difflib import pandas as pd from pathlib import Path def get_dict_data_from_excel_file(file_path: Path, key: str = "") -> tuple: """ Args: file_path: エクセルファイルのフルパス key: IDとなる列の文字 Returns: """ if not file_path.is_file(): raise Exception("{0} というファイルは見つからない".format...
479cb1a7faf455bc8a5884cd561d8e437a0ba596
moguonyanko/pheasant
/pheasant/flask/hello_app/views.py
1,447
3.65625
4
''' 参考 https://code.visualstudio.com/docs/python/tutorial-flask ''' from flask import Flask from flask import render_template import re from datetime import datetime import locale app = Flask(__name__) locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8') @app.route("/") def home(): # return "こんにちは, Flask♪" return...
51b06ab89a0b7a96d973ad14a2a75703697e5d2c
JMBarberio/Penn-Labs-Server-Challenge
/user.py
2,532
4.15625
4
class User(): """ The user class that contains user information. Attributes: ----------- name : str The name of the user. clubs : list The list of the clubs that the user is in fav_list : list The bool list of whether or not a club has been favorite...
28d8559da7a5ae841f40ec7c8695fa52e5a5daa7
noob-cod/DataSturcture-python
/Tree/Heap.py
8,843
4.25
4
""" @Date: 2021/4/9 下午1:37 @Author: Chen Zhang @Brief: 堆 的实现 堆的定义: 堆的特性: """ import abc class Heap(abc.ABC): """堆的抽象类""" def __init__(self, sourceCollection=None): self._container = [None] # 堆容器 self._size = 0 # 堆尺寸 self._top = None # 堆顶 self._bottom = None # 堆尾 i...
8e465a23e4b42689df81233a901515fb1c4c3981
klinetek/Python-Mastery
/TimesTables.py
140
3.96875
4
for i in range (1,13): for j in range (1,13): print ("{0} times {1} is {2}".format(j,i,i * j)) print("===================")
b3d817f95f4949ebaedc5db87e1d40375f84f3cf
klinetek/Python-Mastery
/Modules/filesanddirectories.py
916
3.8125
4
import os """this program searches and displays things neatly to the console so you wouldn't actually need that stuff in a real application. This could be reused in a sorting program or maybe even looking for recursive data in a file lookup system. or not, i do't really know what's goign on mostly haha""" def list_di...
d45f824944ccb0c7385bd09984117676fa4c288e
pwexler/xml2py
/xml2py/xmltodict.py
2,105
3.953125
4
""" XmlToDict """ import collections import re class XmlToDict(object): """Convert an xml element to a python dict. >>> python_dict = XmlToDict().element_to_dict(xml_element) """ def __init__(self, attrib_prefix='_', text_key='_text_', namespace_pattern=r'\{.*\}', ...
6b4aa15ef521397c90e32b0cb2a33bf0f02bc100
daktari01/phonebook_app
/tests/test_phonebook.py
1,360
3.953125
4
import unittest from phonebook import Phonebook class TestPhonebook(unittest.TestCase): def setUp(self): """Initialize variables that will be used""" self.contact1 = Phonebook() def test_add_contact(self): """Test whether user can add a contact""" self.contact1.add...
7d1e821072a7cc422e3668fa0c9b691ec0f26c15
sugaigit/mypython_project
/Anagram.py
165
3.796875
4
def anagram(w1, w2): w1 = w1.lower() w2 = w2.lower() return sorted(w1) == sorted(w2) print(anagram("iceman", "cinema")) print(anagram("leaf", "tree"))
e265136982b65c81b1ab91342198385cdc6da99a
hilts-vaughan/daily-programmer
/20161207/program.py
1,219
3.609375
4
import string from collections import Counter def get_word_score(word): i = 1 total = 0 for c in word: total = total + (score_map[c] * i) i = i + 1 return total def best_word_given_tiles(tiles): best = ('', 0) for entry in word_scores: word = entry[0] if can_for...
0f95c193f3045f06c55c5e78dbeab3925f547d71
antdon/MontyHallSimulator
/montyhall.py
849
3.65625
4
from random import * import pdb class Montyhall: def __init__(self, swap, guess): self.doors = [1,2,3] self.car = self.doors[randint(0,2)] self.swap = swap self.guess = guess def runGame(self): self.doors.remove(self.guess) if self.swap == True: if ...
866497428117b9a5fa19b3519607eb232c2f60a0
sammienjihia/data-structures-python
/linked_list.py
10,499
4.125
4
""" This is an implementation of a singly linked list in python Resources used: 1. LucidProgramming on youtube: https://www.youtube.com/watch?v=FSsriWQ0qYE&list=PL5tcWHG-UPH112e7AN7C-fwDVPVrt0wpV&index=5 """ # Create a class node with the data and next pointer variables class Node: def __init__(self, data): sel...
5887dfa898cd6123ec527ba3c88b32e8f8a634d7
Ricardo-oli/Projeto-3-
/At4.py
495
3.71875
4
pessoas = 0 alt_inf = 0 alt_ent = 0 alt_sup = 0 for pessoas in range(10): altura = float(input('Altura: ')) if altura < 1.6: alt_inf += 1 elif 1.8 >= altura >= 1.6: alt_ent += 1 else: alt_sup += 1 print(f'Total de pessoas cadastradas {pessoas+1}.') print(f'Pessoa...
acc007262e2ab1261b5db371b3c1a3a1523b939e
mohankumart/algos
/codingInterview/rotateMatrix.py
2,205
3.734375
4
from sys import stdout def rotateMatrix(my_array, matrix): loopend = matrix-1 loopstart = 0 looplength = matrix - 1 left = 0 right = 0 while looplength >= 1: for mainloop in range(looplength): temp1 = my_array[loopstart][loopstart] temp2 = my_array[loopstart][lo...
f1eb501015d2edd264b14a633c7fb8037758aa68
rheehyerin/programming_hw
/t_memoize_1.py
503
3.53125
4
import time cached_1 = {} def mysum(x, y): key = (x, y) if key not in cached_1: time.sleep(1) cached_1[key] = x + y return cached_1[key] cached_2 = {} def mymultiply(x, y): key = (x, y) if key not in cached_2: time.sleep(1) cached_2[key] = x * y return cached_...
817d35dd6ee95282807850ca348a78528516beed
jhill57/Module-4-Lab-Activity-
/grading corrected.py
1,553
4.4375
4
# Calculating Grades (ok, let me think about this one) # Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing. # Average Grade # 90+ A # 80-89 B # 70-79 C # 60-69 D # 0-59 F # Exams: 89, 90, 90 # Aver...
460171d20c880de8e084084a16a30c2ab51140c4
tanyajain0018/Tic-Tac-Toe
/tic-tac-toe.py
14,415
4.15625
4
# CS-UY 1114 # Final project import turtle import time import random import ctypes the_board = [ "_", "_", "_", "_", "_", "_", "_", "_", "_"] def draw_board(board): """ signature: list(str) -> NoneType Given the current state of the game, draws the board on...
f9b43c0440e26658ccaf485dff4cde80e19cb61b
uci-physics-231/examples
/dynamic.py
405
3.84375
4
class Particle(object): def __init__(self,mass): self.mass = mass electron = Particle(0.511) proton = Particle(938.0) print 'electron mass is',electron.mass print 'proton mass is',proton.mass # add an attribute to one object without affecting other instances of the same class electron.spin = 0.5 print 'electron ...
c2f3612c792941e5165f220a596fd6499fef26e6
paulmureithi/simple-password-generator
/main3.py
760
3.890625
4
"""writing to files""" def bio(): filename = 'mybio.txt' with open(filename, 'w') as f: f.write('Ladies and gentlemen, a short story about me...') def your_bio(): filename = 'user.txt' user = input('Describe yourself in 5 words...') with open(filename, 'w') as f: f.write(user) ...
4662599440b62da6738848621dcb1b410f9457da
ErikLobato/Exercicios-Python
/Exercícios Python/Exercícios Tuplas/73 exer.py
590
3.96875
4
print('\nExercicio 72') print('Campeonato brasileiro\n') t = ('Flamengo', 'Atlético', 'São Paulo', 'Internacional', 'Grêmio', 'Palmeiras', 'Sport Recife', 'Cruzeiro', 'Botafogo','Corinthians', 'Vasco', 'Fluminence', 'América', 'Chapecoense', 'Santos', 'Vitória', 'Bahia', 'Paraná', 'Atletico', 'Ceará') print('O...
b91af0f3bfaf5ec8058a9b8566e05eb19210e61d
nonabsorbing/python-challenge
/pybank/main.py
3,474
4.34375
4
# In this challenge, you are tasked with creating a Python script for # analyzing the financial records of your company. You will give a set of # financial data called budget_data.csv. # The dataset is composed of two columns: Date and Profit/Losses. # (Thankfully, your company has rather lax standards for accounti...
1b48abeed7454fea2a67ed5afc2755932e093d32
CTEC-121-Spring-2020/mod-6-programming-assignment-tylerjjohnson64
/Prob-3/Prob-3.py
521
4.125
4
# Module 7 # Programming Assignment 10 # Prob-3.py # <Tyler Johnson> def main(): number = -1 while number <0.0: x = float(input("Enter a positive number to begin program: ")) if x >= 0.0: break sum = 0.0 while True: x = float(input("Enter a pos...
5d7f747bd14e3f1e4d62676fe8af3f1eb3f646c9
nickpetzold/python-mega-course
/beyond-the-basics/password_checker.py
202
3.578125
4
password = 'hello' user_try = input('Enter your password: ') while user_try != password: print('That is wrong!') user_try = input('Please try again: ') print('Welcome to the portal! 🚀')
0570b7dc20cb9014dcc929dae0d1af1353ba9491
tlpss/ML_course
/labs/ex04/template/build_polynomial.py
579
4.0625
4
# -*- coding: utf-8 -*- """implement a polynomial basis function.""" import numpy as np def build_poly(x, degree): """polynomial basis functions for input data x, for j=0 up to j=degree.""" # *************************************************** # this function should return the matrix formed # by appl...
a86b9a8f5b2a7d944edade86c1c4df946e1a981a
leon0241/adv-higher-python
/command-line.py
300
3.734375
4
import os a = False print("Leon's python CMD loophole") print("Commands: cd change") while a == False: print(":)", end=" ") x = input() if x == "cd change": y = input("Enter the directory to change to: ") os.chdir(y) os.system("cd") else: os.system(x)
c9804338656ff356407de642e3241b44cc91d085
leon0241/adv-higher-python
/Term 1/Book-1_task-6-1_2.py
659
4.28125
4
#What would be the linked list for.. #'brown', 'dog.', 'fox', 'jumps', 'lazy', 'over', 'quick', 'red', 'The', 'the' #... to create the sentence... #'The quick brown fox jumps over the lazy dog' linkedList = [ ["brown", 2], #0 ["dog.", -1], #1 ["fox", 3], #2 ["jumps", 5], #3 ["lazy", 7], #4 ["ov...
907c008de30d2238a729f5245af0623721d5f96e
leon0241/adv-higher-python
/Project Euler/Resources/prime_algorithms.py
1,225
4.21875
4
import math def find_primes(n): #Finds primes below n primeList = [2] for i in range(3, n, 2): primeList.append(i) #Makes array of odd number to number n(even numbers are not prime) for i in range(3, (int(math.sqrt(n)) + 1), 2): #cycle for i = 3 for j in primeList: if j...
b56a066a3e11ed1e8e3de30a9ed73c35975e8c2e
leon0241/adv-higher-python
/Pre-Summer/nat 5 tasks/task 6/task_6a.py
218
4.1875
4
name = input("what's your name? ") age = int(input("what's your age? ")) if age >= 4 and age <= 11: print("you should be in primary school") elif age >= 12 and age <= 17: print("you should be in high school")
c94e3f427997fe5be7f77b13e64f09e761a2ae19
leon0241/adv-higher-python
/Pre-Summer/nat 5 tasks/task 7/task_7a.py
260
4.09375
4
result = int(input("what percentage did you get? ")) if result >= 90: print("you got an A") elif result >= 80: print("you got an B") elif result >= 50: print("you got an C") elif result >= 40: print("you got an D") else: print("you fail")
863665ae07cf02fb2bed6edd0d962b9428b3ea7c
leon0241/adv-higher-python
/Pre-Summer/nat 5 tasks/task 12/task_12e.py
110
3.71875
4
import math pinum = math.pi places = int(input("how many decimal places of pi")) print(round(pinum, places))
342c01a20ff276cc20ffd71e9130af74d4a11f36
leon0241/adv-higher-python
/Project Euler/03 - Largest prime factor.py
872
3.625
4
#The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? import math import Resources.prime_algorithms as palgs value = 600851475143 primeList = [] primeFactors = [] def find_factor(value, list): #Finds the prime factor maxVal = 0 #Max value = 0 for i in ...
084a1156daa91106722db94b55652654fe4a113c
thortoyo/study
/ABC167/A.py
107
3.6875
4
S=input() T=input() if (T[0:len(T)-1] == S) and ( len(S) +1 == len(T)): print("Yes") else: print("No")
83885b3de61379caefe662625555a1f596046e8d
thortoyo/study
/ABC212/A.py
110
3.546875
4
a,b=map(int, input().split()) if a==0: print("Silver") elif b==0: print("Gold") else: print("Alloy")
b9ac69cfe55027cd2226aac90023810f76a98767
thortoyo/study
/m_solutions2020_a/A.py
239
3.640625
4
a=int(input()) if a >= 1800: print("1") elif a >= 1600: print("2") elif a >= 1400: print("3") elif a >= 1200: print("4") elif a >= 1000: print("5") elif a >= 800: print("6") elif a >= 600: print("7") else: print("8")
6f6822ddfe4a50e8a76d22407f0a1b5a6e30e712
Midnight-Sighs/RPSLS
/game.py
6,705
3.703125
4
from human import Human from ai import AI class Game: def __init__(self): self.gestures = ["rock", "paper", "scissors", "lizard", "spock"] self.game_type = "" self.game_rounds = 3 self.rounds_to_win = 2 def welcome_message(self): print( "Are you ready for t...