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
34fb6e9853d5e8a79152dd3eb6209aff344456da
Arisaarisa/word_filter
/world_filter.py
400
3.609375
4
class WordFilter: def __init__(self, ng_word): self.ng_word = ng_word def detect(self, word): if self.ng_word in word: return True else: return False my_filter = WordFilter('アーセナル') print(my_filter.detect('昨日のアーセナル戦はアツかった!')) print(my_filter.detect('昨日のリバプール戦は...
f95b90b0231c366fbc687acb9d8ab4013597ecb1
40741107/frunch
/python/40741107(15).py
357
3.640625
4
import random a=random.randint(1,100) b=random.randint(1,100) for i in range(a,b): b=int(input("電腦猜數字")) if b>a: print("你猜的數字太大") elif b<a: print("你猜的數字太小") elif b==a: print("恭喜您,答對了!!!") e=input("你還要再玩一局嗎?") if e=="要":
7dff934eafd64f1563ec5d5979aecb312e046a6c
40741107/frunch
/python/大小排序.py
293
3.75
4
a=eval(input()) b=eval(input()) c=eval(input()) if a<b and b<c: print(a,b,c) elif a<b and c<b and a<c: print(a,c,b) elif b<a and a<c: print(b,a,c) elif b<a and c<a and b<c: print(b,c,a) elif c<a and a<b: print(c,a,b) elif c<a and b<a and c<b: print(c,b,a)
fc3905a416f6439996439bb4706c4d1e2bd17ef6
40741107/frunch
/python/506一元二次方程式.py
376
3.734375
4
def compute(a,b,c): r=b**2-4*a*c if r<0: return None elif r==0: return -b/(2*a) else: ans1=(-b+r**0.5)/(2*a) ans2=(-b-r**0.5)/(2*a) return str(ans1)+","+str(ans2) a=eval(input()) b=eval(input()) c=eval(input()) ans=compute(a,b,c) if ans==None: pr...
ed292dfe5a2f8688d894be317b467c3142718c48
40741107/frunch
/python/40741107(1).py
223
3.796875
4
x=float(input("數字1")) y=float(input("數字2")) z=float(input("數字3")) a=float(input("數字4")) b=float(input("數字5")) print(x,y,z,a,b) print("sum=%.1f" %(x+y+z+a+b)) print("average=%.1f" %((x+y+z+a+b)/5))
21baa224c40dfa0134fd9d00e446f03d2afb13c1
40741107/frunch
/python/505等級判斷.py
343
3.5625
4
while True: a=eval(input()) if a==-9999: break else: if a>=90 and a<=100: print("A") elif a>=80 and a<=89: print("B") elif a>=70 and a<=79: print("C") elif a>=60 and a<=69: print("D") elif a>=0 and a<=59:...
9bc5fc8791bdda599bb023eb7f3ab8da94f5c9b3
40741107/frunch
/python/折扣判斷.py
231
3.515625
4
a=eval(input()) if a>=8000 and a<18000: print("%.1f" % (a*0.95)) elif a>=18000 and a<=28000: print("%.1f" % (a*0.9)) elif a>=28000 and a<=38000: print("%.1f" % (a*0.8)) elif a>=38000: print("%.1f" % (a*0.7))
0a675149f9d758ee39cd7256a8d30216d2c46353
hermanmk/AI-AStar
/Util.py
7,892
3.765625
4
# coding=UTF-8 from turtle import * __author__ = 'Øyvind & Herman' # Dictionary with the different arc costs based on the square's value terrains = {'.': 1, 'w': 100, 'm': 50, 'f': 10, 'g': 5, 'r': 1, 'A': 1, 'B': 1} # Dictionary with terrain colors for the graphics colors = {'.': '#ffffff', '#': '#000000', 'w': '#3f...
edf86c988be340e688924f81d6eccb22aa0d8881
hypagedev/Deteccion-Vehiculos-YOLOv3-Maixduino
/YOLOv2/Training and Detection from Scratch/main.py
8,434
3.53125
4
import os, cv2 import matplotlib.pyplot as plt import numpy as np from backend import * import kmeans Labels = ["car"] # Vector that contains all the class names to detect raw_images = "raw_dataset/images/" # Directory containing training images raw_...
b7febb75251bf2e6630af1cb0ff3aefcd680f215
0meeee/for_coding_test
/ch1.파이썬문법/ch1-4.py
1,795
4.0625
4
#조건문 x = 15 if x >= 10 : print("x >= 10") if x >= 0: print("x >= 0") if x>=30: print("x>=30") #코드의 블록을 들여쓰기(indent)로 지정 a = -15 if a >=0: print("a>=0") elif a >= -10: print("0>a >= -10") else : print("-10 > a") score = 85 if score >= 90: print("A") elif score >= 80: print("B") elif score ...
62c6fc2d0b1fab40d2001041e1ede001058ba3a3
LingyeWU/unit3
/Week28/q5.py
321
3.890625
4
# This script will convert a given age to "dog years" # Inputting age in human years print("Please input the age:") #Variables dYears = 0 hYears = int(input()) # Conversion for i in range(1, hYears + 1): if i <= 2: dYears += 10.5 else: dYears += 4 print("The age in dog years is", int(dYears))...
efc2a9bba1db46e90da4f3d1dffaa98ff3fc76ef
LingyeWU/unit3
/snakify_practice/3.py
837
4.1875
4
# This program finds the minimum of two numbers: a = int(input()) b = int(input()) if a < b: print (a) else: print (b) # This program prints a number depending on the sign of the input: a = int(input()) if a > 0: print (1) elif a < 0: print (-1) else: print (0) # This program takes the coo...
8a28e6a47576527d6cac0ed59df12412774ceb5d
LingyeWU/unit3
/python/myLib.py
505
3.5625
4
# This is my library of very useful funtion def me(): print("Developer:".rjust(20), "Lingye WU") print("Date:".rjust(20), "FEB 2020") def prime(x): for div in range(2, x - 1): if x % div == 0: return False return True def distance(target, origin=(0, 0)): # Thi...
d972727a321a270712b348d5c8a480f3544f5a14
lior8/evolutionary-tetris
/analysis/plot_generation.py
2,749
3.984375
4
import matplotlib.pyplot as plt import numpy as np def log_to_data(file_path): """ Converts a log file into a a list representing the generations. :param file_path: The path to the log file :return: A list of lists of lists. Each list is a generation which hold lists which are the games of each indivi...
4bee428ac8e0dd249deef5c67915e62ba1057997
Matshisela/Speed-Converter
/Speed Convertor.py
1,100
4.34375
4
#!/usr/bin/env python # coding: utf-8 # ### Converting km/hr to m/hr and Vice versa # In[1]: def kmh_to_mph(x): return round(x * 0.621371, 2) # return to the nearest 2 decimal places def mph_to_kmh(x): return round(1/ 0.621371 * x, 2) # return to the nearest 2 decimal places # In[2]: speed_km = float(i...
ca527ac5ef3d48249eefd38f84a2a32c87c12339
lucyhattersley/6002x
/week1/Lecture2/l2p4.py
723
3.65625
4
import random def dist1(): return random.random() * 2 - 1 def dist2(): if random.random() > 0.5: return random.random() else: return random.random() - 1 import random def dist3(): return int(random.random() * 10) def dist4(): return random.randrange(0, 10) import rand...
7d29edcc30f90521409c338707e662abbcdaf6a8
lucyhattersley/6002x
/week3/L5/noReplacementSimulation.py
736
4.0625
4
import random def noReplacementSimulation(numTrials): ''' Runs numTrials trials of a Monte Carlo simulation of drawing 3 balls out of a bucket containing 3 red and 3 green balls. Balls are not replaced once drawn. Returns the a decimal - the fraction of times 3 balls of the same color were dra...
96fc093a45ffb817d24edc5dbebe963b285b696c
mlizhenbin/python-toy
/basic/FunctionTest.py
477
3.875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # 定义函数 def printme(str): print str; return; # 调用函数 printme("我要调用用户自定义函数!"); printme("再次调用同一函数"); printme(""); pass # 可写函数说明 def changeme(mylist): "修改传入的列表" mylist.append([1, 2, 3, 4]); print "函数内取值: ", mylist return # 调用changeme函数 mylist = [10, 20...
f6eee45146d12b5d3eeca51353c924fefedde3eb
yu-daniel/Newbie-Projects
/Hangman - v2.py
2,077
3.796875
4
import random, sys import string word_list = ['path of exile', 'talesweaver', 'maplestory','ragnarok online', 'diablo 2', 'starcraft', 'warcraft 3','age of empire 2', 'grim dawn' ] correct_answers = [] used_words = [] selected_word = list(random.choice(word_list)) letters = list(st...
34b0f3d8ae1d8fa7fbec1ffb3f122b03f5349520
apuvvala-git/python_programming
/readable_timedelta.py
446
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 31 21:00:22 2018 @author: Ajay """ def readable_timedelta(days): """ readable_timedelta - Returns readable timedelta days - # of days. Type: int """ nweeks = days // 7 nmoddays = days % 7 str = "{0} week(s) and {1} day...
5f90cf3ee2b9a95d877d3a61a5f4691535c182f3
s-andromeda/PreCourse_2
/Exercise_4.py
1,469
4.5
4
# Python program for implementation of MergeSort """ Student : Shahreen Shahjahan Psyche Time Complexity : O(NlogN) Memory Complexity : O(logN) The code ran successfully """ def mergeSort(arr): if len(arr) > 1 : # Getting the mid point of the array and dividing the array into 2 using...
9c4320f0804b9cf39e4aa14ae4c93dd639b3dfac
fishjawzrex/Algorithms-and-Data-Structures-in-Python
/fibby.py
140
3.671875
4
def fib(n): if n==0: return 0 if n==1: result = 1 else: result = fib(n-1)+fib(n-2) return result print(fib(7))
08aa9b8e3e5c10cb5ba69bbba564186b12cdf067
arpitsomani8/Data-Structures-And-Algorithm-With-Python
/Linked List/Doubly Linked List .py
1,497
3.890625
4
# -*- coding: utf-8 -*- """ @author: Arpit Somani """ class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if...
1bdfb1dfe2b1d5c7b707a38f071a7167f6f514e8
arpitsomani8/Data-Structures-And-Algorithm-With-Python
/Stack/Representation of a Stack using Dynamic Array.py
1,517
4.125
4
# -*- coding: utf-8 -*- """ @author: Arpit Somani """ class Node: #create nodes of linked list def __init__(self,data): self.data = data self.next = None class Stack: # default is NULL def __init__(self): self.head = None # Checks if stack is empty def isempty(self): if self.head == ...
0646144b3ca1bd57be1c30e74d23c2883351dfc7
arpitsomani8/Data-Structures-And-Algorithm-With-Python
/Stack/Two stacks in an array.py
1,475
3.828125
4
# -*- coding: utf-8 -*- """ @author: Arpit Somani """ class twoStacks: def __init__(self, n): self.size = n self.arr = [None] * n self.top1 = -1 self.top2 = self.size #push element x to stack1 def push1(self, x): #empty space for new element is must if self.top1 < self.top2 - 1 : sel...
52b616788bca2013bcc0cf9f716ad5c0486cf80f
arpitsomani8/Data-Structures-And-Algorithm-With-Python
/Searching/Linear_Search.py
581
3.9375
4
# -*- coding: utf-8 -*- """ @author: Arpit Somani """ def linear_search(n,x): element=[] for i in range(1,n): element.append(i) count=0 flag=0 for i in element: count+=1 if(i==x): print("Yes! I found my number at position"+str(i)) flag=1 break; if(flag==0): print("Number is not found...
5f953fd21715b5229a2aeccd9c8cd52c579111e7
cyrustabatab/TicTacToe
/game.py
4,710
3.578125
4
import pygame import time import random pygame.init() SCREEN_WIDTH,SCREEN_HEIGHT = 600,800 SQUARE_LENGTH = 200 BOARD_WIDTH = BOARD_HEIGHT = 600 FPS = 30 screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) pygame.display.set_caption("Tic Tac Toe") board = [[None for _ in range(3)] for _ in range(3)] d...
b40f4fcddff8eb58677600a88a611c0c3c33efa4
sanjai21/simple-open-port-checker
/check_open_ports.py
843
3.59375
4
import socket from colorama import init , Fore #declaring colours for output init() GREEN = Fore.GREEN RED = Fore.RED WHITE = Fore.WHITE BLUE = Fore.BLUE YELLOW = Fore.YELLOW def port_check(host,port): try: #trying to connect to the port s = socket.socket() s.connect((host,po...
e1ee3f3c7f84fa7cb12198fa16dbf03b5ec26b6f
bekaarcoder/python_scripts
/Image_Manipulation/image_converter.py
605
3.578125
4
import sys import os from PIL import Image # grab the arguments from the command image_folder = sys.argv[1] output_folder = sys.argv[2] print(image_folder, output_folder) # check if the output folder exists if os.path.exists(output_folder): print(f'{output_folder} exists') else: print(f'Creating {output_folder} ...
639abe66cf617200ba24896517a9556307cae119
EpicureanHeron/courseraIntroPython
/memory.py
3,492
3.640625
4
# http://www.codeskulptor.org/#user31_IwJ8VYHAa5yHCI8_3.py # implementation of card game - Memory import simplegui import random cards = [] cards_2 = [] cards = range(0, 8) cards_2= range(0, 8) cards.extend(cards_2) exposed = {} counter = 0 ordered_deck = {} state = 0 turns = "Turn = 0" card_1 = 0 last_card = 0...
b6d143eb55b431f047482aaf881c025382483c0a
SHIVAPRASAD96/flask-python
/NewProject/python_youtube/list.py
432
4.1875
4
food =["backing","tuna","honey","burgers","damn","some shit"] dict={1,2,3}; for f in food: #[: this is used print how many of the list items you want to print depending on the number of items in your list ] print(f,"\nthe length of",f,len(f)); print("\n"); onTeam =[20,23,23235,565]; print("Here are the p...
f329c396a33ce79e1452eeff2cb48ab49f6ba18f
pradeep-528/pradeep
/uniq_lst.py
185
4
4
#!/usr/bin/python # printing unique elements in alist def unique(list): l2=[] for i in list: if i not in l2: l2.append(i) print l2 unique([1,2,1,3,2,4])
ee837cb9f55d9e92eddc306b48a82142ecb3d13a
pradeep-528/pradeep
/months.py
159
3.765625
4
# printing months def months(): a = ("jan","feb","mar","apr","may","june","july","aug","sep","oct","nov","dec") for x in a: print x months()
fc59afebf5f77f6007965b14e7e1957c72f0d9ec
pradeep-528/pradeep
/employ_class.py
290
3.828125
4
#!/usr/bin/python # entering employee details and their count class employee: count=0 def __init__(self,name,salary): print name print salary employee.count+=1 print employee.count em=employee('pradeep',20000) em=employee('kumar',18000)
c467acdcc4ee0cd176bd4d1df69731d22b10a307
pradeep-528/pradeep
/dict_kv.py
169
4.0625
4
#!/usr/bin/python # interchanging keys,values in a dictionary def dic(d): dd = {} for k,v in d.items(): dd[v] = k print dd dic({'a':1,'b':2,'c':3})
79de9bea510e00a8e783e1c05b07251a0f19728f
pradeep-528/pradeep
/insert_lst.py
147
3.984375
4
#!/usr/bin/python # list operation-insertion x=["ram","raju"] print "before insert" print x print "after insertion" x.insert(1,"chandra") print x
bef434e61acd02c0941bb341d85221d51f45c056
DagmarMpheio/PeriodoDeEstudo
/periodoEstudo.py
818
3.796875
4
estudantes = int(input("Digite o numero de estudantes: ")) table={} idade=0 cN=0 cM=0 estN={} estM={} for i in range(estudantes): nome = input("Digite o nome do estudante {0} :".format(i+1)) anoNascimento = int(input("Digite o ano de nascimento do estudante {0} : ".format(i+1))) idade=2020 - anoNa...
79ae1803dc9109c9e321bc6fe9b4cf5220f597c7
Souzanderson/Python_codes
/AULAS DE PYTHON/interfacegrafica.py
872
3.8125
4
from tkinter import * #funções def Calcular(): result['text'] = form.get() #move o texto da form para o Label Result result['fg']='red' #muda a cor do texto do Label Result #cria a tela app=Tk() #define o tamanho da tela app.geometry("400x300") #titulo do programa app.title("Calculadora") #icone da tela ...
521817c0323b4e69fa8dddfc764b1ccd4c6f990a
Souzanderson/Python_codes
/GERENCIADOR DE DB/cadastro.py
632
3.609375
4
import sqlite3 def Cad_pessoaf(): conn = sqlite3.connect('clientes.db') cursor=conn.cursor() nome=input("nome: ") telef=input("telefone: ") cpf=input("CPF: ") cursor.execute(""" INSERT INTO pessoa (nome,fone,CPF) VALUES (?,?,?) """,(nome,telef,cpf)) conn.commit() print...
2dfecc9b4b9f884c984b5d34937fa322f7422004
Kangsiyuan/first-git
/8.py
436
3.546875
4
import random def ra(): list1 = [] for i in range(10): x = random.randint(0,10) list1.append(x) return set(list1) a = ra(); b = ra(); print("A矩阵:",a,"矩阵长度:",len(a),"最大值:",max(a),"最小值:",min(a)) print("B矩阵:",b,"矩阵长度:",len(b),"最大值:",max(b),"最小值:",min(b)) print("A、B的并集",a|b) print("A...
9b89a57be64b7dd7ee4706edd9e32081a4dcba8f
sruddell09/schoolWork
/Phonetics/Grad/Scripts/getMinPairs.py
3,249
3.75
4
#coding:utf8 def split_word(word): letter = 0 chars = [] while letter < len(word): if letter < len(word) - 1: if word[letter + 1] not in exceptions: chars.append(word[letter]) letter += 1 else: chars.append(word[letter] + word[l...
3f7bf9adb78d3c5bbc0f8f5f9a5fa815f28617f1
DecodEPFL/eiv-grid-id
/src/models/matrix_operations.py
6,040
3.671875
4
from typing import Tuple import numpy as np import scipy.sparse as sp """ Useful function for operations on matrices and vectorization Provides tools to vectorize/unvectorize matrices, as well as complex/real transformations. The Duplication, transformation and elimination matrices can also be ge...
9cd46a8d08623962e4d72899e3ff831c2b1db294
tsaiiuo/pythonNLP
/dicTuple.py
557
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 30 13:36:29 2021 @author: huannn """ dic1={"lemon":1,"apple":2,"pitch":3} for key, value in dic1.items(): if(key=="lemon"):print(f"key={key}; value={value}") for items in dic1.items(): print(items) dic2=dic1.copy() #for items in dic2.items()...
60fc8a28c92e1cf7c9b98260f1dee89940929d68
tsaiiuo/pythonNLP
/set and []pratice.py
1,015
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 23 15:24:16 2021 @author: huannn """ #list[item1,item2....] a=['apple','melon','orange','apple'] a.append('tomato') a.insert(3, 'tomato') print(a) a.remove('apple') print(a) a.pop(0)#pop out a certain position print(a) a1=['fish','pork'] #a.append(...
485453cc97fe50a2aaf07b126c96ca4bd2ba0702
celsopa/CeV-Python
/utilidadesCeV/dado/__init__.py
487
3.75
4
def leiadinheiro(msg): """ -> Executa a leitura de um valor monetário, encontrando o caractere separador entre valor inteiro e real. :param msg: (String) Mensagem a ser exibida no prompt para o usuário durante a leitura. :return: o valor monetário em ponto flutuante. """ n = input(msg).strip() ...
96e3f96b1d3800769dbb20d4c178d1531289859b
celsopa/CeV-Python
/mundo02/ex045.py
1,161
4.09375
4
# Exercício Python 045: Crie um programa que faça o computador jogar Jokenpô com você. from random import randint print(f"""Suas opções: [ 1 ] - PEDRA [ 2 ] - PAPEL [ 3 ] - TESOURA""") maoUser = int(input("Qual sua opção: ")) maoPC = randint(1, 3) if maoUser == 1: if maoPC == 1: print("O computador escolh...
cbea35a79abb7977edef6f839faafc8a32cf9b77
celsopa/CeV-Python
/mundo03/ex085.py
1,101
4.09375
4
# Exercício Python 085: Crie um programa onde o usuário possa digitar sete valores numéricos e # cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. # No final, mostre os valores pares e ímpares em ordem crescente. pares = [] impares = [] for e in range(1, 8): try: n = int(inp...
ad1dcc7b5a7c601125ef8a5db39a1cd393af58a4
celsopa/CeV-Python
/mundo01/ex028.py
501
4.25
4
# Exercício Python 028: 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 nPC = randint(0,5) nUser = int(inp...
c5847011cf3d5f5d59fc7fc58b903d0332c71973
celsopa/CeV-Python
/mundo02/ex036.py
786
4.25
4
# Exercício Python 036: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. valorCasa = float(input("Informe o valor do i...
8c1c54f709da53277c757ef5e767bca997db94f2
celsopa/CeV-Python
/mundo02/ex052.py
332
3.90625
4
# Exercício Python 052: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. n = int(input("Digite um número inteiro: ")) div = 0 for d in range(2, n): if n % d == 0: div += 1 print("O número não é primo!!!") break if not div: print("Esse número é primo!")
2d9753ea6268e180eb5a9e34b15e4c17f0ccac20
celsopa/CeV-Python
/mundo01/ex034.py
481
3.921875
4
# Exercício Python 034: Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%. sal = float(input("Informe o salário do funcionário: R$")) if sal > 1250: sal *= ...
512efa228df5979cddc8a2295705c3f9ab927177
celsopa/CeV-Python
/mundo03/ex104.py
570
4.125
4
# Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante # à função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. # Ex: n = leiaInt('Digite um n: ') def leiaint(msg): while True: n = input(msg) if n.isnumeri...
c0c5160a22cbbfe2dcc98d47dea98cfb2ca70484
celsopa/CeV-Python
/mundo02/ex065.py
923
4.0625
4
# Exercício Python 065: 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. n = int(input('Digite um número: ')) m...
bef62bd7bd8c4fd6da841a77d1934ef4fde60525
celsopa/CeV-Python
/mundo02/ex050.py
380
4.0625
4
# Exercício Python 050: Desenvolva um programa que leia seis números inteiros e mostre a soma apenas # daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o. soma = 0 i = 0 for x in range(6): n = int(input(f"Digite {x}º número inteiro: ")) if n % 2 == 0: soma += n i += 1 print...
1435439681379f4ee14d0a1409d0218931401cf6
celsopa/CeV-Python
/mundo02/ex048.py
358
4
4
# Exercício Python 048: Faça um programa que calcule a soma entre todos os números ímpares # que são múltiplos de três e que se encontram no intervalo de 1 até 500. i = 0 soma = 0 for x in range(1, 501, 2): if x % 3 == 0: i += 1 soma += x print(f"A soma dos {i} valores ímpares múltiplos de 3 entre ...
0a92283589cb836c2e256347ca95fa8f0889a786
celsopa/CeV-Python
/mundo02/ex056.py
1,135
3.765625
4
# Exercício Python 056: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. # No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho # e quantas mulheres têm menos de 20 anos. from time import sleep pessoas = [] somaIdade = 0 fSub20 = 0 idadeHomemVelho = 0 hVelho = ''...
ac25c390e4052d2feafe522841b38da51975643c
celsopa/CeV-Python
/mundo02/ex070.py
1,175
3.890625
4
# Exercício Python 070: 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. # B) quantos produtos custam mais de R$1000. # C) qual é o nome do produto mais barato. totalGasto = 0 menorPrec...
6b381dc1f2b109f74fb967456a288783dab00fee
celsopa/CeV-Python
/mundo02/ex044.py
1,280
3.90625
4
# Exercício Python 044: Elabore um programa que calcule o valor a ser pago por um produto, considerando # o seu preço normal e condição de pagamento: # - à vista dinheiro/cheque: 10% de desconto # - à vista no cartão: 5% de desconto # - em até 2x no cartão: preço formal # - 3x ou mais no cartão: 20% de juros preco = f...
4ec21acb5c414b5a34db008225502db8576e3003
pawarspeaks/HACKTOBERFEST2021-2
/PYTHON/pythagorean_theorem.py
1,777
4.5
4
#A Pythagorean theorem solver that accounts for whether the hypotenuse is known or not def main(): def is_right(): righty = input("Do you have a right triangle (meaning one of the angles is 90 degrees)? (Y/N) ") if y_or_n(righty) == "Y": get_angles() else: not_right...
152e7b7430ded1d3593c2ec9b3a2cec89d7d270d
pawarspeaks/HACKTOBERFEST2021-2
/PYTHON/PasswordGen.py
606
4.125
4
import string import random #Characters List to Generate Password characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") def password_gen(): #Length of Password from the User length = int(input("Password length: ")) #Shuffling the Characters random.shuffle(characters) #Picking random Characters...
b3af88cb1b7bf2c4fe2bdb2654e45fefed048776
pawarspeaks/HACKTOBERFEST2021-2
/PYTHON/minimal NFA.py
664
3.84375
4
#Construction of a minimal NFA accepting a set of strings over {a, b} in #which each string of the language starts with ‘ab’. def stateX(n): if(len(n)==0): print("string not accepted") else: if (n[0]=='a'): stateY(n[1:]) elif (n[0]=='b'): print("string not accepted") def stateY(n): ...
ddc0ca12d498f95ad0c7ae33bacc397f67eed2cd
pawarspeaks/HACKTOBERFEST2021-2
/HackeRank/cycle_detection.py
469
3.640625
4
#username :- ravi4713 #cycle detection program from hackerank def has_cycle(head): if head is None: return 0 if head.next is None: return 0 slow = head fast = head while fast != None and slow != None: slow = slow.next if fast.next is not None: ...
a80054299a309764bc6281b277a629ee262dd953
MarkCarbonell98/UniSecondSemester
/algorithmen_und_datenstrukturen/ubungen/ubung10/maze.py
3,130
3.53125
4
# Aufgabe 1a graph = [[1], [2,3], [1], [4,5], [3], [3,6,7], [5], [5,8,10], [7,9,10], [8], [7,8, 11], [12,13], [11] ,[11, 14, 15], [13], [13]] for arr in graph: arr.sort(reverse=True) print("Adjazenzlisten: ", graph) # aufgabe 1b def way_out(graph, startnode, targetnode): visited = [None]*len(graph) dead...
fb262c8af4994227d6fe59af0464e6dc39a4e104
MarkCarbonell98/UniSecondSemester
/algorithmen_und_datenstrukturen/gruppe/generators.py
491
3.609375
4
a = (i for i in range(10)) # generator function for i in a: print(i) # run fish for i in a: print(i) def a(): i = 0 while i < 10: yield i i += 1 for i in a(): print(i) b = a() print(type(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b...
a164e3e78d90205837aeb4f2b5fdad3b45378ad3
aster724/Ejercicios_Basicos
/falsoOVerdadero.py
400
4
4
#!/usr/bin/env python 3.7 ''' Julianv 12/10/2019 Ingresar el nombre y edad de dos usuarios y mostrar en pantalla si son iguales. ''' usuarioUno = input("Cual es tu nombre: ") edad_usuario_uno = int(input("Edad: ")) usearioDos = input("Cual es tu nombre: ") edad_usuario_dos = int(input("Edad: ")) print(...
f57a83fa3ada31c06c699cbc167c4a9c78a6a842
TholhahZabri/Learn-Python
/testpython2.py
1,636
4.03125
4
#python operators # + , - , * , / , // , % , ** num1 = 10 num2 = 20 print(num1 ** num2) print(num1 // 3) print(num1 % 3) #Comparison operators # < , > , <= , >= , == , != print(num1 == num2) print(num1 <= num2) print(num1 < 10) print(num1 <= 10) #Identity operators n1 = 100 n2 = 200 print() print(n1 is n2) print...
89e35877091dcda54be0968f452658dbc65e386f
xolisa003/palgorithms
/mypackage/sorting.py
3,077
4.375
4
def bubble_sort(items): ''' Puts a list in increasing order by successively comparing adjacent elements interchanging them if they are in the wrong order ''' for num in range(len(items)-1,0,-1): for i in range(num): if items[i]>items[i+1]: temp = items[i] ...
9b1614027171ad17c2aea33f537ab2d618488429
ahryhoryev/Lesson
/lesson-05/Solution-02.py
242
3.765625
4
import random people = ["Sasha", "Dima", "Kristina", "Olga", "Marina"] random.shuffle(people) for i in range(len(people) - 1): print(people[i], "is secret santa for:", people[i + 1]) print(people[-1], "is secret santa for:", people[0])
af298b1551b5b069f63180026980325e504c61bd
leolanese/python-playground
/tips/*40.py
253
3.875
4
print("Hello!, Welcome to Python") print("*" * 40) print("Please Enter your name ") name = input() print("Your name is, " + name) # Hello!,Welcome to Python # **************************************** # Please Enter your name # Leo # Your name is, Leo
de91aed8808c9c1562ace961b39d5e2f6d3d20bc
leolanese/python-playground
/tips/list-comprehensions.py
318
4.34375
4
# Python's list comprehensions vals = [expression for value in collection if condition] # This is equivalent to: vals = [] for value in collection: if condition: vals.append(expression) # Example: even_squares = [x * x for x in range(10) if not x % 2 even_squares # [0, 4, 16, 36, 64]
813aab7ada6e671f8a19642b863d829312465bed
leolanese/python-playground
/tips/sort-dict- by-value.py
692
4.0625
4
# How to sort a Python dict by value # (== get a representation sorted by value) # 1 xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} sorted(xs.items(), key=lambda x: x[1]) # [('d', 1), ('c', 2), ('b', 3), ('a', 4)] # 2 Weight_details = { 'Sam':45, 'Irum':67, 'Dolly':80, 'Bela':20 } sorted_weight = sorte...
6935349bd6516c47a274c2cf6c0938a1ae7dc1be
brightsunp/learn
/leetcode/DCP_61-70.py
12,616
3.75
4
#!/usr/bin/python # coding=utf-8 ''' __author__ = 'sunp' __date__ = '2019/1/24' ''' import unittest, random from collections import defaultdict, OrderedDict class Solution1(object): '''Google Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x...
538815e6bf7abf3f2ebb11fe278dc407aae09608
brightsunp/learn
/leetcode/solve_Hard.py
1,868
3.671875
4
#!/usr/bin/python # coding=utf-8 ''' __author__ = 'sunp' __date__ = '2019/1/17' How to solve a hard question: Find the naive solution, then optimize it. ''' class Solution1(object): ''' Largest Rectangle in Histogram Naive: for each bar, find left and right where height is lower, then calculate max_area...
96d7cda7ee9c9db84dd80fc28fcdb6af9d0ffb2f
cwang066/Dash_SimpleAPP
/merge_data.py
583
3.53125
4
import pandas as pd import numpy as np svy18 = pd.read_csv('Survey_2018.csv') svy19 = pd.read_csv('Survey_2019.csv') svy20 = pd.read_csv('Survey_2020.csv') for y, d in zip(range(18, 20+1), [svy18, svy19, svy20]): print(f'Survey 20{y} Columns:', d.columns) print('Make sure that one column you want to merge...
ee2d5fa2d85740d0219040b80426b1ef57087857
datasciencecampus/coffee-and-coding
/20191112_code_testing_overview/02_example_time_test.py
1,166
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 11 10:28:55 2019 @author: pughd """ from datetime import datetime class TestClass: # Difficult to automate test this as depends on time of day! def test_morning1(self): assert time_of_day() == "Night" # Far easier to...
4d4b7a8332608fd2149d783c782d525d272f59d2
sai194/Python
/basics/weather_functions.py
1,023
3.953125
4
# Note you need to run 'pip install requests' to use the requests module import requests def get_weather_desc_and_temp(city): api_key = '67da29cb91129f1a68c1c06c1be92daa' url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial&appid=' + api_key request = requests.get(url) ...
92f40150deb9f84570fe8fc1af09889715c861fe
sai194/Python
/basics/funcs.py
426
3.640625
4
def add(a: int, b: int) -> int: # arg are not type checked like java but there are options to enforce return a + b print(add(1,2)) print(add("Fred", "Jones")) def show(a, b, *args, **kwargs): print(f"a is{a}, b is {b}") print(type(args)) for a in args: print(a) print(type(kwargs)) for ...
41a620339db917ca267f36206d7608a2766b93bd
SoggyBottomBoys/Nixon
/reader.py
285
3.5625
4
import csv as csv import numpy as np def reddit(c,d): #reads csv's from selected file. print("Importing data from",c) csv_file_object = csv.reader(open(c),delimiter=d) header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) return [header,data]
7042b216761fe26ce8ffa3e913f54a0508d19ca4
sreelekha11/Number-Guessing
/NumberGuessingGame.py
1,254
4.40625
4
#Creating a simple GUI Python Guessing Game using Tkinter and getting the computer to choose a random number, check if the user guess is correct and inform the user. import tkinter import random computer_guess = random.randint(1,10) def Check(): user_guess = int(number_guess.get()) #Determine ...
7de7c7742a70c650b8885d352c122bd9d04b162d
oolym/learning_python_
/20200212_구구단출력.py
550
4
4
#--------구구단출력 for n in range(1,10): print (1, 'x', n,'=', 1*n) for n in range(1,10): print (2, 'x', n, '=', 2*n) #--------모든 구구단 for n in range(1,10): print ('='*10) for m in range(1,10): print (n, 'x', m, '=', n*m) #---------구구단입력 number = int(input ('구구단을 몇 단 출력할까요? 숫자를 입력하세요:')) whil...
b3cef4c80105f8271f876d2aa249d691f6a05c63
rlawjddns0/ALGO
/Programers/튜플.py
1,324
3.53125
4
import re def solution(s): answer = [] s=s[1:len(s)-1]#맨 앞에 { 맨 뒤에 } 제거 s=s.split('}')# }기준으로 나누기 print(s) #입력 :"{2},{2,1},{2,1,3},{2,1,3,4}" #출력: ['{2', ',{2,1', ',{2,1,3', ',{2,1,3,4', ''] s=s[0:len(s)-1]# 맨 마지막에 아무것도 없는 리스트가 생겨서 그거 제거 ? 왜 생기지? num_list = [] for i in range(l...
606ebd3762d14c1bfb3ac93ed045e048f3fb1427
laanbroekh70729/Lucky_Unicorn_git
/Lucky_Unicorn2.py
167
3.65625
4
# Generate random token import random tokens = ["horse", "zebra", "donkey", "unicorn"] for item in range(1, 15): picked = random.choice(tokens) print(picked)
b919a7bde732d2fa2a2600341b38326ef1a1e811
kchateau/advent
/2020/day_2/main.py
1,584
3.578125
4
class ReportRepair(): def parse_input(filename): with open(filename, "r") as my_file: input_parsed = [] for line in my_file: line = line.split() input_parsed.append({ "min": int(line[0].split("-")[0]), "max":...
f1e37e4248e19c780afbbb7b5edec09ec8115c94
kchateau/advent
/2020/day_9/main.py
1,799
3.5625
4
class EncodingError(): def parse_input(self, filename): with open(filename, "r") as my_file: data = [] for line in my_file: data.append(int(line.strip('\n'))) return data def check_list_for_pair(self, my_list, goal): for x in my_list: ...
20b75b2b6d7dd73263d5f31d02f9ed807413fd90
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex006.py
258
4.09375
4
import math numero = int(input('Insira um número inteiro: ')) print('O dobro de {} vale {}.'.format(numero, numero*2)) print('O triplo de {} vale {}.'.format(numero, numero*3)) print('A raiz quadrada de {} vale {:.2f}.'.format(numero, math.sqrt(numero)))
c6b1f9c547d8e6e690137881466ba3948858d98b
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex011.py
378
3.90625
4
largura = float(input('Insira a largura da parede (em metros): ')) altura = float(input('Insira a altura da parede (em metros): ')) print('Sua parede tem a dimensão de {:.2f}x{:.2f} m e sua área é de {:.2f} m^2.' .format(largura, altura, largura * altura)) print('Para pintar sua parede, serão necessários {:.2f} l...
7142f67a6a5e23c8f0720705f3f4127c9ffed5a7
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex050.py
417
3.890625
4
soma = 0 dicionario = { 1 : 'primeiro', 2 : 'segundo', 3 : 'terceiro', 4 : 'quarto', 5 : 'quinto', 6 : 'sexto' } for i in range(1, 7): numero = int(input('Insira o {} número: '.format(dicionario[i]))) if numero % 2 ==...
c78ca3e37465540bb0f4035985ad2463ce640969
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex022.py
468
3.84375
4
nomeCompleto = input('Digite seu nome completo: ').strip() print('Analisando o seu nome...') print('Seu nome em letras maiúsculas é {}.'.format(nomeCompleto.upper())) print('Seu nome em letras minúsculas é {}.'.format(nomeCompleto.lower())) print('Seu nome contém {} letras.'.format(len(nomeCompleto) - nomeCompleto.cou...
2833af1e9255f2e435f8800710129d42817d75cd
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex059.py
1,263
4.0625
4
inicio = True option = 4 while option != 5: if inicio == False: print("=-="*10) print('[ 1 ] Somar') print('[ 2 ] Multiplicar') print('[ 3 ] Maior') print('[ 4 ] Novos números') print('[ 5 ] Sair do programa') option = int(input('>>>>> Qual é a sua opção? ')...
a557165776b648dae5007453b3659a0f428ac9b8
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex086.py
380
3.96875
4
matrix = [] linha = [] for i in range(0,3): for j in range(0,3): linha.append(int(input('Digite um valor para [{}, {}]: '.format(i, j)))) matrix.append(linha[:]) linha.clear() print('-=' * 20) i = j = 0 while i < len(matrix): while j < len(matrix[i]): print('[{:^5}]'.format(matrix[i][j...
76bd2d0de14ed9413613aab3e77c7d82c3357bfd
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex068.py
1,223
3.6875
4
from random import randint print('=-=' * 14) print('{:^42s}'.format('VAMOS JOGAR PAR OU ÍMPAR!')) print('=-=' * 14) vitorias = 0 while True: while True: numeroUser = int(input('Escolha o seu número (de 1 a 10): ')) if numeroUser > 10 or numeroUser < 0: print('Número inválido. Escolha ...
88c9bcb3bc69cd7cd7110927266486744a1b9c3e
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex085.py
398
3.640625
4
pares = [] impares = [] numeros = [pares , impares] for i in range(1, 8): numero = int(input('Digite o {}o. valor: '.format(i))) if numero % 2 == 0: pares.append(numero) else: impares.append(numero) pares.sort() impares.sort() print('-='*20) print('Os valores pares digitados foram: {}.'.fo...
e03f8f82082f2d96739abcef2a9fdaadb29c508c
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex020.py
377
3.71875
4
import random print('Digite o nome de cada um dos quatro alunos a serem sorteados:') aluno1 = input('Nome do primeiro aluno: ') aluno2 = input('Nome do segundo aluno: ') aluno3 = input('Nome do terceiro aluno: ') aluno4 = input('Nome do quarto aluno: ') lista = [aluno1, aluno2, aluno3, aluno4] random.shuffle(lista) p...
f34ee47b0993ddc755461e315345130929e08a2c
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex104.py
319
3.984375
4
def leia_inteiro(_texto): while True: numero = str(input(_texto)) if numero.isnumeric(): return numero else: print('Erro! Digite um número inteiro válido!') numero = leia_inteiro('Digite um número: ') print('Você acabou de digitar o número {}.'.format(numero))
6b5fe200e052ad514dcece6d543cf2088317ada4
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex027.py
188
3.8125
4
nomeCompleto = input('Digite seu nome completo: ').strip().split() print('Seu primeiro nome é {}.'.format(nomeCompleto[0])) print('Seu último sobrenome é {}.'.format(nomeCompleto[-1]))
f40f083661a601ad6ce91f4b8b60f4e2b4ad8f2f
ajduberstein/titanic_predictions
/titanic_logit.py
1,341
3.515625
4
import pandas as pd import numpy as np from sklearn import linear_model """ Goal: Given features of a Titanic passenger, predict whether that passenger lived or died. Survived = was_first + was_second + was_female + age + fare + sibsp + parch + ...
80372221944fbf2c560fd597e48d5e447a0bd4dd
henrikac/randomturtlewalk
/src/main.py
1,077
4.375
4
"""A Python turtle that does a random walk. Author: Henrik Abel Christensen """ import random from turtle import Screen from typing import List from argparser import parser from tortoise import Tortoise args = parser.parse_args() def get_range(min_max: List[int]) -> range: """Returns a range with the turtles ...
0f7a6015be08ffbfcae7cf74aa519bb342c994ab
Trietptm-on-Coding-Algorithms/algopy
/algorithms/max_flow.py
2,967
3.890625
4
#!/usr/bin/env python #coding: UTF-8 # # Implementation of the push-relabel algorithm to solve the max flow problem. # # Copyright (c) 2013 Samuel Groß # from graph import * def _get_active_node(graph, s, t): for node in graph.nodes(): if not node is t and not node is s and node.overrun > 0: r...
ad10854ee1f3164d01e4de0aeb0a52dac08b8eb6
Mustafa-Mahmoud-5/Adventure-Python-Game
/game.py
4,285
3.90625
4
#!/usr/bin/python # -*- coding: utf-8 -*- import time import random enemy = '' rand = random.randint(1, 3) if rand == 1: enemy = 'thanos' elif rand == 2: enemy = 'Galactious' elif rand == 3: enemy = 'Loki' def message(message): print (message) time.sleep(2) def intro(): message("This is cal...
53ec2278380e9eb5b137a006ea22ea33d15d2b0e
Depleto/Grokking_Algorithms
/Algorithms.py
1,292
3.734375
4
def binary_search(sorted_array, item): low = 0 high = len(sorted_array) -1 while low <= high: mid = (low + high) // 2 guess = sorted_array[mid] if guess == item: return mid elif guess > item: high = mid-1 else: ...