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
19e6db1b7bc873f5c10ff4d6d43c80ad005ae7df
HasithaAthukorala/sumitpython
/HistogramWaterContent.py
3,796
3.71875
4
import sys LEFT = 1 RIGHT = 2 def findIndexOfMax(ls): if len(ls) == 0: return -1 elif len(ls) == 1: return 0, ls[0] # index is 0 pos else: max = ls[0] # print 'Max ' + str(max) # print 'ls ' + str(ls) for i in ls[1:]: if i > max: max = i return ls.index(max), max def getArea(ls, leftOrRight): ...
d94ce0c24eccbdea5fca04b259583e50e3dedb17
Dynatrace/dynatrace-api
/third-party-synthetic/third-party-tester/tests/test.py
2,069
3.5625
4
from datetime import datetime import logging class Test: """ A base class for test definitions. To create a concrete test one should derive this class and fill its 'steps' field, which contains TestStep objects that encapsulate test step logic. """ TEST_ARGUMENTS = [] """ Additional...
9de6d50bce515e0003aaff576c3c92d04b162b9d
chandanakgd/pythonTutes
/lessons/lesson6_Task1.py
1,513
4.125
4
''' * Copyright 2016 Hackers' Club, University Of Peradeniya * Author : Irunika Weeraratne E/11/431 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-...
39514047f6a039f5ac04ed612febfd8e087da5c4
htphan16/datawrangling
/run_pymongo.py
8,074
4.53125
5
""" Your task is to sucessfully run the exercise to see how pymongo works and how easy it is to start using it. You don't actually have to change anything in this exercise, but you can change the city name in the add_city function if you like. Your code will be run against a MongoDB instance that we have provided. If ...
6a0c9526c14dd7fb71a9ba8002d3673e7da8b29b
yangzhao1983/leetcode_python
/src/queue/solution225/MyStack.py
1,512
4.125
4
from collections import deque class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.q1 = deque() self.q2 = deque() def push(self, x): """ Push element x onto stack. :type x: int :rtype: None ...
721fe05fb4fe54d2f82475ce785212a34dda5467
yangzhao1983/leetcode_python
/src/tree/solution111/Solution.py
835
3.75
4
from src.tree.TreeNode import TreeNode class Solution(object): def __init__(self): self.depth = 0 def minDepth(self, root): """ :type root: TreeNode :rtype: int """ return self.get_depth(root) def get_depth(self, root): if not root: retu...
3083b47c98863aed57fda0b3c0d302dc377e1b5b
Grecota/le-wagon-exercises
/le-wagon-exercises/hello-world/hello.py
586
3.609375
4
# pylint: disable=missing-docstring # Here is what you need to do: # 1. Write some code below # 2. Save to disk with Ctrl + S (Windows) or Cmd + S (Mac) # 3. Run the code print("Hello World !") age = 21 #Variable assignment print (age) #one year passes age = (age + 1) #Variable re-assignment #Shortcut version...
a6583a7ce979cf00853f1d716134ffc8515bc549
wonwick/data-structures
/tree.py
307
3.546875
4
class Node: def __init__(self,Data): self.data=Data self.left=None self.right=None class Tree: def __init__(self): self.root=None def add_node(self,Data): n=Node(Data) current=self.root cuurent def travers(self):
7ee1a1ee9cbb1e4ef99df5d49c3d24d7e59cccaa
yatharthahuja/Prediction-of-Steering-Angle-using-Throttle-and-Road-Angle-Values-for-Vehicle-Control
/Image_feature_extraction_beta.py
3,061
3.78125
4
# PREPROCESING CODE # Program to read the images from data set and generate a vector for road angles corresponding to each image. # This vector will be used as a parameter in training the regression model. # The model obtained will then be used to preedict steering angles using polynomial regression. import matplotlib...
8391c86a5a14cb4c50bd0b5f3c3d0ad85101888a
AlexMazonowicz/PythonFundamentals
/Lesson09/solution/validate_email_utils.py
986
4.0625
4
# Importing user-defined exception from Lesson09.solution.UserDefinedException import EmailNotValidError def is_email_valid(mailing_list): """ This function validates whether the email addresses in the current mailing list are valid emails. To be considered a valid email, for the purpose of...
a8467024224b66dfcb623a8f41d4d7f33d0db241
AlexMazonowicz/PythonFundamentals
/Lesson09/problem/problem_validate_email_utils_optional_part1.py
1,122
3.765625
4
# Import library to work with regex patterns # Import user-defined exception def is_email_valid_optional_regex(mailing_list): """ Your docstring documentation starts here. For more information on how to proper document your function, please refer to the official PEP8: https://ww...
a657612ac1dbce789b2f2815e631ffad2a8de060
AlexMazonowicz/PythonFundamentals
/Lesson2.1/solution/urlvalidator_solution.py
1,040
4.28125
4
import requests def validate_url(url): """Validates the given url passed as string. Arguments: url -- String, A valid url should be of form <Protocol>://<hostmain>/<fileinfo> Protocol = [http, https, ftp] Hostname = string Fileinfo = [.html, .csv, .docx] """ protocol_valid = True valid_pro...
1570f3bee2c39199745fb642ebf582bcfdc57732
zwmtrue/CompInvest
/HWs/HW5/Bollinger_val.py
3,078
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed May 11 22:43:28 2016 @author: William Part 1: Implement Bollinger bands as an indicator using 20 day look back. Create code that generates a chart showing the rolling mean, the stock price, and upper and lower bands. The upper band should represent the mean plus one stand...
79a2b5f3b7e3594ed0137ed3f0d12912f15e6d6f
mulus1466/raspberrypi-counter
/seconds-to-hms.py
302
4.15625
4
def convertTime(seconds): ''' This function converts an amount of seconds and converts it into a struct containing [hours, minutes, seconds] ''' second = seconds % 60 minutes = seconds / 60 hours = minutes / 60 Time = [hours, minutes, second] return Time
d9335c35e5ce351d96fe21da51abc316fdfbfb4f
minh-t-coding/RSA-FactoringAlgo
/rsa.py
727
3.90625
4
import utils # This is an example of how RSA is implemented. def genKeyPair(klen): e = 3 # Choose some e that is relatively prime to phi(n) p = utils.genPrime(klen//2, 40) q = utils.genPrime(klen//2, 40) while (p%e == 1): p = utils.genPrime(klen//2, 40) while (q%e == 1): q = utils....
47917d1d41722101dd1dff8107d107b58f5bb3be
victorkumi/atbswp
/collatz.py
622
4.03125
4
from sys import exit def collatz(number): if number > 0: if number % 2 == 0: result = number // 2 else: result = 3 * number + 1 print (result) return result else: print ('You didn\'t enter a positive integer.') exit(0) print ('Enter a posit...
f1f55721d42c27a4dbc4a9b275b940c1e9bc256f
victorkumi/atbswp
/list_to_str.py
494
3.890625
4
def list_str(ls): if len(ls)>0: a=str(ls[0])+', ' i=0 for j in range(len(ls)-2): #this ensures that two items are left for ist and last cases. i+=1 a=a+str(ls[i])+', ' if len(ls)==1: return str(ls[0]) elif len(ls)>1: return a+'a...
7aad3b5cb134f2d836070775a27205117f57dc45
HB-LAND/pour-decisions
/crud.py
2,336
3.5625
4
"""CRUD operations.""" from model import db, connect_to_db, User, Wine, Cheese, Pair, Rating def create_user(fname, lname, email, password): """Create and return a new user""" user = User(fname=fname, lname=lname, email=email, password=password) db.session.add(user) db.session.commit()...
b9af6aaa450ecb83ca62cdd37591e10502126983
ANekhai/netDeckr
/netdeckr/utils.py
947
4
4
def format_text(text): uncapitalized = ["a", "an", "and", "at", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up"] # set all words to lowercase text = text.lower() text = text.capitalize() words = text.split(" ") # capitalize ever other word tha...
32be3ddb526a24d4825c87690a458363fc3e2a58
moxi624/LearningNotes
/数据结构/NowCode/36_Print.py
1,421
3.703125
4
# 按之字形顺序打印二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Print(self, pRoot): if pRoot == None: return [] # write code here stack1 = [pRoot] stack2 = [] # 存储打印 ret ...
abe7ab430e0296646b785eb775a516e8c9e4d469
moxi624/LearningNotes
/数据结构/NowCode/A1_binarySearch.py
481
3.828125
4
# 二分查找 class Solution: def binarySearch(self, array, key): left = 0 right = len(array) while(left < right): middle = int((right + left) / 2) if array[middle] == key: return middle elif array[middle] > key: right = middle - ...
6cedc72ef17165ed62ea053e6eada4bd75ad7aa6
moxi624/LearningNotes
/数据结构/NowCode/A6_MergeSort.py
1,526
3.625
4
# 归并排序 class Solution: def MergeSort(self, arrayList): arrayLen = len(arrayList) # 判断输入参数的正确性 if arrayLen < 1: return [] # 归并的出口是当分解到长度为1的时候 if arrayLen == 1: return arrayList # 获取中间索引值 middleIndex = arrayLen >> 1 # 递归左边部分 ...
a0c87eb53ba66fed17320c85e92ca3c92c29b4e1
moxi624/LearningNotes
/数据结构/NowCode/30_FindPath.py
1,680
3.671875
4
# 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None import copy class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): if root == None: ...
128326cc34f7a3736a5ff9b3b631429cb999fa99
moxi624/LearningNotes
/数据结构/NowCode/5_ReplaceSpace.py
687
3.734375
4
# 替换空格 # 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 class Solution: # s 源字符串 def replaceSpace(self, s): return s.replace(' ', '%20') def replaceSpace2(self, s): strLen = len(s) aaa = [] for i in range(0, strLen): if s[i] == " ...
0df76c213b7c33834068c94f9ee14b4343683a3c
Nilsonsantos-s/Python-Studies
/HackerRank/11.py
674
3.6875
4
# if __name__ == '__main__': pessoas = [] pessoa = [] scores = [] penultimo = [] for x in range(int(input().strip())): name = input().strip() score = float(input().strip()) pessoa.append(name) pessoa.append(score) scores.append(score) pessoas.append(p...
5be76054d3e797c6f7a997569a99f01aedfbd6a8
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex022.py
458
4.125
4
# leia um nome completo e mostre : letra maiusculas, letras miusculas, quantas letras sem espaços, letras tem o primero nome. nome = input('Digite seu nome completo:') print(f' O seu nome completo em maiusculo é : {nome.upper()}') print(f' O seu nome completo em minusculo é : {nome.lower()}') print(f' O seu nome tem {l...
5ced7539df95f131356ae9426478d30dda94b092
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex044.py
966
3.8125
4
# Leia preço normal e condição de pagamento, sendo elas á vista dinhero/cheque: 10% de decsconto, em até 2x no cartão: preço normal. 3x ou mais no cartão 20% de juros preco = float(input('Digite o preço padrão do produto:')) print(f''' {"="*40} Digite a condição de pagamento sendo: Á vista: Dinheiro ou cheque Cartão: 2...
ba25f64610567598313f2b33919334f925db8b86
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/ex115/__init__.py
2,125
4.34375
4
# crie um pequeno sistema modularizado que # permita cadastrar pessoas pelo seu nome e idade em um arquivo de txt simples # o sistema so vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas def titulo(texto): texto = str(texto) print('*-' * 25) print(f'{texto.title(): ^50}') ...
2fbde86ebba0d575833e4aeb65e77dfd1f2e0ab2
Nilsonsantos-s/Python-Studies
/basic_python/aulas_by_geek_university/reversed.py
986
4.65625
5
''' -> Reversed OBS: não confundir com reverse pois é uma função das listas: lista.reverse() # Retorna a lista invertida O Reversed funciona para quaisquer iterável, invertendo o mesmo. -> Retorna um iterável propio, de nome: List Reversed Iterator # Exemplos: ## Iteraveis dados = list(range(10)) print(dados)...
fac4cc6ce769a755a8a5f6cba3a85a654b044701
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex024.py
183
3.890625
4
# leia uma cidade e verifique se começe com a palavra "SANTO" cidade = input('Digite o nome de uma cidade:').strip() print(f' A começa com Santo: {"SANTO" in cidade.upper()[0:5]}')
3b96b643008d0250c969c15ac4ef2c932e75943f
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex058.py
655
3.953125
4
# Computador pensar em um numero entre 0 e 10, porem o jogador vai tentando advinhar até acertar, e no final mostrar quantos palpiter foram necessarios from random import randint vpc = int(randint(0,10)) vus = -1 sm = 0 while not vpc == vus: print('= ='*10) vus = int(input('Tente Advinhar o Numero Que o comput...
3b1dfc3803f8f1d1f45727d5835db3a76e15104d
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex067.py
371
4.0625
4
# a tabuada de varios numeros, ume de cada vez para cada valor que o usuario digitar, o programa sera interrompido quando o flag for negativo. while True: print('= ='*20) n = int(input('Digite um Valor Inteiro:')) if n < 0: print(f'Valor negativo digitado: {n}, Parando...') break for x i...
4c8e9d1b0cad94aa93539ef6ca630c088bc0fe2c
Nilsonsantos-s/Python-Studies
/urionlinejudge-python/1043.py
1,133
4
4
''' Leia 3 valores reais (A, B e C) e verifique se eles formam ou não um triângulo. Em caso positivo, calcule o perímetro do triângulo e apresente a mensagem: Perimetro = XX.X Em caso negativo, calcule a área do trapézio que tem A e B como base e C como altura, mostrando a mensagem Area = XX.X Entrad...
eac3895890c7556554a2b23c495e8b9920a67cd6
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex005.py
190
4.09375
4
# programa que leia um numero inteiro e mostre seu antecessor e seu sucessor n1 = int(input('Digite um numero:')) print('O numero {}, com antecessor {} e sucessor {}'.format(n1,n1-1,n1+1))
16111df4967b0e888dc6bdf20b9ed2eea93691bd
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex019.py
277
3.75
4
# leia quatro nomes e escolha um from random import randint n1 = input('Digite um nome:') n2 = input('Digite um nome:') n3 = input('Digite um nome:') n4 = input('Digite um nome:') lista = [n1, n2, n3, n4] numerorand = randint(0,3) print(f'Aluno Sorteado: {lista[numerorand]}')
f36d0c8ed4b84ada6ba921db39c31ed44b3ef22e
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/073.py
806
3.984375
4
# uma tupla com os 20 primeiros times da tabela do campeonato brasileiro de futebol, na ordem colocação. por fim mostrar, # apenas os 5 primeiros colocados, os ultimos 4 colocados, # um lista com os times em ordem alfabetica, # em que posição na tabela esta o time do Grêmio times = ('Atlético-MG','Internacional','São ...
971f85f83c29c39d6fd7b32b0761b029bc56ae73
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex055.py
220
3.984375
4
# leia o peso de 5 pessoa e mostre o maior e menor peso lido l = [] for x in range(0,5): p = float(input('Digite Um Peso:')) l.append(p) l.sort() print(f'O Menor peso é: {l[0]}\nO Maior peso é: {l[len(l)-1]}')
f41a5eeacf2230a37bfd1d833441b0c30e34a4f4
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex057.py
175
3.640625
4
# leia Sexo (M,F) caso esteja errado para digitar certo ate ter um valor correto sexo = 'a' while sexo not in 'MmFf': sexo = str(input('Digite O sexo [M/F]:')).strip()[0]
aa3f71e57d73de3c72c2561abc862e3f8d746432
Nilsonsantos-s/Python-Studies
/urionlinejudge-python/1065.py
552
3.78125
4
''' Faça um programa que leia 5 valores inteiros. Conte quantos destes valores digitados são pares e mostre esta informação. Entrada O arquivo de entrada contém 5 valores inteiros quaisquer. Saída Imprima a mensagem conforme o exemplo fornecido, indicando a quantidade de valores pares lidos. ''' pares ...
177d028cd34533c680e68ba4b5b858146855200b
Nilsonsantos-s/Python-Studies
/Mundo 2 by Curso em Video/Exercicios/ex065.py
529
3.765625
4
# Leia varios numeros inteiros pelo teclado, no final da execução, mostre a media e qual foi o maior e o menor. o programa deve perguntar ao usuario se ele quer continuar ou não a digitar valores flag = 'a' sm = 0 ct = 0 ls = [] while flag not in 'Ss': print('= ='*15) n = int(input('Digite um numero:')) fla...
8d1947a37f5305936fe58775d47c8267a767db97
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/075.py
1,207
4.125
4
# leia quatro valores pelo teclado e guardalos em uma tupla, no final mostrar, quantas vezes apareceu o valor 9. # em que posição foi digitado o primeiro valor 3, quais foram os numeros pares. valores = pares = tuple() # Forma Realizada for x in range(0,4): inpu = input('Digite um valor:') valores += tuple...
b25e884a889322e221af60a25e8185a7ac9c291e
Nilsonsantos-s/Python-Studies
/urionlinejudge-python/1010.py
1,082
4.0625
4
''' 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 cada linha haver...
faa48ee13b364fa7957b22353a37e0f9a515e11a
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex010.py
154
4.15625
4
# programa que leia um numero e converta para dolar. 3,27 n1 = float(input('Digite um numero:')) print(f'O Numero : {n1} R$\nEm dolar : {n1/3.27:.2f} $')
3ae76c70671c80b157240feeef76e21f52312354
Nilsonsantos-s/Python-Studies
/basic_python/aulas_by_geek_university/ordered_dict.py
491
4.21875
4
""" Modulo Collections (Modulo conhecido por alta performance) - Ordered Dict > Um dicionario que tem a ordem de inserção garantida # Demonstrando Diferença entre Dict e Ordered Dict from collections import OrderedDict dict1 = {'a':1,'b':2} dict2 = {'b':2,'a':1} print(dict1 == dict2) # True odict1 = OrderedDict({...
e46d7a7dfdf79364f8b4d0397c68d64ac9b7f989
Nilsonsantos-s/Python-Studies
/HackerRank/2.py
145
3.53125
4
# if __name__ == '__main__': a = int(input('')) b = int(input('')) so = a+b sm = a-b m = a*b print(f'{so}\n{sm}\n{m}\n')
668d7d56a5c3fcbb6701de11dd5f23520d69f0be
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/072.py
926
4.09375
4
# tenha uma tupla totalmente preenchida de 0 a 20 escrita# crie um programa que vai gerar 5 numeros aleatorios e colocar em uma tupla, depois disso mostre a listagem de numeros gerados e tambem indique o menor e o maior valor que esta na tupla por extenso ler um numero pelo teclado entre 0 e 20 e mostrar na tela por ex...
6cf95eaee1c7dd9e1255a947371ba6540ec9f7a4
Nilsonsantos-s/Python-Studies
/Mundo 3 by Curso em Video/Exercicios/091.py
880
3.5
4
# 4 jogadores joguem um dado (1 a 6) e tenham resultados aleatorios, guarde esses resultados em um dicionario, no final coloque esse dicionario em ordem, # sabendo que o vencedor tirou o maior numero no dado. from random import randint from time import sleep jogo = {} jogoord = {} valores = [] for x in range(0,4): ...
d8914aa996af7c53aa7fb55e1adf0b6edc18931e
Nilsonsantos-s/Python-Studies
/Mundo 1 by Curso em Video/Exercicios Python 3/ex029.py
306
3.875
4
# escreva um numero em km por hora, se for acima de 80 km/h tem multa de 7 RS por km n1 = float(input('Digite uma velocidade em Km/h:')) if n1 > 80: mt = (n1 - 80) * 7 print(f'Você precisa pagar um multa de {mt:.2f} R$') else: print(f'Você é um bom motorista e não precisa pagar multa ;)')
2fead6e39b4aa410c0949d5148069ffe8d0b4cfd
allenaerostar/client-launcher
/dietstory-routing/registration/password_utils.py
378
3.546875
4
import random import string class RandomPasswordGenerator: def __init__(self): self.password_length = 8 self.password_characters = string.ascii_letters + string.digits + "-_" def generate(self): return ''.join(random.choice(self.password_characters) for i in range(self.password_lengt...
4c6a409fe4f3701a2d13b7ca6290ba78bcbbfced
Shiouxios/Hangman_python
/Hangman.py
1,486
3.90625
4
# Import and clear terminal import os os.system('cls') # Get player to choose a word word = input("Player 1, choose a word: ") word = word.lower() print (word) os.system('cls') # Setup blank and wrong list blanks = [] wrong = [2] for x in range(0, len(word)): blanks.append("_") lives = 10 # Loop of guesses w...
45d1a3a08d68b4f7f24f36b9dc01f505ee715004
JamesSG2/Handwriting-Conversion-Application
/src/GUI.py
1,998
4.40625
4
#tkinter is pre-installed with python to make very basic GUI's from tkinter import * from tkinter import filedialog root = Tk() #Function gets the file path and prints it in the command #prompt as well as on the screen. def UploadAction(event=None): filename = filedialog.askopenfilename() print('Selected:', fil...
619536ae6b48f5e5919c2e5b8d4e5cd87ebfc386
AnusreeNath/JISAssasins
/anu13.py
433
4.09375
4
#question no 23 by anusree string=input("enter the string") count=0 for i in string: count=count+1 print("length of stringis ",count) list=string.split(" ") list.reverse() print(string[::-1]) string1=input("enter thestring") s3=string+string1 print(s3) if(string==string1): print("they are equal are...
2a24f985a563feec613b263ac1c6215026f8a50b
RafaelRampineli/exercism.io
/Python/hamming/hamming.py
375
3.515625
4
def distance(strand_a, strand_b): if len(strand_a) > len(strand_b): raise ValueError("First strand longer than second strand") elif len(strand_a) < len(strand_b): raise ValueError("Second strand longer than first strand") else: return len(([position for position in range(0, len(stran...
569406ad15d85c5866854fc21d06075a366f2d14
dsam99/Flight_Finder_Files
/data_presentation.py
469
3.640625
4
import randomflight; # Outputs all information about the chosen flights def data_presentation (flight_tuple): price = float(flight_tuple[0][3]) + float(flight_tuple[1][3]) print("Origin: " + flight_tuple[0][0]) print("Destination: " + flight_tuple[0][1]) print("Total Cost: " + str(price)) print("Starting Date: " ...
ceff151c5749cf478e7150eab4cc6804a7b52ffc
lvguichen1/algorithm004-02
/Week 02/id_472/N叉树的遍历/LeetCode_589_472.py
778
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2019/12/14 # @Author : xujun """ N叉树的前序遍历 给定一个 N 叉树,返回其节点值的前序遍历。 """ # 递归 # class Solution: # def preorder(self, root): # res = [] # self.helper(root, res) # return res # # def helper(self, root, res): # if not root: # ...
b607310a21c100f934c1225fda5d9f288ca5d717
lvguichen1/algorithm004-02
/Week 03/id_472/深度优先搜索和广度优先搜索/LeetCode_515.py
623
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2020/3/19 # @Author : xujun from collections import deque class Solution: def largestValues(self, root): if not root: return [] result = [] q = [(root, 0)] while q: curr, level = q.pop(0) ...
f9092e1874c6e81a3d58fc03f0348a5b4fb4be8a
paulstatezny/oss-university
/mitx-6.00.1x/pset2-problem2-paying-debt-off-in-a-year.py
403
3.875
4
balance = 5000 annualInterestRate = 0.18 payment = 0 lowestPaymentFound = False while (not lowestPaymentFound): payment += 10 testBalance = balance for i in range(12): testBalance -= payment interest = testBalance * (annualInterestRate / 12) testBalance += interest if testBalan...
fcfe2cc13a4f75d0ea9d47f918a7d53e3f8495df
cs-fullstack-2019-fall/python-basics2f-cw-marcus110379
/classwork.py
1,610
4.5
4
### Problem 1: #Write some Python code that has three variables called ```greeting```, ```my_name```, and ```my_age```. Intialize each of the 3 variables with an appropriate value, then rint out the example below using the 3 variables and two different approaches for formatting Strings. #1) Using concatenation and the...
6ce6a716cdea44d165dca588d5f539db326a88d0
Nispanu78/list-of-Selenium-tests
/test_assert_dict_equal.py
370
3.640625
4
import unittest class TestAssertDictEqual(unittest.TestCase): def test_dict_equal(self): dict1 = {'lang':'python', 'tool':'selenium', 'publication':'apress'} dict2 = {'lang':'python', 'tool':'selenium', 'publication':'Fernando'} self.assertDictEqual(dict1, dict2, "Dictionaries do not match...
30527eaad4fc17a9f0d1fd9f388ff9e94d7408e4
Nispanu78/list-of-Selenium-tests
/test_assert_set_equal.py
299
3.5
4
import unittest class TestAssertSetEqual(unittest.TestCase): def test_set_equal(self): set1 = {'python', 'selenium', 'apress'} set2 = {'python', 'selenium', 'Fernando'} self.assertSetEqual(set1, set2, "Sets do not match") if __name__ == '__main__': unittest.main()
abe1013408503dd49a62f855502e2d9f6efc2cbc
charlax/doubles
/doubles/expectation.py
2,822
3.625
4
from doubles.allowance import Allowance class Expectation(Allowance): """An individual method expectation (mock).""" def __init__(self, target, method_name, caller): """ :param Target target: The object owning the method to mock. :param str method_name: The name of the method to mock....
ac7bc94a05ee302940d8685694349a03631fb1a9
ratmirasanov/simple_linear_regression
/salary_prediction.py
891
3.765625
4
import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression DATA_SET = pd.read_csv("salary.csv") X = DATA_SET.iloc[:, :-1].values Y = DATA_SET.iloc[:, 1].values X_TRAIN, X_TEST, Y_TRAIN, Y_TEST = train_test_split(X, Y, tes...
67a6fd2be67f593a5fd4f30749627fd7f85cdaa2
JPGITHUB1519/Intro-To-Relational-Databases-Udacity
/Unit 3 - Python DB-API/SQL LITE/connect.py
335
3.53125
4
import sqlite3 # coneccting to database conn = sqlite3.connect("cookies") # cursor fetch result and save data cursor = conn.cursor() cursor.execute("select host_key from cookies limit 10") # get all results, to fetch only on is fetchone() result = cursor.fetchall() print results # always close the connection...
740e4a4754e8e85b633fb2b55fd4cdeccf19d600
Lizzy95/MICP
/HWweek4.py
851
4.03125
4
def wordBreak(text, dictionary): if text != '' and dictionary != {}: text = text.lower() for x in dictionary: if x.lower() in text: text = text.replace(x.lower(),'') if text == '': return True return False #test print wordBreak('youenjoy',{'pear', 'salmon', 'foot', 'prints', 'footprints', 'leave', '...
0e781af0a70b8693bad4fc60355e68792b080411
tongyao7/machine-learning
/LR.py
2,769
3.5625
4
from sklearn.linear_model import LogisticRegression import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split def create_data(): iris = load_iris() print(iris) df = pd.DataFrame(iris.data,...
bc7aa053583b217a2a0639505575fe737645bb45
kavin-lee/AI
/DS/day01/demo08_stack.py
480
3.5625
4
#!/usr/bin/python3 # !coding=utf-8 ''' 组合与拆分 ''' import numpy as np a = np.arange(1, 7).reshape(2, 3) b = np.arange(7, 13).reshape(2, 3) print("a:", a) print("b:", b) # 水平方向操作 c = np.hstack((a, b)) print(c) a, b = np.hsplit(c, 2) print("a:", a) print("b:", b) #垂直方向操作 c=np.vstack((a,b)) print(c) a,b=np.vsplit(c,2) pr...
0ec0bce267549382f614974383eeedb675cd018c
ultravioletrad/Data-Manipulation-at-Scale-Assignment_3
/MR asymmetric friends.py
879
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 4 18:57:19 2019 @author: hp """ import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # ...
6da2a295309c5a2b5a73f819ff9b6d45068ee44b
minhd2/advent-of-code-2020
/day2_password_philosophy/day2.py
601
3.828125
4
def password_requirements(filename): valid_password_counter = 0 with open(filename, 'r') as file: for lines in file: columns = lines.split() number_range = columns[0].split('-') letter = columns[1].rstrip(':') password = columns[2] minimum ...
808d17f322ca404cf022ac9e126cba6e7d3c70fd
minhd2/advent-of-code-2020
/day10_adapter_array/main_two.py
894
3.765625
4
def adapters_creation(filename): adapters = [0] split_adapters = list() total_paths = 1 with open(filename, 'r') as file: for line in file: adapters.append(int(line.rstrip())) adapters.sort() start = 0 for i in range(len(adapters) - 1): if (adapters[i + 1] - adapters[i]) == 3: split_adapters...
4d9ae48a4c482a332d57ca25f074479193b43f53
JoamirS/object-oriented-python
/Orientado-objeto-3/Person.py
1,396
4.0625
4
from datetime import date class People: current_year = int(date.today().year) def __init__(self, name, age, eating=False, speaking=False): self.name = name self.age = age self.eating = eating self.speaking = speaking def __str__(self): return self.name def sp...
44bbabe3d3e0728f5a8ec6d7aa45537be2f76ce9
JoamirS/object-oriented-python
/Orientado-objeto-3/class_shopping_cart.py
532
3.671875
4
class ShoppingCart: def __init__(self): self.products = [] def insert_product(self, product): self.products.append(product) def list_product(self): for product in self.products: print(product.name, product.price) def total_sum(self): total = 0 for p...
7c93169b8fc5476a20fd24269ad7683e76df11cd
JoamirS/object-oriented-python
/account.py
1,635
3.703125
4
class Account: def __init__(self, number_account, cardholder_name, balance_account, limit_account=1000): print(f'Criando o objeto {self}') self.__number_account = number_account self.__cardholder_name = cardholder_name self.__balance_account = balance_account self.__limit_ac...
3763ee2e94ab64e04a0725240cdc3a7a6990a3ad
yz398/LearnFast_testing
/list_module/max_difference.py
1,314
4.125
4
def max_difference(x): """ Returns the maximum difference of a list :param x: list to be input :type x: list :raises TypeError: if input is not a list :raises ValueError: if the list contains a non-float or integer :raises ValueError: if list contains +/-infinity ...
b38b98ca4fbf0074e1a965b4df5bfdea2f767542
Duinho/learn
/PYTHON/hello.py
191
3.59375
4
a = 20 def alex(): print("파이썬") if a == 21 : print("a is 20") else: if a == 20: print ("a is not") for a in [0,1,2,3,4,5,6]: print (a) alex() print("end")
ec8324d076ad963ddb4f9039f6edfcb46c4ecacf
gilescm/game-of-life
/main.py
2,765
3.609375
4
# 3rd Party Imports / Includes import argparse import matplotlib.pyplot as Plot import matplotlib.animation as Animation from matplotlib.widgets import Button # Imports / Includes import State as S import Iteration as I # Main() # Our main function that runs the show def Main(): N, Infinite, ...
933bb3559dfe0989ac77bed684bb726e63f8a52e
TKuzola/tryit
/homework.py
2,282
3.921875
4
''' Created on Mar 23, 2018 @author: Anthony exercises for edX that is PyLint clean ''' def remaining_balance(periodic_rate, amount, payment, months): ''' This is the f(x) function used by the bounds and bisection search Parameters: periodic_rate is APR / 12 amount = total l...
21d8d9435d119b4e3919e155189d91df144a404f
isso5235/ProjectEuler
/problem4.py
485
3.71875
4
#左右どちらから読んでも同じ値になる数を回文数という. # 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である. #では, 3桁の数の積で表される回文数の最大値を求めよ. def Palindrome(n): n = str(n) if n[0] == n[-1]: if n[1] == n[-2]: if n[2] == n[-3]: print(n) for i in range(100, 1000): for j in range(100, 1000): ...
0d928de5b0ef9ac1e103070b850c6b997c7f3e34
patrikch/ubungo
/ubungo.py
1,553
3.796875
4
import math class Card: def __init__(self): self.shape = [] def try_put_together(self, pieces): pass def assign_piece(self, shape, piece): """ assign somehow and return empty rest shape """ class Piece: """ """ def draw(self): pass class...
57e5bd531930c8ace9781feec073fb82c7a252f2
AleksandraZych/Profil
/sort_filter.py
3,203
3.5
4
#sort and filter import csv from core import count_awards, count_nominations def sort_by(arg, TorF): reader = csv.DictReader(open('Backend_movies.csv','r',encoding ='UTF-8', newline='')) sortedlist = sorted(reader, key=lambda row:( row[arg]), reverse=TorF) for s in sortedlist: print(s['ti...
c55314ed4d6dd3bf1a0189f2ed84e17e273f9bc9
KonstantinSukhorukov/Python
/HW8_Task_2.py
1,128
3.859375
4
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. # При вводе пользователем нуля в качестве делителя программа должна корректно обработать # эту ситуацию и не завершиться с ошибкой. class DivisionByZero: def __init__(...
5e0d6174878665e8d527565df100acfdc00c9273
KonstantinSukhorukov/Python
/HW8_Task_7.py
2,401
3.859375
4
# Реализовать проект «Операции с комплексными числами». # Создайте класс «Комплексное число», реализуйте перегрузку методов # сложения и умножения комплексных чисел. # Проверьте работу проекта, создав экземпляры класса (комплексные числа) # и выполнив сложение и умножение созданных экземпляров. # Проверьте коррект...
438ca826bc68f0f1fa8f7de1d0d2539bb2dcef21
luizfernandopavanello/hands-on_Python_4Linux
/Day_01/imc/imc.py
1,053
3.8125
4
from typing import Tuple escala_imc = { 'amp': 'Muito abaixo do peso', 'ap': 'Abaixo do peso', 'pi': 'Peso ideal', 'ac': 'Acima do peso', 'o1': 'Obesidade 1', 'o2': 'Obesidade 2', 'o3': 'Obesidade 3' } def calcular_imc(peso_kg: float, altura_m: float)-> Tuple[float, str] : imc = peso_kg / altura_m ** ...
20c08ad43503ba8bcd68bfc1e1237c405c6ee546
TTully/learning
/InterruptDetection.py
622
3.765625
4
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) # choose BCM(for GPIO numbering) or BOARD(for pin numbering) GPIO.setwarnings(False) # turned off warnings Pir = 29 # Assigning pin number to variable GPIO.setup(Pir,GPIO.IN) # Setting Pir (Pin) as an Input Pin State = 0 # Global variable def ...
30700878a847645203c0327c67b40d66d2715fdc
vicuartas230/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
776
3.9375
4
#!/usr/bin/python3 """ This script defines a function island perimeter """ def island_perimeter(grid): """ This function that returns the perimeter of the island described in grid """ perimeter = 0 for main_list in range(len(grid)): """ if 1 not in grid(main_list): continue """...
70276b8e585bd6299b8e9a711f5271089f25ab04
BenjaminLBowen/Simple-word-frequency-counter
/word_counter.py
938
4.25
4
# Simple program to list each word in a text that is entered by the user # and to count the number of time each word is used in the entered text. # variable to hold users inputed text sentence= input("Type your text here to count the words: ") # function to perform described task def counting_wordfunc(sentence): #...
0f89ead0c2b7fdf5f8f12e68c6dce539f714d605
Xinyi-Ma/Tabu-Search
/turn_to_py.py
4,557
3.578125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import random import datetime import matplotlib.pyplot as plt import pandas as pd import numpy as np # In[2]: def tabusearch(stop_time,initial_route,candidate_t,tabu_length): # Stop time: stop running when we reach this iteration limit. # I...
d1b389b2119a4dc261d04c3c72df7f3bda40d9e5
michaelvargasloza/Python-CRUD-python-desde-cero-
/app.py
513
3.671875
4
import insert import read import update import delete class Programa: def __init__(self): self.dato = 1 def menu(self): while self.dato: selection = input('\nSelecciona 1 para insertar, 2 para actualizar, 3 para leer, 4 para borrar.\n') if selection == '1': insert.insert() elif selection == '2': ...
19abd760dc51682111766579843d498338726e39
Ynteres/learning-git-tasks4.2
/z4.2 palindromy.py
744
3.671875
4
# zadanie z funkcją sprawdzajacą czy dany wyraz jest palindromem a funkcja zwraca prawdę lub fałsz ''' The reverse() is an inbuilt method in Python programming language that reverses objects of list in place. Returns: The reverse() method does not return any value but reverse the given object from the list The join() ...
6a08b43ad703d9ebb482588c761f971ccff4f21b
poemlin/ComputerVisionProject
/Mnist/onehot_to.py
496
3.625
4
# -*- coding: utf-8 -*- from tensorflow.examples.tutorials.mnist import input_data import numpy as np mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # 看前20张训练图片的label for i in range(20): # 得到one-hot表示,形如(0, 1, 0, 0, 0, 0, 0, 0, 0, 0) one_hot_label = mnist.train.labels[i,:] # 通过n...
58897217ac8185416254e68b390a7e87ad13585c
ariellang94/proyecto1
/prueba2.py
546
3.96875
4
from tkinter import * ### Opción 1 "Instancia de Clase Tk" #instancia de objeto Tk Ventana1 = Tk() Ventana1.title('Ventana 1') ### Acá iría todo el programa Ventana1.mainloop() ############################################################################### ### Alternativa 2 nueva clase "heredando clase Tk" class ...
d97863606d6864745dba3e167a3ac50e50d2f262
llecigne/sudoku
/sudoku/solver.py
3,098
3.6875
4
def solve(grid): """Sudoku solver""" if not is_grid_format_valid(grid): return None return _solve(grid) def is_grid_format_valid(grid): def is_row_format_valid(row): return isinstance(row, list) and len(row) == 9 return ( isinstance(grid, list) and len(grid) == 9 ...
e557e78a72b9ad5863b730d7d207b726612b5989
TH-Williamson/Class-Projects
/dateformat.py
688
4.3125
4
#need to tqke an integer input, and convert it to mm/dd/yyyy AND DD-MM-YYY format #TH Williamson, intro to programming, Prof. Kurdia user_day = str(input('Please enter day: ')) user_month = str(input('Please enter month: ')) user_year = str(input('Please enter year: ')) if user_day[0] == 0: user_day = '0' + use...
f9d24b47cb3e9cc35e453fc1194620c389d1820f
TH-Williamson/Class-Projects
/Cels_to_Fahr_FunctionPractice.py
182
3.953125
4
def c_to_f(c): F = c * (9/5) + 32 return F temp_c = float(input('Enter temperature in Celsius: ')) temp_f = None temp_f = c_to_f(temp_c) print('Fahrenheit:' , temp_f)
c7b32d7c040304d87a25b09008f6045d0d5d304b
rj-fromm/assignment3b-python
/assignment3b.py
530
4.375
4
# !user/bin/env python3 # Created by: RJ Fromm # Created on: October 2019 # This program determines if a letter is uppercase or lowercase def main(): ch = input("Please Enter a letter (uppercase or lowercase) : ") if(ord(ch) >= 65 and ord(ch) <= 90): print("The letter", ch, "is an uppercase letter")...
ab04555fc9f98af4816ca20d6d152074921e2e7d
riken17891/Practice
/archieved/DataStructures/LinkedLists/linked_list.py
795
3.8125
4
class LinkedList: def __init__(self, head): self.head = head def __str__(self): n = self.head s = "" while n is not None: s = s + n.name + " -> " n = n.next return s class Node: def __init__(self, name, next=None): self.name = name...
3e082887c6068d08fe27d4988aa531eec271044b
chrismessiah/KTH-AppliedComputerScience
/Lab3/C/Uppgift C.py
819
3.65625
4
# Author: Christian Abdelmassih, Alexandra Runhem from bintreeFile import Bintree import time import random starttime = time.time() tree = Bintree() file_name = "word3.txt" # create list and tree with random integers. value_list = [] for x in range(0,100000+1): value = random.randint(0,1000000) value_list.app...
bc1e281b97a807e8dd814b1b7e43a7a9019bf35b
chrismessiah/KTH-AppliedComputerScience
/Lab5/E/D2/labb5.py
1,259
3.734375
4
# Written by Christian Abdelmassih, Alexandra Runhem from hashtest import * from hashtable import * # Creates a list with all the atoms as elements def create_atom_list(): init_atom_list = skapaAtomlista() final_atom_list = [] for atom in init_atom_list: temp_letter_list = atom.split(" ") while True: try...
a133cf50251616f806d8500009a98c549081c9aa
flym1/lesson1
/ifelse.py
187
3.875
4
age = int(input('Сколько Вам лет?')) if age >= 7: print('иди в шк') elif age > 18: print('иди в универ') elif age >= 25: print('иди на работу')
1ef44c513148b9e2c09646e828ecc77d191cd90c
missy-davies/hb-1-3-melon-delivery-report
/produce_summary.py
661
3.640625
4
def print_daily_report(day, the_file): """Given a day number and a path to a file generate a report Generate a report for the number of melons and the total cost delivered for a particular day""" log = open(the_file) print(f"Day {day}") for line in log: line = line.rstrip() wo...
ebe2b41d6d5366e2443263e2badc124650a90f5b
CHAHAT-10/GRAPHICS_PROGRAMS
/circle.py
287
3.765625
4
import turtle turtle.pensize(2) turtle.speed(15) turtle.bgcolor("black") for i in range(10): for colours in ["yellow", "blue", "white", "green", "red", "pink", "purple"]: turtle.color(colours) turtle.circle(150) turtle.left(10) turtle.hideturtle()