blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2909c7baca3f265c9ba5c4f2b1f9171d6cb51a4b
DanilooSilva/Cursos_de_Python
/Curso_Python_3_UDEMY/desafios/desafio_dia_semana.py
273
3.515625
4
def get_dia_semana(dia): dias = { (1, 7): 'fim-de-semanda', tuple(range(2, 7)): 'semana' } dia_escolhido = (tipo for numero, tipo in dias.items() if dia in numero) return next(dia_escolhido, '** dia inválido ***') print(get_dia_semana(2))
f374c8b57722d4677cbf9cc7cde251df8896b33d
sreerajch657/internship
/practise questions/odd index remove.py
287
4.28125
4
#Python Program to Remove the Characters of Odd Index Values in a String str_string=input("enter a string : ") str_string2="" length=int(len(str_string)) for i in range(length) : if i % 2 == 0 : str_string2=str_string2+str_string[i] print(str_string2)
6896c8dc7af0a4dde9d561c5347454b039aa5b10
FreekDS/Discord-Bot
/chess/chess_base.py
1,338
3.84375
4
import enum from abc import abstractmethod class Position: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): x = self.x + other.x y = self.y + other.y return None if (x or y) not in range(0, 8) else Position(x, y) def __str__(self): ...
acc1c4163d2fa38824203e725076c9f8d5068888
komotunde/DATA602
/Homework 2 (Cars Data Set).py
3,264
4.09375
4
#1. fill in this class # it will need to provide for what happens below in the # main, so you will at least need a constructor that takes the values as (Brand, Price, Safety Rating), # a function called showEvaluation, and an attribute carCount class CarEvaluation: """A simple class that represents a car evaluatio...
c3ba85a5be209b6ce186b54b22a49a4cc6259010
Confidential-Innovation/Algorithm
/Searching_Algorithm/Binary Searching.py
1,451
3.859375
4
# Binary Searching- 1 ''' def binary_search(L,i): left, right = 0, len(L)-1 while left <= right: mid = (left + right)//2 # integer divison if L[mid] == i: return mid if L[mid] < i: left = mid + 1 else: right = ...
6cb9c313594341112ecea9b3d69968361ce0ff10
dls-controls/dls-pmac-lib
/dls_pmaclib/dls_pmaclib.py
887
4.09375
4
class HelloClass: """A class who's only purpose in life is to say hello""" def __init__(self, name: str): """ Args: name: The initial value of the name of the person who gets greeted """ #: The name of the person who gets greeted self.name = name def for...
cd239ed588f11605897aca695473bc918093190f
zzhyzzh/Leetcode
/leetcode-algorithms/130. Surrounded Regions/solve.py
1,644
3.828125
4
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ if board == []: return def search(i, j): if j not in range(len(board[0])) or i not in range...
e0284f68c706a251380ee31163352c26e9ab8571
MatheusTostes/simular-triangulos
/(TKINTER) Identificando tipos de triângulo.py
6,929
4.1875
4
# O objetivo aqui era criar uma interface grafica que pedisse 3 entradas, rodasse condições dizendo se esses 3 valores # poderiam formar um triangulo, em caso afirmativo, devolver as classificações do triângulo e plotar uma representação # do mesmo em escala reduzida. # Resultado: https://i.imgur.com/5I6uX21.png f...
64fc1baed6b18f12360b3ad341730637cc486ca5
wwzz1/Wilson-s
/Scylla.py
1,556
4
4
from fractions import Fraction from math import pi #1 def mixed_number(a,b): x=str(a//b) y=str(a%b) b=str(b) z=x+" "+y+"/"+b return z print(mixed_number(5,2)) #2 def vowel_count_1(x): num=0 for char in x: if char in "aeiouAEIOU": num+=1 return num print(vowel_count_1(...
4f09e5225ff0ecbfc6d24767be5cd5805f37155b
wandesky/codility
/lesson03TimeComplexity/TapeEquilibrium/solutionA.py
788
3.625
4
''' Failed complexity test, the code below returt O(N*N) yet the question wants O(N) ''' # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 lengthy = len(A) if (lengthy == 0 or lengthy == 1): return 0 ...
6e9ea7f5ad4272c66654137d67a8509a97b9cc65
Kimyechan/codingTestPractice
/programmers/queueAndStack/다리를 지나는 트럭.py
1,032
3.546875
4
from collections import deque def solution(bridge_length, weight, truck_weights): answer = 0 bridge_line = deque([0] * bridge_length) current_truck = [] while True: current_weight = 0 if bridge_line.popleft() != 0: if current_truck: current_truck.pop(0) ...
47a0b1fb4c75deae9e591d1ebe8a5c415b0e6e46
Trigl/Recommender-System-Learning
/Chapter1.py
972
3.640625
4
# 推荐系统评分预测准确度指标:均方根误差(RMSE)和平均绝对误差(MAE) # records[i]=[u,i,rui,pui],测试数据:records = [['haha',1,3.2,3],['hehe',2,2.5,2]] from math import sqrt def RMSE(records): return sqrt(sum([(rui-pui)*(rui-pui) for u,i,rui,pui in records]))/float(len(records)) def MAE(records): return sum([abs(rui-pui) for u,i,rui,pui in records])...
f378064cf7c91da51eacdbf933382d8a36053c31
ParanoidAndroid19/Common-Patterns_Grokking-the-Coding-Interview
/6. In-place reversal of Linked List/3_Reverse k node sublist.py
1,360
3.828125
4
class Node: def __init__(self, data, next=None): self.data = data self.next = next def reverseKSublist(head, k): current = head prev = None while True: i = 1 node_before_sublist = prev last_node_sublist = current temp = None ...
46879a3bb3c2c47c3e7408816eda150becfdc725
brunopesmac/Python
/Python/curso/ex45.py
388
3.65625
4
from random import randint cpu = randint(1,3) player = int (input("JO KEN PO\n1 pedra\n2 papel\n3 tesoura\n")) if cpu == player: print ("EMPATE!") elif cpu == 1 and player == 2 or cpu == 2 and player == 3 or cpu == 3 and player == 1: print ("VOCÊ VENCEU!") elif player == 1 and cpu == 2 or player == 2 and...
f0957036ea33120d2001adb75ba33f877cb8439e
EnthusiasticTeslim/MIT6.00.1x
/other/gcdIter.py
560
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 16 20:43:48 2019 @author: olayi """ def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if a < b: init_d = a else: init_d = b while a...
7c70d9ed04ecae63c3f0dfa073045dd23da415ae
daniel-reich/ubiquitous-fiesta
/dqJYvDRTyXzQPGimc_19.py
135
3.578125
4
def is_unfair_hurdle(hurdles): if len(hurdles) > 3: return True if len(hurdles[0].split('#')[1]) < 4: return True return False
cbc1c82e42e5e5b61b1be878efddb00757818a52
calebe-takehisa/repository_Python
/procedural_programming/ex013.py
537
3.71875
4
""" Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. SAÍDA: Qual é o salário do Funcionário? R$4319.43 Um funcionário que ganhava R$4319.43, com 15% de aumento, passa a receber R$4967.34 """ # Minha solução: salario = input('Qual é o salário do Funcionário? ...
266e2012071b9e3c272ef5504f395685488a8f05
DiasVitoria/Python_para_Zumbis
/Lista de Exercícios I Python_para_Zumbis/Exercicio10.py
333
3.75
4
cigarrosDia = int(input("Informe a quantidade de cigarros fumados por dia: ")) anosFumando = int(input("Informe os anos fumando: ")) totalDia = (anosFumando * 365 * cigarrosDia * 10)/1440 print('O total de dias perdidos será de: %.2f' %totalDia, 'dias') print ('2 elevado a 1 milhão tem %i digitos' %len(str(2**1...
9832ce0a1de701b7c77bb270a91037f1d25c9484
andresnunes/Projetos_Python
/Projetos_Python/Exercicios-Livro-PythonForEverybody/9Ex1.py
569
4.0625
4
''' Exercise 1: Download a copy of the file www.py4e.com/code3/words.txt Write a program that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary. ''' value = 0 di = di...
44cee04bddae4273e7adf178c93442c0605d5886
knight-byte/Codeforces-Problemset-Solution
/Python/AntonAndPolyhedrons.py
294
4.03125
4
def main(): sides = {"tetrahedron": 4, "cube": 6, "octahedron": 8, "dodecahedron": 12, "icosahedron": 20} n = int(input()) ans = 0 for _ in range(n): shape = input().lower() ans += sides[shape] print(ans) if __name__ == '__main__': main()
34dcc5df5e4d6498245d448b580f05f936d537c4
BXGrzesiek/HardCoder
/pythonBasics/Exam/exam3.py
2,049
4.0625
4
from os import system, name from time import sleep # -----------VARIABLES-------------- # x = 0 shopping_list = [] ballance = 100.0 shopping_cart = '' product_costs = dict() choice = 'y' # -----------FUNCTIONS-------------- # def removeDuplicates(shopping_cart): for i in shopping_cart: if i not in sho...
80c7e417f7afb9ba58e4470e7048e37f268e706e
aravindanath/TeslaEV
/Assignment/TaxCalculation.py
238
3.6875
4
x=int(input("Enter the gross Income:")) y=int(input("Enter the percentage of State tax: ")) z=int(input("Enter the percentage of Central tax: ")) totaltax=y+z a=(totaltax/100)*x netincome=x-a print("The Net income is:" + str(netincome))
389843f2c1dc0312c93a54f594639045c534bd98
memelogit/python
/module2/listas - range.py
212
3.78125
4
# RANGE # ------ # Creando rangos rango = range(1, 3) rango = range(3, 30) rango = range(2, 10, 2) # Tipo de dato range print(type(rango)) print(rango) # Imprimiendo la secuencia de un rango print(list(rango))
be993cc8710c0c2a8fe30d476838d5aab78176c1
ivanjankovic16/pajton-vjezbe
/Excercise 2a.py
220
4.125
4
print('Enter a number.') number = input() if int(number) % 4 == 0: print('This number can be divided by 4.') elif int(number) % 2 == 0: print('This is an even number.') else: print('This is an odd number.')
5596002695f1af0443e4c19596516cc34c69a60e
zwarburg/exercism
/python/kindergarten-garden/kindergarten_garden.py
692
3.859375
4
class Garden(object): def __init__(self, diagram, students=['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry']): self.rows = map(lambda row: list(row), diagram.split()) self.students = students def plants(self, student): plant...
66651b416b99aac1ddfa8c88591535d9d6c52964
dmontag23/mars-rovers
/test/test_create_rovers.py
5,902
3.625
4
import unittest from rovers.create_rovers import CreateRovers from rovers.point import Point from rovers.terrain import Terrain class TestCreateRovers(unittest.TestCase): ''' Tests the CreateRovers class. ''' def test_create_command_from_user_input(self): input_string = "MLRMMRL" self....
3b91b9060bea612cb1456b921d46db1a0001850a
kaichimomose/CS1
/Roulette_noclass.py
5,115
3.6875
4
import random # x = random.randint() random.seed(1) # from random import randint # x = randint() # from random import randint as r # x = r() bank_account = 1000 bet_amount = 0 bet_color = None bet_number = None bet_even_odd = None green = [0, 37] red = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, ...
7f4a41eab2cb6edd2ad5ba794baf18e8b840ab9c
philipenders/Mission_To_Mars
/m2m.py
7,086
3.890625
4
import random """The crew is made up of character objects""" class Crew(object): def __init__(self, full_crew_b=True): if full_crew_b: self.crew_roles = full_crew_list else: self.crew_roles = limited_crew_list self.full_crew = {} for role in self.crew_role...
e31da3ad567769dd36d4a9a84d9ebf239b8736c6
hkapp/ML_course
/labs/ex02/template/costs.py
427
3.71875
4
# -*- coding: utf-8 -*- """a function used to compute the loss.""" import numpy as np def compute_loss(y, tx, w, lossf = "MSE"): """Calculate the loss. You can calculate the loss using mse or mae. """ e = y - tx.dot(w) if (lossf == "MSE"): return (1 /(2 * y.shape[0])) * e.T.dot(e) el...
ffd8299ff4b1b1fe997a4e789e3d90cbf64238ed
Mallik-G/dataload
/sample/record_generator.py
2,681
3.53125
4
""" Sample record generator to be used on data-load. """ import sample.randomize class SampleRecordGenerator(): """ Class used to generate a sample record to data load. """ def __init__(self, args, configs): self.configs = configs['sample'] self.fields = self.configs['fields'] ...
3ef92f613e7b27e4e7120b43788c696913932bee
courtneyng/Intro-To-Python
/Mad-Libs/Mad-Libs.py
1,577
4
4
# Program ID: Mad-Libs # Author: Courtney Ng # Period 7 # Program Description: Making a mad lib based on the string functions adj = input("Please input an adjective. ") noun = input("Please input a noun. ") verb = input("Please input a verb. ") place = input("Please input a place. ") line1 = "After the upri...
d68cab75e1f20ae09c2f37a297e2224bf6712e57
KojoEAppiah/kata-pencil-durability
/kata-pencil-durability/Pencil.py
2,811
3.625
4
class Pencil(): def __init__(self, durability, length, eraser_durability): self.paper ="" self.initial_durability = durability self.durability = durability self.length = length self.eraser_durability = eraser_durability self.last_erased = None self.erased_pos...
eda6f93d61ec1f2aa864a029fb07e6e1df58200a
jerinsebastian521/python
/Cycle 5/C5.4 time.py
563
4
4
class Time: def __init__(self, hour, minute, second): self.__hour = hour self.__minute = minute self.__second = second def __add__(self, other): return self.__hour + other.__hour, self.__minute + other.__minute, self.__second + other.__second a = int(input("enter 1st hour")) ...
5081b58e0ee599dacd81afd5d2a61a0c316ed4c1
LITiGEM/Simulation
/Game of LIT/gameOfLIt.py
1,713
3.71875
4
import numpy as np import random #-------------------------------------------------------- # Object #-------------------------------------------------------- class Agent: #defining a new class to provide the standard features, agent is the "player of the Game of Lit" def __init__(self, A,B,C,D,E): #function to d...
ddd2a50ebff12e5b030cd9a2ecfba1e66c2322c6
Icode4passion/practicepythonprogams
/even_odd.py
245
4
4
numbers = [1,2,3,4,5,6,7,8,9] count_even = 0 count_odd = 0 for number in numbers: if number % 2 == 0: count_even = count_even+1 else : count_odd = count_odd + 1 print "Count Even:", count_even print "Count Even:", count_odd
bc74b00a2d29957bbf21ed92da0daf306e2692bd
vesso8/Tuples-and-Sets
/01. Unique Usernames.py
137
3.546875
4
n = int(input()) unique_names = set() for _ in range(n): names = input() unique_names.add(names) print(*unique_names, sep= "\n")
0ae1660aa6e48f85b462ebdb30265f8fd20f3ab0
alf808/python-labs
/09_exceptions/09_04_files_exceptions.py
2,121
4.15625
4
''' In this exercise, you will practice both File I/O as well as using Exceptions in a real-world scenario. You have a folder containing three text files of books from Project Gutenberg: - war_and_peace.txt - pride_and_prejudice.txt - crime_and_punishment.txt 1) Open war_and_peace.txt, read the whole file content and...
232fbc19ecd77515d260f6d0f653f73ffb84551e
nguyenhuudat123/lesson8
/bt8.py
153
3.6875
4
_2tuple = (4,6,9,0,0,0,0,0) k = 1 for item in _2tuple: if _2tuple[0] != item: k = 0 break print('giong all') if k == 1 else print('khong giong all')
4e689bb332deffdbd2f719c48f2e6291d57718e7
tylermargetts/05-Space-Shooter
/main1.py
5,819
4.1875
4
""" Move with a Sprite Animation Simple program to show basic sprite usage. Artwork from http://kenney.nl If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.sprite_move_animation """ import arcade import random import os SCREEN_WIDTH = 800 SCREEN_HEIGHT...
887b4ac4bfdc18cd0625a736e7c9733a18e92c5e
KalsaHT/lc_practice
/array_python/33.py
1,806
3.625
4
# -*- coding: utf-8 -*- """ @time: 2017/8/24 @author: leilei """ class Solution1(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if nums == []: return -1 try: ret...
c72e226d15a142db283a666d8826575a806fe424
CaveroBrandon/TicTacToe
/TicTacToe_V1.py
4,652
3.75
4
# Tic tac toe game, not ussing IA, just random numbers # This version doesnt have a UI from random import randint import sys global empty_spaces empty_spaces = {} def restart_game(): global empty_spaces empty_spaces = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7...
38f2e24de60d0de1c0d5f67a66f2fc77f34ffd1c
reynoldscem/aoc2017
/05/2.py
682
3.65625
4
from argparse import ArgumentParser from itertools import count def build_parser(): parser = ArgumentParser() parser.add_argument('filename') return parser def main(): args = build_parser().parse_args() with open(args.filename) as fd: data = fd.read().splitlines() jumps = [int(ent...
0d1f41169ca3b57df82e69470ea71a94a69f2084
pauldedward/100-Days-of-Code
/Day-20&21&24/snake_Game/snake.py
2,022
3.625
4
from turtle import Turtle, xcor STEP_SIZE = 20 class Snake: def __init__(self): self.make_snake() def make_snake(self): self.body = [] for i in range(0, 3): todd = Turtle() todd.penup() todd.color("white") todd.shape("square") ...
416d60e0178ef549f42aa00553b9910d0090e6b9
sharmasaravanan/Machine_learning
/pythonCourse/module-8.py
1,358
4.25
4
# functions # no arg no return def operation(): a = int(input("Enter any number :")) b = int(input("Enter any number :")) print(a+b, a*b) operation() # no arg with return def operation(): a = int(input("Enter any number :")) b = int(input("Enter any number :")) return a+b, a*b s,m = operati...
98bc247babc9be6d9ce316e94ef4ccd67e175c31
chittella369/LearnPython
/ForLoops.py
222
3.796875
4
friends =["Jim","Carrey","Tom","Steve","Arnold"] #range = len(friends) for index in range(5): if index==0: print("first iteration") else: print("not first") #print(friends[index]) #friends.
a24d7ca0d6bed29ffb079916d15dd6501ff24922
salmasalem99/Sorting-Algorithms
/s1.py
4,700
4.03125
4
'''Merge Sort''' def merge(array,s,m,e,length): temparray =[0]*length index1=s index2=m+1 i=s z=0 while i <= e: z=i if index1==(m+1): while z <= e: temparray[z]=array[index2] index2+=1 z+=1 elif ind...
762ed37e8da2d117515002119c370faf5a693c0b
Raj-kar/Python
/Project/rock_paper_scissors_v3.py
896
4.09375
4
from random import randint while True: print("\n..... rock .....\n..... paper .....\n..... scissors .....") user1= input("\nEnter player 1's Choice :: ").lower() rand_num=randint(0,2) if(rand_num==0): comp="rock" elif(rand_num == 1): comp="paper" elif(rand_num == 2): comp="scissors" print(f"Computer ...
f557a9a8473d20f46db32667e40da90dbabce2a3
atikhasan2090/newton-s-divided-difference-formula
/diivided difference.py
764
3.75
4
#Newtons Divided difference formula n = int(input("Enter the number of data in dataset : ")) li = [[0 for i in range(n)]for i in range(n+1)] for i in range(n): li[0][i] = int(input("enter the value of x{} : ".format(i))) li[1][i] = int(input("enter the value of y{} : ".format(i))) x = int(inpu...
d1fc075ca8ccdaf22f23698607fa5a01954e82d1
Basstma/PathfindingAlgorithmWithPygame
/solver.py
16,519
3.8125
4
from maze import Maze from linkedlist import Node, NodeGraph from graph import Graph, Edge from threading import Thread import time class Solver: def __init__(self, maze: Maze, target): """ Basic Class for an Solver, that soves the maze :param maze: :param target: """ ...
219e4b12d647c28e5472d07ccf113e778a389bcb
camarena2/camarena2.github.io
/name_generator.py
460
3.734375
4
import random first = ("Amy", "Bob", "Billy", "Ben", "Alyssa", "Natalie", "Mari", "Christian", "Cora", "Lalo", "Joel", "Eric", "Erika", "Eugene", "Mazikeen", "Linda", "Chloe", "Benneth") second = ("James", "Kerry", "Mate", "Camino", "Flotando", "Botella", "Tableta", "Mesa", "Madera", "Dolbiniak", "Jenski", "Spy", "Ana...
de470ea20490a21a145eeb812ce64d5221d985c8
nushrathumaira/Fall2017102
/newlab3/lab3sol/is_sorted.py
343
4.15625
4
import sys # python is_sorted.py <input_file> with open(sys.argv[1], "r") as numbers: arr = [] for line in numbers.readlines(): arr.append(int(line)) if all(a <= b for a,b in zip(arr[:-1], arr[1:])): print("List of " + str(len(arr)) + " integers is sorted!\n") else: print("Lis...
3db5cf86a97f92af30e9c032c8b6f738f4fa6e97
elenakaba/First_task_Ventilation-start_of_second
/with_rooms.py
3,797
3.59375
4
import math import matplotlib.pyplot as plt from shapely.geometry import Point from ventilation_coverage import VentilationCoverage from vent_body import VentBody from building import Building def plot_shape_graphics(shape): _x, _y = shape.exterior.xy plt.plot(_x, _y) def create_and_plot_vent...
810a16454af623da8ccca0ac6d47e16de273bf12
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2_neat/16_0_2_Duy_revenge-of-the-pancakes.py
1,449
3.796875
4
#!python2.7 # Standard libs import argparse def get_min_flips(stack): if not stack or '-' not in stack: return 0 # Truncate the happy bottom of the stack last_blank_index = stack.rindex('-') part_we_still_need_to_flip = stack[:last_blank_index + 1] # If the top of the stack is blank, we ...
6df12eeedf2576ffa1172f783f848f8c7286ef88
dalexach/holbertonschool-machine_learning
/supervised_learning/0x13-qa_bot/1-loop.py
419
4.25
4
#!/usr/bin/env python3 """ Create the loop Script that takes in input from the user with the prompt Q: and prints A: as a response. If the user inputs exit, quit, goodbye, or bye, case insensitive, print A: Goodbye and exit """ cases = ['exit', 'goodbye', 'bye'] while True: ans = input('Q: ') ans = ans.lower(...
47d9ef2eb60adbe870fa4d9f23427dbfa9d7f282
LucasLeone/mochila-de-recursos
/ex4.py
422
3.9375
4
""" Determinar la palabra mas grande (indicar criterios) """ print('El criterio para determinar la palabra mas grande es por la cantidad de letras.') texto = input('Ingrese un texto: ') palabras = texto.split(' ') mayor = 'a' for i in range(0, len(palabras)): if i == 0: mayor = palabras[0] ...
76a395da2ef8ad2df665a088cb06254063d93dcc
mohitgaggar/BullsandRights
/game.py
1,017
3.6875
4
a=input("Enter the string") s=list(a) import os def cl(): os.system('cls') flag=False cl() count=0 k=[] q=[] while flag!=True and count<len(s)*3: print("Guess a",len(s),"letter word") string=input() if string=='igiveup': print("The word was:",a) break if len(s)!=len(string): print("Please en...
0e9d57bfa49325be30cb66a9194aab74a2ffa9b1
NielXu/algo
/greedy/shortest_path.py
1,563
4.21875
4
""" Problem: Shortest path Find the shortest paths from a given vertex to all other vertices in the graph G. Ideas: We can solve this problem by the Dijkstra's algorithm. Running Time: O(|V|*|E|) where V is vertices and E is edges Addition: The following implementation uses list and dict for storing data. A better ...
ae13e64db7916ad89052f5bf6901771f5b91303d
stagadimples/hangman
/hangman.py
997
3.71875
4
import random class Hangman: words = [ 'keyboard', 'comb', 'apple', 'table', 'house', 'bulldozer', 'hat', 'window', 'glue', 'bed', 'sticker', 'computer', 'snake', ] incorrect = 0 def wordChoice(self...
0564aa8eab4631210b6426b0b7233ed8c804ac58
tomaszkajda/wdi2020-2021
/wdi1/cw3.py
670
3.921875
4
#Zadanie 3. Proszę napisać program sprawdzający czy istnieje spójny podciąg ciągu Fibonacciego o zadanej #sumie. sum = 20 first1 = 1 first2 = 1 current1 = 1 current2 = 1 result = 1 #suma podciągu if result != sum: while result < sum: result += current2 #dodajemy wyraz z prawej strony cu...
091b1538b90818390967896c38806e01c4122389
pocokim/algo
/python/elice/chapter2/mission/1_findDifference.py
1,802
3.703125
4
def findDifference(str1, str2): dic= {} for ch in str2: dic[ch] = dic.get(ch,0) + 1 # for ch in str2: # if ch not in dic : # return ch # 딕셔너리만 가지고 if문을 사용할 수 있을까? : z와 같은 다른 원소가 포함된 경우 사용가능 할 수 있지만 , 추가된 원소가 p일경우 잡을 수 없다고 생각함. for ch in str1: if ch in dic...
45e2de7458ac70d042da70772157af3382c5d58c
TestAnalyst1/python-challenge
/PyBank/main.py
3,065
3.828125
4
import os,csv from pathlib import Path # Path to collect data from the Resources folder budget_data_csv = os.path.join("budget_data.csv") # def print_bankdata(dataRow): # # The total number of months included in the dataset # # total_no_of_months = len(dataRow[0]) # # print (" The total number of months...
68ab3477e173475bfa13ac9a59d762aaa100333a
TOFUman404/Python
/Hello.py
875
3.921875
4
d=int(input()) h=int(input()) m=int(input()) if d == 1: day = "sunday" if d == 2: day = "monday" if d == 3: day = "tuesday" if d == 4: day = "wednesday" if d == 5: day = "thursday" if d == 6: day = "friday" if d == 7: day = "saturday" if (h == 4 and m > 0 or h > 4 and h < 12 or h == 12 an...
bcaaa34ea1bcb4ccac269ac3f7bc20a0552a90db
derekjanni/derekjanni.github.io
/pyocr/app.py
1,525
3.578125
4
import flask from sklearn.linear_model import LogisticRegression import numpy as np import pandas as pd #---------- MODEL IN MEMORY ----------------# # Read the scientific data on breast cancer survival, # Build a LogisticRegression predictor on it patients = pd.read_csv("haberman.data", header=None) patients.columns...
201bd8e0c439acd8e10847460b89fd459ca293ea
charanchakravarthula/python_practice
/lists.py
1,250
4.21875
4
# nuemeric data types int float and complex integer_var=-1 float_var=1.0 complex_var=1+2j print(type(integer_var),type(float_var),type(complex_var),sep="\n") # playing with list # creating an empty list list_var=[] # creating a list with some values list_var2=[1,2,'a'] # adding elements to a list list_var2.a...
9d76bd12cfc6b0faf8fd3158e5db4908ac5117bc
silviordjr/exercicios-python
/contaSegundos/conta_segundos.py
375
3.78125
4
segundos = int(input("Por favor, entre com o número de segundos que deseja converter: ")) dias = segundos // (3600 * 24) segundos = segundos - dias * (3600 * 24) horas = segundos // 3600 segundos = segundos - horas * 3600 minutos = segundos // 60 segundos = segundos - minutos * 60 print(dias, "dias, ", horas, "h...
d4f2ceff37d2b801cbb554d13f4c3c8b4c6982c7
alewang/Projects
/python/numbers/next-prime.py
324
3.765625
4
#!/usr/bin/env python import primes primeList = []; index = 0; keepGoing = True; while keepGoing: inp = raw_input("Enter q to quit: "); if inp == 'q': keepGoing = False; else: if index == len(primeList): primes.genPrimes(primeList); print primeList[index]; index += 1; print "Program complete. Exiting....
8837f0ec30cae7dde823c85add9c5ceee14d1da1
conanjm/Introduction-to-Computer-Science-and-Programming-Using-Python
/Problem-Set-1/countingBob.py
260
4.0625
4
''' prints the number of times the string 'bob' occurs in s ''' s = 'bobobobbob' counter = 0 for s1 in range(0,len(s)+1): for s2 in range(s1,len(s)+1): if s[s1:s2] == "bob": counter += 1 print 'Number of times bob occurs is:', counter
931d0ac4d8f5a209c03a4ae36e1bddcb64f426fc
RubenBS7/Cuatro-en-linea
/src/CuatroEnLinea.py
6,309
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import math import sys import numpy as np import pygame #instalar numpy y pygame para interfaz de las matrices y la interface grafica (mediante la consola de comandos) # pip install numpy y pip install pygame NUM_FILA = 6 NUM_COLUMNA = 7 AMARILLO = (242, 230, 12) R...
5fba451353d1d134d7e57b4c6b99c5e2fbe1ecd0
Hegemony/Python-Practice
/LeetCode practice/Other/501.findMode.py
693
3.71875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def findMode(self, root: TreeNode): if not root: return [] # 第一想法是哈希表记录 ...
abf9de670d9119e77b0ff6fc6081b13d6e06ff23
mottaquikarim/pydev-psets
/pset_loops/loop_basics/p4.py
335
4.34375
4
""" Factorial """ # Find the factorial of a number input by a user. Then print out the factors within the factorial and then print out the actual numeric answer. Hint: The formula for a factorial is n! = (n-1)*n. # Example output: """ 8! = 8*7*6*5*4*3*2*1 8! = 40320 """ user_input = input('Enter a number to find it...
5995d45cefcd88ffd2b1b4b123dfe427b4aae063
tarantot/Final_task
/add_to_final_task_DB.py
1,109
3.8125
4
import sqlite3 import datetime def add_to_final_task_DB(): for personal_ID = 0: personal_ID+=1 emp_age = datetime.emp_bdate - datetime.date.today() emp_sex = emp_sex.upper() if emp_sex is not 'М' is not 'Ж': print('Пожалуйста выберите корректное значение!') for emp_phonenumber != 0:...
ade282e3ba387f4fb1bf31a56f78a22b42862e0e
nisacchimo/challenge
/ch6_2.py
223
3.875
4
#http://tinyurl.com/hapm4dx word1 = input("昨日書いたものは?:") word2 = input("送付した人は?:") message = "私は昨日、{}を書いて{}に送った!".format(word1,word2) print(message)
b415872dca06c52afa8b64b54d28ea709a06723d
frclasso/python_examples_two
/newtontest.py
131
3.71875
4
#!/usr/bin/python from newton import * print("Enter a number: ") number = int(input()) print(sqrt(number)) print(average(144, 9))
d73d39936d5cd96467423de8e7d2fcdc6718d17b
bluella/hackerrank-solutions-explained
/src/Arrays/Arrays: Left Rotation.py
1,066
4.71875
5
#!/usr/bin/env python3 """ https://www.hackerrank.com/challenges/ctci-array-left-rotation A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1, 2, 3] then the array would become [3, 2, 1] Given an array of integers and a...
456fe93eb9e3d9e3d3f94538c1c0afd1c2734b77
rafaelperazzo/programacao-web
/moodledata/vpl_data/10/usersdata/61/10344/submittedfiles/testes.py
192
3.984375
4
# -*- coding: utf-8 -*- from __future__ import division import math a=input('Digite o valor de a: ') if (a%3)==0: print ('a é multiplo de 3') else: print ('a não é multiplo de 3')
5ad20eef5ff45a3903c5fed3ed2f669bd99cac70
facufrau/beginner-projects-solutions
/solutions/magic_8ballgui.py
2,986
4.40625
4
# Beginner project 3. ''' Simulate a magic 8-ball. Allow the user to enter their question. Display an in progress message(i.e. "thinking"). Create 20 responses, and show a random response. Allow the user to ask another question or quit. Bonus: Add a gui. It must have box for users to enter the question. It ...
04a6ad3fe0df6cc55e995b105e9704d8350b8670
tayabsoomro/CMPT317-GroupProject
/A1/src/unique.py
965
3.703125
4
import copy """ UniqueHashable class implementation. UniqueHashable implemented due to requirements of uniqueness of states in Python dictionaries. Particular classes can be made unique hashable by hashing the arguments, keyword arguments, and class itself. Authors: Mahmud Ahzam*, Tayab Soomro*, F...
019ba9d216414b5bd2f7ea60c0ca379727c547ed
TorNATO-PRO/WA_COVID_DATA_TRACKER
/data_grabber.py
2,059
3.734375
4
from os import getcwd from os import mkdir from os import path import requests # Downloads a file from a url, saves it in # a specified directory within the working # directory with a given name def download_file(url, directory, name): # tries to get the requested file, exits if unable to do so try: ...
4a745dfc1a77fbff7346144809cd39018a62829c
cymerrad/aoc
/2019/1.py
543
3.578125
4
#!/usr/bin/python3 fuel_sum = 0 def fuel_for_mass(mass): fuel = mass//3 - 2 if fuel < 0: return 0 return fuel def true_fuel_for_mass(mass): if mass <= 0: return 0 req = fuel_for_mass(mass) return req + true_fuel_for_mass(req) with open("input1") as fr: for line in fr: ...
1400e7ec35a3ca827e6bc3c1a52804dc1e2936a7
thiagorangeldasilva/Exercicios-de-Python
/pythonBrasil/03.Estrutura de Repetição/03. validar nomes.py
2,181
4
4
#coding: utf-8 """ Faça um programa que leia e valide as seguintes informações: Nome: maior que 3 caracteres; Idade: entre 0 e 150; Salário: maior que zero; Sexo: 'f' ou 'm'; Estado Civil: 's', 'c', 'v', 'd'; """ cont = 'a' x = 0 z = 0 n = "A" i = 151 s = 0 sx = "d" es = "a" lf = "S - solteira, C - casada, V - viúva ou...
ae62bb8dda951933e3c902a2f381486bc739158c
lonelycloudy/python_study
/13.8.1-iter.py
589
3.71875
4
#!/usr/local/python/bin/python #-*-coding:utf-8-*- for element in [1,2,3]: print element for element in (4,5,6): print element for key in {'one':1,'two':2}: print key for char in "789": print char for line in open("/tmp/a.log"): print line """ 1 2 3 4 5 6 two one 7 8 9 The third line:is wri...
807d57cd8d1420d99e5463db3863f515648a05c2
Louis192/Python_Challenge_1
/function3.py
375
4.28125
4
# The code below will read a file and print out a count of each name inside the file list_of_names=[] def Name_count(): for line in open('file3.txt').readlines(): list_of_names.append(line.strip()) count_names=list(set(list_of_names)) for name in count_names: print(name + ' occurred ' + ...
6bd0e283186e09d270aaaddc31449de810b3b5fc
EvgeniyBudaev/python_learn
/ cycles/cards_sum/cards_sum.py
517
3.796875
4
# Мой вариант current_hand = [2, 3, 4, 10, 'Q', 5] total = 0 for x in current_hand: if x == 2 or x == 3 or x == 4 or x == 5 or x == 6: total += 1 elif x == 7 or x == 8 or x == 9: total += 0 elif x == 10 or x == 'J' or x == 'Q' or x == 'K' or x == 'A': total += -1 print(f'total: {total}') # Реш...
c2eec19443e8762f7f55b047067a289ab7b18503
NikhilDusane222/Python
/FunctionalPrograms/primeFactorization.py
341
4.125
4
# Prime factorization number=int(input("Enter the number :")) def prime_factor(number): prime_factors=[] while number>1: for factor in range(2,number+1): if number%factor==0: number=number//factor prime_factors.append(factor) return prime_factors print(...
331213255a2597eb5cdb2e55a174c08cc847e1f4
Roiw/LeetCode
/Python/258_AddDigits.py
310
3.5625
4
class Solution: def addDigits(self, num: int) -> int: if num <= 9: return num while num > 9: answer = 0 while num > 0: answer += num % 10 num = num // 10 if answer > 9: num = answer return answer
edb4d4315bce6c406928bc63853f24e919ed880e
stephenmcnicholas/PythonExamples
/progs/SudokuChecker.py
456
3.8125
4
row = ' ' lst = [] valid = True while(len(row)>0): #print(lst) row = input("Enter a row of nine digitsm then ENTER (or just ENTER to finish): ") if(row.isdigit()): lst.append(row) if(len(lst)<9): valid = False else: for elem in lst: for i in range(1,10): if(elem.find(st...
86d8c9b80943d5e739da6b5f9792250657a8616e
TardC/books
/Python编程:从入门到实践/code/chapter-5/favorite_fruits.py
429
4.0625
4
favorite_fruits = ['apple', 'banana', 'watermelon'] if 'apple' in favorite_fruits: print("You really like apples!") if 'banana' in favorite_fruits: print("You really like bananas!") if 'watermelon' in favorite_fruits: print("You really like watermelons!") if 'orange' in favorite_fruits: print(...
4c775a9b6a4a7eaf172a4441b079607904b7cc5b
Gchesta/assignment_day_4
/find_missing.py
250
3.765625
4
def find_missing(list_1, list_2): #creating sets set_1 = set(list_1) set_2 = set(list_2) if set_1 == set_2: return 0 #return the symmetric difference and then converts it into a list else: return list((set_1 ^ set_2))[0]
7b5286c3ed8e9a13bca49af60d01075ffb0fb44c
trvsed/100-exercicios
/ex046.py
279
3.65625
4
from time import sleep start=str(input('Digite "começar" sem aspas para iniciar a contagem: ')).lower() .strip() if start == 'começar': for c in range(10, -1,-1): print(c) sleep(1) print('Feliz ano novo!!!') else: print('Entrada Inválida!')
410436994d50c3b996e5791d3c62a10affc8a697
NikitaFedyanin/python_tests
/other/lamp_time.py
1,954
3.875
4
"""На вход функции дан массив datetime объектов — это дата и время нажатия на кнопку. Вашей задачей является определить, как долго горела лампочка. Массив при этом всегда отсортирован по возрастанию, в нем нет повторяющихся элементов и количество элементов всегда четное число (это значит, что лампочка, в конце концов...
5b9d25bce6edad29ac3a31c4f2cc65e6e5ea9691
jcastillo7/GP_PRML_demos
/bayesdemo.py
9,732
3.65625
4
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt def gaussian_process_demo(n=2,m=1000,fits=10): """ Using a gaussian process we can evaluate the weights across all measurements but we cannot plot the most probable weights as they change for each location predicted. Thi...
b61d3276ade3f2d4a460ca6c6f11195364cc9e37
CompetitiveCode/hackerrank-python
/Practice/Regex and Parsing/Validating and Parsing Email Addresses.py
456
4.0625
4
#Answer to Validating and Parsing Email Addresses import email.utils import re for i in range(int(input())): b=input() a=email.utils.parseaddr(b) if bool(re.match(r'^[A-Za-z]{1}(\w|_|-|\.)*@[A-Za-z]+\.[A-Za-z]{1,3}$',a[1])): print(b) """ Code: import email.utils print email.utils.parseadd...
2e199536d4c40fad344064e2cea9a0ae052c673c
Rishi05051997/Python-Notes
/2-CHAPTER/Practice/01_add.py
111
3.90625
4
a = int(input('Enter first number')) b = int(input ('enter second number')) print("The value of a+b is ", a+b)
90e47d3694a3513e46572b5f6f75fd8e509cabe5
yusufibro/upload-project
/luas.py
3,092
3.578125
4
import math import sys def hitung_luas_lingkaran(): print("Menghitung luas lingkaran") radius = int(input("jari-jari = ")) luas = 22 / 7 * radius * radius print(("Luas= "), luas) def hitung_luas_persegi_panjang(): print("Menghitung Luas Persegi Panjang") panjang = int(input("panjang= ")) ...
ce72f9758d200b5689dc491a5c886d827db99162
SalvaJ/Python-Examples
/es_entero.py
189
3.734375
4
#!/usr/bin/env python import math def es_entero(x): x = abs(x) x2 = math.floor(x) if (x2 - x) >= 0: return True else: return False print es_entero(-3.2)
0e9223c587570cf3920b25605658eaca59c5cfc3
mmetsa/PythonProjects
/ex02_binary/binary.py
1,136
4.09375
4
"""Converter.""" import math def dec_to_binary(dec: int) -> str: """ Convert decimal number into binary. :param dec: decimal number to convert :return: number in binary """ list_bin = [] if dec == 0: list_bin.append(0) while dec != 0: list_bin.append(dec % 2) d...
9de50d067eb3029451cd60634500c6c8df30ae65
Alwayswithme/LeetCode
/Python/073-set-matrix-zeroes.py
1,122
3.84375
4
#!/bin/python # # Author : Ye Jinchang # Date : 2015-06-24 17:58:33 # Title : 73 set matrix zeroes # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. class Solution: # @param {integer[][]} matrix # @return {void} Do not return anything, modify ma...
96ca3a7ed14fe1358aef074d620b4ed77b167393
farrukhkhalid1/100Days
/Day22/scoreboard.py
848
3.703125
4
from turtle import Turtle FONT = ("Arial", 30, "normal") ALIGNMENT = "center" class Scoreboard(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.score_left = 0 self.score_right = 0 self.hideturtle() self.update_score() ...
d8a327600ba9f209850f80ee7611ece158b0e786
liberbell/py08
/cal.py
638
3.5
4
import calendar import math import random cal = calendar.month(2019,10) print(cal) result = math.sqrt(49) print(result) number = random.randint(1, 100) # print(number) state1 = 0 state2 = 0 state3 = 0 state4 = 0 state5 = 0 for i in range(1000): number = random.randint(1, 5) # print(number) if number == 1...
25064d3c6a782c27b726de5d41de79295a33e8e0
aish2028/stack
/s2.py
272
3.6875
4
def searchLinear(lst,ele): index= -1 for i in lst: if i == ele: return index index += 1 return -1 ele=6 res=searchLinear([1,2,3,4,5,6,7,8],6) if res == -1: print(f"{ele} is not found") else: print(f"{ele} is found at:{res}")