blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
21d0209acc6b90699114fbb2e496a2ea542774b3 | MarcosPenin/FuncionesPython | /TablaMultiplicar1-5.py | 213 | 4.03125 | 4 | print("TABLA DE MULTIPLICAR 1-5")
num=1
cont=1
cont2=1
while cont2<=5:
print("Tabla del",num)
while cont<=10:
print(num,"*",cont,"=",num*cont)
cont+=1
cont2+=1
cont=1
num=num+1 |
7f0cb81b9c803e98a64b83652ec570831ab018b2 | andrewyang96/AdventOfCode2017 | /day09/tests.py | 881 | 3.53125 | 4 | from solution import group_score
from solution import count_canceled_chars
with open('input.txt') as f:
stream = f.readline().strip()
assert group_score('{}') == 1
assert group_score('{{{}}}') == 6
assert group_score('{{},{}}') == 5
assert group_score('{{{},{},{{}}}}') == 16
assert group_score('{<a>,<a>,<a>,<a>}'... |
32334206ca291a997282fef94b2cd9b76ed19798 | lixiangabcd08/ee5902-2dmesh-simulation | /network_map.py | 482 | 3.609375 | 4 | """
functions to link the coordinates x,y and id
"""
def coordinates_2_id(coordinates, m, n):
return coordinates[0] * n + coordinates[1]
def coordinates_2_id_list(coordinates_list, m, n):
id_list = []
for coordinates in coordinates_list:
id_list.append(coordinates_2_id(coordinates, m, n))
#... |
4a10cc43a963ec5cc6f2874902e96bbd2f3c34b6 | James-Cristini/oop_patterns | /proxy_pattern/proxy_1.py | 3,015 | 3.53125 | 4 | ### Provides a surogate or placeholder for another object in order to control access to it
# Instead of calling the thing you want to call, you call a thing that calls the thing you want to call
# Remote: When you to access a resource outside the 'safe' boundaries of your application
# Virtual: controls access to a res... |
22189f766000fdc22c5b422ae9c1f4d3f792634d | James-Cristini/oop_patterns | /strategy_pattern/strategy_1.py | 3,376 | 3.78125 | 4 | # 2.7
### Simple Strategy Pattern Example of using interchangable behaviors which can be defined 'at runtime' rather than Inheritance
## Goal is to keep the algorithms/behaviors separate from the client so that these algorithms can change or be altered without
## needing to make changes to the "client"
from __future__... |
dff44c74eacd471fcfea6a55626072c86637f3b8 | san81/LevenshteinDistance | /LevenshteinDistance.py | 2,259 | 3.6875 | 4 | class LvnDistance:
"""Class for calculating the Levenshtein Distance"""
dictionary = ["Bombay","Mumbai","Calcutta","Pune","Madras","Hyderabad","Delhi","Goa"]
def minValue(instance, a, b, c):
temp = None
if a<b:
temp=a
else:
temp=b
if temp<c:
... |
f014671e34d219c7ce252808929f69c402278a32 | singh-ankitkr/interestingCodingQuestions | /dfs/AllPathsSum.py | 1,272 | 3.78125 | 4 |
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class AllPathsToSum:
def __init__(self):
self.all_paths = []
self.current_path = []
def all_paths_to_sum(self, node, current_sum, required_sum):
... |
5f6ce3e0e284eb3e8616c100058e919277b3ec6d | singh-ankitkr/interestingCodingQuestions | /DepthFirstSearch/find_defined_sum.py | 1,087 | 3.78125 | 4 |
# In a binary tree find the path from root to leaf with a given sum.
from tree_node import TreeNode
from copy import deepcopy
path = []
paths = []
def find_paths(node, target_sum):
paths = []
path = []
def find_path(node, target_sum):
if node is None:
return False
if node.... |
689f2a8c3f9cac8d8e86ee51a733f016e38f84e1 | rioirinko/neobis-autumn | /hackerrank/medium/strings/minions.py | 418 | 3.515625 | 4 | def minion_game(string):
kevin=0
stuart=0
n=len(string)
for i in range(n):
if string[i] in ['A', 'E', 'O', 'I', 'U']:
kevin += n-i
else :
stuart += n-i
if kevin > stuart:
print ("Kevin", kevin)
elif stuart > kevin :
print ("Stuart", stuart)... |
865b6eb201d4a6e534db777ff83480d2a7aaaecd | rioirinko/neobis-autumn | /hackerrank/medium/interatools/Compress.py | 114 | 3.609375 | 4 | from itertools import groupby
s = input()
for a, b in groupby(s):
print(tuple((len(list(b)),int(a))),end=' ')
|
2ade01bbc452725a95ba509dfe253c83e7a391d0 | kanchanj3000/SeleniumPython | /demo1/factorial.py | 106 | 3.859375 | 4 | num = input("Enter the number") #7=6*5*4*3*2*1
res = 1
for i in range(1,num,1):
res *= i
print res
|
70e87094ec3683ffc8921b8c8a27691724e30d52 | kanchanj3000/SeleniumPython | /demo1/strings.py | 755 | 3.796875 | 4 | '''
string1 = "Kanchan"
string2 = "Mayur"
print (string2+string1)
print (string2*3)
print (string2[2:-1])
print (string1.count('n',0,7))
print (string1.find('n'))
print string2.upper()
print string2.isalnum()
print string2.isupper()
print string2.isupper()
print string1.split()
print len(string1)
#Tuples
x = ... |
a3898def9c4bcb51acfcb5807ab042ac098fd1da | kotaro0522/python | /procon20180115/two.py | 455 | 3.59375 | 4 | s = input()
t = input()
s_sorted = sorted(s)
t_sorted = sorted(t)
try:
for i in s_sorted:
for j in t_sorted:
if i < j:
print('Yes')
raise Exception
elif i == j:
t_sorted.remove(i)
break
else:
print(... |
a4a7df8244f857d638f6d0bd7c3297e8f3d057f4 | kotaro0522/python | /procon20180805/acCepted.py | 284 | 3.765625 | 4 | s = input()
def check(s):
if s[0] != 'A':
print('WA')
return
if s[2:-1].count('C') != 1:
print('WA')
return
s = s.strip('A')
s = list(s)
s.remove('C')
s = ''.join(s)
if s.islower() != True:
print('WA')
return
print('AC')
check(s)
|
3398e37718c4eb294a12e8143609c7654efc0744 | kotaro0522/python | /20180407/same_integers.py | 1,101 | 3.953125 | 4 | import math
number_list = [int(i) for i in input().split()]
even_counter = 0
for i in number_list:
if i % 2 == 0:
even_counter = even_counter + 1
def even_checker(n_list):
for i in n_list:
if i % 2 == 0:
return i
def odd_checker(n_list):
for i in n_list:
if i % 2 == 1:
return i
if ev... |
64e2fab7fbceacf64898be6388f99d8abff4f1af | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-0/calculator.py | 372 | 4 | 4 |
num1=input('Enter 1st number:')
num2=input('Enter 2nd number:')
ch=input('Enter the operation symbol(+,-,*,/):')
def calc(var,a,b):
switcher = {
'+': a+b,
'-': a-b,
'*': a*b,
'/': a/b
}
return switcher.get(var,"Invalid Choice")
print('The o... |
bce5c62eba0f32e3b71c213d897193562f220a98 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-2/tempconvert.py | 174 | 4.1875 | 4 | tempincel=int(input('Enter the temprature in celsius:'))
#after taking input from user, following converts it into °F
tempinfar=tempincel*1.8+32
print(str(tempinfar)+'°F')
|
35d832a7a0859b5c58cb0afbf6832d905ab095dc | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-1/recurfact.py | 263 | 4.28125 | 4 | num=int(input('Enter a number to calculate factorial:'))
#below function uses recursion
def fact(a):
if(a>0):
#while value of a is greater than 1
return (a*fact(a-1))
else:
#when it finally becomes 1
return 1
print(fact(num)) |
e479001c39968fb64f4ef3250bd60375b4a9d09c | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-23/SecondHighest.py | 415 | 3.796875 | 4 | if __name__ == '__main__':
n = int(input('Enter no. of elements: '))
arr=[]
for i in range(0,n):
arr.append(int(input()))
high=sechigh=-32768
for i in range(len(arr)):
if(high<arr[i]):
high=arr[i]
print('Now high is '+str(high))
for i in range(len(arr)):
... |
b30bdda8e2744d0d0475e759350f6024fdb583f6 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-31/StringFirstLetterCap.py | 245 | 3.5 | 4 | x=str(input())
dcn={}
for i in range(len(x)):
if(i==0 or x[i-1]==' '):
dcn[i]=x[i].upper()
finalstr=''
for j in range(len(x)):
if (j in dcn.keys()):
finalstr+=dcn[j]
else:
finalstr+=x[j]
print(finalstr) |
beb0c0bf868f3b3b30acb53af047597e4067379e | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-15/charoccurence.py | 541 | 4.03125 | 4 | string = str(input('Enter the string:'))
occur={}
for i in range(len(string)):#check for every character in the string
check=string[i]
count=0
for j in range(len(string)):#whenever that particular character occurs in the string
if(string[j]==check):
count+=1#increment the counter
if(... |
bbce99eb5d7e789ec48a8f5aadf75ef77b0c0994 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-36/SetsIntersection.py | 343 | 3.640625 | 4 | m = int(input()) # no of elements in first set
x = set(map(int, input().split())) # elements separated by a space
n = int(input()) # no of elements in 2nd set
y = set(map(int, input().split())) # elements separated by a space
x = x.intersection(y) # perform intersection
count = 0
for i in x:
count += 1
print(c... |
f23fadb49e1f9e955461babd848f7a445f2ef794 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-28/StringSwapCase.py | 217 | 3.828125 | 4 | strin=str(input())
convrt=''
for i in strin:
if(i.islower()):
i=str.upper(i)
convrt+=i
elif(i.isupper()):
i=str.lower(i)
convrt+=i
else:
convrt += i
print(convrt)
|
b1885e2c4f4460f1ec9c4b52649467aaa5768328 | amanjaiswalofficial/100-Days-Code-Challenge | /code/python/day-28/StringAlphanum.py | 589 | 4.3125 | 4 | """Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum() return true or false based on it
other methods: isupper() islower() isalpha() isdigit()"""
s1=s2=s3=s4=s5=False
strin=str(input())
for i i... |
cc37ab007f032c6d1bb73e62354d8528d6b10955 | adefisayoA/python_class | /OOP-concept/python_Polymorphism.py | 3,313 | 4.28125 | 4 | # Example - Person, Employee finance calculation ############################
#
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
# inherit the Person class and use it inside the Employees cla... |
ed40ca05902438e6576b31dd39dde08899ac8a53 | adefisayoA/python_class | /flow_control.py | 1,857 | 4.375 | 4 | # conditional statements (if, elif, else),
# loops (for, while).
# # # if statement
# # if <expr>:
# # <statement> # one way logic
# else:
# <statement> # this is the option to take
# if x > y:
# print(f"{x} is greater than {y}")
# else:
# print(f"{x} is less than {y}")
#
# # rich man, good man,... |
3ab084fcf00ce4190a6d49b1564fa088b2063e75 | HeRaNO/OI-ICPC-Codes | /HSAHRBNUOJ/P30xx/P3096.py | 158 | 3.53125 | 4 | def fac(x):
ans = 1
for i in range (2,x+1):
ans = ans * i
return ans
n = int(raw_input())
ans = 1
for i in range (2,n+1):
ans = ans + fac(i)
print ans
|
563a011611670850efa5b270b98e8f86ead1dda7 | DataSorcerer/Bike-sharing-model-and-analysis | /helper_methods.py | 1,075 | 3.734375 | 4 | #import necessary packages
from sklearn import preprocessing
import pandas as pd
def label_one_hot_encode(df, col_name):
"""First label encode the specified column and then one hot encode it
Arguments:
df: pandas.DataFrame that consists of the column to be encoded
col_name: categorical attribut... |
de476e1b99b1a73ccbc4f1b23b1a0cd3c0a0c907 | whjr2021/G11-C13-V1-SAA1-Solution | /C13_SAA1_Solution.py | 313 | 4.15625 | 4 | # Define a funtion "simple_interest" to calculate simple interest given principal amount(p), rate of interest(r) and time(t)
# SI = (P*T*R)/100
def simple_interest(p,t,r):
si = (p*t*r)/100
return si
# Call the function "simple_interest()" and print the result
si = simple_interest(3000,5,2)
print(si) |
d70347b50a23fd5b36b795a4e16ddc865e1a4d12 | Decalogue/aiml3 | /aiml/WordSub.py | 3,450 | 4.4375 | 4 | """This module implements the WordSub class, modelled after a recipe
in "Python Cookbook" (Recipe 3.14, "Replacing Multiple Patterns in a
Single Pass" by Xavier Defrang).
Usage:
Use this class like a dictionary to add before/after pairs:
> subber = TextSub()
> subber["before"] = "after"
> subber["begin"] =... |
e0ff872d2790564a6977d689d820fd3f0b58c564 | GongGecko/GitSun | /gong_master_ea/fractal_geometry_tree.py | 782 | 3.625 | 4 | # 分形几何树
from turtle import *
# 设置色彩模式是RGB
colormode(255)
lt(90)
lv=14
l=120
s=45
width(lv)
# 初始化RGB颜色
r=0
g=0
b=0
pencolor(r,g,b)
penup()
bk(l)
pendown()
fd(l)
def draw_tree(l,level):
global r,g,b
# 保存当前笔刷宽度
w=width()
# narrow笔刷宽度
width(w*3.0/4.0)
r=r+1
g=g+2
b=b+3
pencolor(r... |
813acd67cb2479cbb881e4bb88eed5213e02387c | A01375137/Tarea-07-2 | /Tarea 7-2.py | 5,070 | 3.640625 | 4 | # Autor: Mónica Monserrat Palacios Rodríguez
# encoding: UTF-8
# Tarea 7.2
#Función que crea una lista con solo los pares a través de un for y un if
def crearListaConPares(lista):
nuevaLista=[]
for dato in lista:
if dato%2==0:
nuevaLista.append(dato)
return nuevaLista
#Función que encu... |
166efdc76afd19d06e36af3fc48bb50d0c09a451 | barneypotter24/recursion_workshop | /count_terminal_nodes.py | 706 | 3.65625 | 4 | # count_terminal_nodes.py
from classes import *
def count_terminal_nodes(n):
'''From a given node, count all of its descendant terminals
'''
return # PUT YOUR RECURSIVE NODE COUNTER HERE
#### HELPER FUNCTIONS ####
def test():
small = build_small_tree()
med = build_medium_tree()
large = b... |
ab77b735ac817109ebc5b2731a4abb330892caf8 | KevinWu2005/Year9DesignPythonKW | /3DShapesCalculator/3DShapesCalculator4.py | 3,789 | 3.75 | 4 | import math
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
#Functions
def on_closing():
print("closing")
#Step 2 create messagebox
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
def calcVolumeCone(*args):
if int(cone1.get()) >= 0 and int(cone2.get()) >= 0:
... |
a18f85c5daea0d86fb6d33aba476172a55d6f73f | de223/textClassification | /extract_top.py | 2,076 | 3.5 | 4 | import csv
import math
with open('./result/pretrained_embedding (desktop)/test.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
rows = []
for row in reader:
rows = rows + [row]
values = [float(pos_value)-float(neg_value) for pos_value,neg_value in zip(rows[1],rows[2])]
le... |
5159f606c4478fa1efa95c07674779719ccda30c | Predstan/Analyzing-the-Informed-Search-Algorithms | /random_board.py | 456 | 3.734375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from Board import Board
import sys
import os
if (len(sys.argv) != 3):
print()
print("Usage: %s [seed] [number of random moves]" %(sys.argv[0]))
print()
sys.exit(1)
def main():
seed = int(sys.argv[1])
number_of_moves = int(sys.argv[2])
goal = ... |
b6318680a5b3be702dd2b8470c39d17053234319 | Vgandhi9/artifacia-client-python | /artifacia/artifacia.py | 4,608 | 3.703125 | 4 | import json
import requests
class Client:
"""
This is the entry point in Python client API.
if you are going to use our API, first of all you should instanciate
client objent with your username and passwrod which you got from the dashboard.
Now start using Artifacia recommendations APIS.
"""
... |
2a6802835f229c64096ed63db87d35d55c81df0c | Taikamya/TestingPyCode | /multiprocessing_test.py | 865 | 3.609375 | 4 | #!/usr/bin/env python3
# Ver_1.0.0_3
from multiprocessing import Process
from time import time
def time_and_exec(func, name):
'''
Create, execute, terminate and join a Process(func),
whilst timing its execution.
'''
before = time()
p1 = Process()
p1.start()
func()
p1.terminate()
... |
3e6193d49a6a15d2480ce2feea6c63b04e2bfd15 | Phong-Hua/Udacity_Problems-vs.-Algorithms | /Problem4.py | 5,737 | 4.21875 | 4 | """
Dutch National Flag Problem
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
You're not allowed to use any sorting function that Python provides.
Note: O(n) does not necessarily mean single-traversal. For e.g. if you traverse the array twice,
that would still be an O(n) ... |
54d56e79085004d3f618be348b60e7c0154e26e0 | Abhiforcs/mypythonworkspace | /findmailer.py | 266 | 3.859375 | 4 | count = 0
fhand = open(input('Enter the file name to look in: '))
for ln in fhand:
if ln.startswith('From '):
words = ln.split()
print(words[1])
count = count + 1
print('There were',count,'lines in the file with From as the first word')
|
d6cb7fc55dc4299e0dd926acac5d168191fdd780 | Abhiforcs/mypythonworkspace | /list_ops.py | 291 | 3.890625 | 4 | ls = list()
while True:
val = input('Enter a number: ')
try:
int(val)
ls.append(val)
except:
if val=='done':
print('Maximum:',max(ls))
print('Minimum:',min(ls))
break
print('Enter only numeric')
exit()
|
ba38fcf942c821478083fdd18626a1de8c473ed4 | rahulruzz/ProjectEuler | /Problem10.py | 361 | 4 | 4 | import math
def isPrime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, math.floor((math.sqrt(n))) + 1, 2):
if n % i == 0:
return False
return True
sum = 2
for x in range(1, 2000001, 2):
if isPri... |
164f3c4e290e1417bb4f27afc4128cf03137a86b | ClassUserName/SelfTaughtProgrammerGitHub | /chp6_ex4.py | 291 | 3.921875 | 4 | # TODO change the string "Where now? Who now? When now?" using a method that
#returns the list separated by the question marks
string_one = "Where now? Who now? When now?"
list_one = string_one.split("?")
list_two = [i+"?" for i in list_one]
list_two.pop()
print(list_one)
print(list_two)
|
af210b20975be57d4e0f54ba22b97de3dd482842 | JohnSpencerTerry/WorkBlocks | /windows/window.py | 467 | 3.5 | 4 | import tkinter as tk
# base class for all windows - holds any common functionality we identify
class Window:
def __init__(self, window: tk.Tk, title: str = "Work Blocks"): # default title
self.__window = window
self.__window.title(title)
def render(self):
self.__window.mainloo... |
69d66ab227413b45378965c13c924076fccb9dc0 | Jacksonleste/exercicios-python-curso-em-video | /ex075.py | 485 | 3.9375 | 4 | num = (int(input('insira um número: ')), int(input('insira um número: ')),
int(input('insira um número: ')), int(input('insira um número: ')))
print(f'O valor 9 apareceu {num.count(9)} vezes')
cont3 = num.count(3)
if cont3 > 0:
print(f'O valor 3 foi visto primeiramente na {num.index(3)+1}ª posição')
else:
... |
e73577eebdd078fe817c14af3b7936f972722511 | Jacksonleste/exercicios-python-curso-em-video | /ex111/ultilidadescev/moeda/__init__.py | 2,878 | 3.828125 | 4 | def moeda(n):
"""→ Função que formata moeda.
:param n: Valor a ser formatado
:type n: Numerico
:return: valor formatado ex:"R$25,00"
:rtype: string
"""
return f'R${n:.2f}'.replace('.', ',')
def aumentar(n, p, form=False):
"""→ aumenta um valor usando porcentagem.
:param n: valor ... |
a7d93f7ce1d61001cf8c64f8e2b10652bd2c6e88 | Jacksonleste/exercicios-python-curso-em-video | /ex068.py | 844 | 3.59375 | 4 | from random import randint
print(f'''{'=-' * 15}
VAMOS JOGAR PAR OU ÍMPAR
{'=-' * 15}''')
vit = der = 0
while True:
cpu = randint(0, 10)
jog = int(input('insira um valor: '))
escolha = ' '
while escolha not in 'PI':
escolha = str(input('[I/P]: ')).strip().upper()
soma = jog + cpu
print(... |
20934b0c4a6adcdbe39b122165e72826adacace9 | Jacksonleste/exercicios-python-curso-em-video | /ex085.py | 319 | 3.5625 | 4 | lista = [[], []]
for c in range(0, 7):
n = int(input(f'Insira o {c+1}º valor: '))
if n % 2 == 0:
lista[0].append(n)
else:
lista[1].append(n)
print('•═' * 25)
print(f'Os numeros pares são: {sorted(lista[0])}')
print(f'Os numeros ímpares são: {sorted(lista[1])}')
print('•═' * 20) |
595c0536841c04e20503f89d95db8642d706d928 | Jacksonleste/exercicios-python-curso-em-video | /ex096.py | 250 | 3.59375 | 4 | def area(l, c):
print(f'A área do terreno {l}x{c} é igual a {l*c}m²')
print('Controle de terrenos')
print('-'*25)
largura = int(input('insira a largura(m): '))
comprimento = int(input('insira o comprimento(m): '))
area(largura, comprimento) |
009bafaa3861aa23e68404a0767f5c9cfece747e | Jacksonleste/exercicios-python-curso-em-video | /ex040.py | 353 | 3.96875 | 4 | nota1 = float(input('insira sua primeira nota: '))
nota2 = float(input('insira sua segunda nota: '))
media = (nota1 + nota2) / 2
print('sua média foi {:.2f}'.format(media))
if media < 5.0:
print('Você foi reprovado.')
elif 7 > media >= 5.0 :
print('Você está de recuperação.')
elif media >= 7.0:
print('Parab... |
5c712df6a5989cc1996b3e84477515eb8f4bf66e | Jacksonleste/exercicios-python-curso-em-video | /ex031.py | 456 | 3.703125 | 4 | print('\033[31;1m-=-'*10)
print('\033[33mCALCULAODRA DE PASSAGEM')
print('até 200KM: R$0,5 por KM')
print('acima de 200KM: R$0,45 por KM')
print('\033[31m-=-'*10)
km = float(input('\033[30mInsira a distância da sua viagem em KM:'))
p1 = km*0.5
p2 = km*0.45
if km <= 200:
print('uma Viagem de \033[32m{}KM\033[30m cus... |
ffaba035e03aa43fcc8c1047ecc21d732d8ad73c | Jacksonleste/exercicios-python-curso-em-video | /ex048.py | 188 | 3.75 | 4 | soma = 0
cont = 0
for c in range(0, 501, 3):
if c % 2 != 0:
soma = soma + c
cont = cont + 1
print('a soma de todos os {} valores solicitados é {}'.format(cont, soma))
|
f28ec5d57f713c2c8eb088f68da88e957ca96f69 | Jacksonleste/exercicios-python-curso-em-video | /ex043.py | 404 | 3.703125 | 4 | peso = float(input('insira seu peso:(KG)'))
alt = float(input('insira sua altura(M)'))
imc = peso / (alt * alt)
print('seu IMC é de {:.1f}, e você está '.format(imc), end='')
if imc < 18.5:
print('abaixo do seu peso ideal')
elif imc < 25:
print('no seu peso ideal')
elif imc < 30:
print('em sobrepeso')
elif ... |
a139fec35c50e53f4046a5ee88a68e13a8c00dc1 | Jacksonleste/exercicios-python-curso-em-video | /ex045.py | 873 | 3.703125 | 4 | from random import choice
from time import sleep
jog = int(input('''Suas opções:
[1] PEDRA
[2] PAPEL
[3] TESOURA
Qual sua jogada? '''))
if jog == 1 or jog == 2 or jog == 3:
if jog == 1:
jog = 'Pedra'
elif jog == 2:
jog = 'Papel'
elif jog == 3:
jog = 'Tesoura'
cpu = choice(['Pedr... |
90a7cd3af73cc65d32932aa1274be8bae190f368 | Jacksonleste/exercicios-python-curso-em-video | /ex014.py | 218 | 3.59375 | 4 | cel = float(input('\033[30;1mqual a temperatura em C°?'))
far = 1.8*cel+32
ke = cel+273.15
print(' a tempreatura \033[31m{}C°\033[30m equivale a \033[36m{:.2f}F°\033[30m e \033[36m{}K°\033[m '.format(cel, far, ke)) |
aac65a5576e9d9cce149ce6897cac11350b07826 | DavidUps/pythom | /01_validacionDni/dni.py | 301 | 3.828125 | 4 |
letras = "trwagmy"
numero = int(input("Escribe tu dni: "))
numero = numero % 23
letra = input("Escribe tu letra: ")
if letra == letras[numero]:
print("Tu DNI es correcto")
else:
print("La letra de que corresponde a ese DNI es: " + letras[numero] +"\n" + "la que tú as puesto es: " + letra)
|
27865c3c7aea9306d4550918ed3360c3e68895ee | liujiapengdezhanghao/python- | /坑朱笑阳.py | 768 | 3.6875 | 4 | """
只需复制即可使用
"""
from tkinter import *
import tkinter.messagebox
def qw_qw(q):
if q == "朱笑阳":
i = "是猪"
elif q == "刘家朋":
i = "是天才"
elif q == "杨光坤":
i = "天才他妈"
else:
i = "是人"
return i
def pr():
label = Label(top,text = qw_qw(w.get()))
la... |
e963b4d050ab819c2453d3077454d4f702d2f9b5 | udiland/Udi | /ete3_tutorial.py | 6,073 | 4.28125 | 4 | import ete3
# load tree (newick format)
t = ete3.Tree("tree.newick", format=1)
# show tree
print(t)
print()
# write to file
# t.write(outfile="")
'''
When you load a tree you will be always placed at the root of the tree. You can
check that by typing:
'''
print(t.is_root())
'''
To go one node down in the tree str... |
530f36eceded1909ad63de9a59c07571cb497160 | devinaconley/py-object-factory | /examples/product_orders.py | 3,630 | 3.75 | 4 | """
product order example
use the objectfactory library to handle product orders across multiple vendors. validate incoming
order data, load as python objects, and calculate price and estimated delivery
"""
import objectfactory
def main():
raw_orders = [
{
'_type': 'DollarStoreProduct',
... |
84e7a5f1d7696c0df579928b2dd6d1712c7f5e4e | GarimaChauhan16/Python-PyBank-and-PyPoll | /PyPoll/PyPoll.py | 2,312 | 3.703125 | 4 | import os
import csv
# csv File Read
csvpath = os.path.join('..','Resources', 'election_data.csv')
with open (csvpath, 'r') as csvfile:
csvreader=csv.reader(csvfile, delimiter =',')
csv_header=next(csvreader)
# Create Indivisual Lists
Voter_ids = []
Counties = []
Candidates= []
for row in csvr... |
fc596fbbb973ba3469f323d53db131db1f4a22d2 | AaronJi/RL | /python/RLutils/algorithm/policy_gradient.py | 1,238 | 3.5625 | 4 |
""" The policy gradient algorithm
a policy-based method (instead of policy-value method)
input:
t: step
Gt: the long-term return at step t
w_grad_a_with_s: the direction of param which most increases the possibility of repeating the current action on future visits to the current state
"""
import numpy as np
def cal... |
71c627988392d238c50b48e72a7a4cb78a47c534 | evan1026/projectEuler | /src/problem25.py | 470 | 3.890625 | 4 | #!/usr/bin/python
prev1 = 1
prev2 = 1
def findDigits(num):
tempNum = num
digits = 0
while(tempNum):
digits += 1
tempNum /= 10
return digits
def fibNextIsTheOne():
global prev1
global prev2
nextOne = prev1 + prev2
prev2 = prev1
prev1 = nextOne
return findDigits(p... |
8053f90d1a77fb1926d6e984939af5da7490b9a0 | evan1026/projectEuler | /problem27 | 1,466 | 3.578125 | 4 | #!/usr/bin/python3
import time
def numPrimes(a,b):
n = 0
while is_prime(n*n + a*n + b):
n += 1
return n - 1
primeDict = {1: False, 2: True, 3: True, 4: False, 5: True} #Setting up a prime cache with a few values
def is_prime(n):
global primeDict
if n in primeDict:
return primeDic... |
c566bdd2985797ac8adacc7191e0b10dacc16940 | nicoroulet/pap | /pap-tp4/ej3/ej3.py | 2,461 | 3.75 | 4 | from math import atan2, pi # atan2(y,x): angulo en radianes del vector (x,y) con respecto a la horizontal, en sentido antihorario
from sys import exit
class point(tuple):
def __add__(self, other):
return point(s + o for (s, o) in zip(self, other))
def __sub__(self, other):
return point(s - o fo... |
d781189996d5f87e86a8578d19c093e059494945 | kaylabracall/dat129_ccac | /Week1/Bracall_python2_homework.py | 1,294 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 20:46:56 2020
@author: kaybr
"""
import csv
def process_capital_projects():
''' this function iterates over the capital_projects csv file to determine
percentage of completed projects'''
file = open('capital_projects.csv', newline= '')
reader = c... |
7553bdb8fd1632eebfd213b873ec2944b197dbd7 | joachimth/GanttMaker | /GanttGrapher.py | 8,001 | 3.5 | 4 | ###############################################################################
# Filename: GanttGrapher.py
# First written: 08-20-2016
# Author: Samuel Miller
#
# Description: This is a simple program that uses Plotly software to make a
# Gantt chart for repeated tasks, taking the schedule data from a .csv file.
####... |
1b49a59d6ba5750702f6a6687e6d8f219873e9ab | TaeKyoungKim/lecture2 | /print_name.py | 200 | 3.6875 | 4 | def print_name(name):
for i in range(len(name)):
print(i+1,'번째는',name[i])
name_data = ['홍길동', '양만춘','이순신','안중근']
print( name_data)
print_name(name_data)
|
48f2cf824063379bcd3a17343800e5fd70ba772d | wtufhv/zj | /Days02/圆的半径、周长计算.py | 379 | 4.0625 | 4 | '''
输入半径计算圆的周长和面积
Version:0.1
Author:余超
'''
import math
#导入math函数
radius=float(input('请输入圆的半径'))
#radius赋值为浮点型数值
perimeter=2*math.pi*radius
area=math.pi*radius**2
print('周长:%.2f'%perimeter)
#打印周长为perimeter,保留2位小数
print('面积:%.2f'%area)
#打印面积为area,保留2位小数 |
77142dfbc69707c83b125deeafb846dac854cb81 | wtufhv/zj | /Days03/分段函数求解2.py | 282 | 3.890625 | 4 | """
分段函数求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
Version: 0.1
Author: 余超
"""
x=float(input('x='))
if x>1:
y=3*x-5
else:
if x>=-1:
y=x+2
else:
y=5*x+3
print('f(%.2f)=%.2f'%(x,y)) |
2eace89b6e91189fa214e6a36f6eff9a6eb89fcc | Ashishprashar222/python-programs | /print_func.py | 344 | 4.40625 | 4 | '''Read an integer N.
Without using any string methods, try to print the following:
123...N
Note that "" represents the values in between.
Input Format
The first line contains an integer N.
Output Format
Output the answer as explained in the task.
Sample Input
3'''
n = int(input())
for i in range(n):
... |
10bb188f825698119e26aeda015ff436441cdecd | Ashishprashar222/python-programs | /oop/dunder.py | 986 | 3.703125 | 4 | class company: #class
increment = 1.5
no_of_worker= 0
def __init__(self,fname,lname,salary): #constructor
self.fname=fname
self.lname=lname
self.salary=salary
company.no_of... |
5b6c6a73ddb3aff344cf4f35f10c2de56b67cb1f | yanermen/self_taught_exercises | /factorial.py | 174 | 3.96875 | 4 | def factorial(number):
result = 1
for x in range(1, number + 1):
result *= x
print(str(x) + "!\t = " + str(result))
return result
factorial(53)
|
cd3cb3e305599a460b678ddd6229ed40d3786f24 | UGureev/pyEssentials | /myhashmap.py | 3,576 | 3.984375 | 4 | class LinearMap:
"""
обычная Map, в составе список, в котором хранятся кортежи (key, value)
"""
def __init__(self):
self.items = []
def add(self, k, v):
"""
добавляет в список кортеж (key, value)
"""
self.items.append((k, v))
def get(self, k):
""... |
ba58422c40779debf042922dc7bc2c705c5c104a | ramprasadtx/SimplePrograms | /prem4.py | 655 | 3.546875 | 4 | #required output (from Lowest to Highest points)
#Newcastle 18
#Spurs 25
#Leicester 26
#Liverpool 31
team_info = { 'Leicester': 26,'Liverpool': 31,'Newcastle': 18, 'Spurs': 25 }
point_list = []
for points in team_info:
point_list.append(team_info[points])
new_point_list = (sorted(point_list))
team_info_by_point... |
06608f1a9292b4bc0b6b66025bf7689a4df0bde9 | sophiahoffman/student-exercises-type | /instructor.py | 786 | 3.71875 | 4 | from student import Student
from cohort import Cohort
# You must define a type for representing an instructor in code.
# First name
# Last name
# Slack handle
# The instructor's cohort
# The instructor's specialty (e.g. dad jokes, excitement, dancing, etc.)
# A method to assign an exercise to a student
class Instruc... |
28f9c2d0859ebcbb0d2627039795908a03a80d91 | jeremiahmarks/dangerzone | /scripts/python/scratchpad_dp6Mar15_hard_numberChains.py | 11,419 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Jeremiah Marks
# @Date: 2015-03-08 19:24:27
# @Last Modified 2015-03-10
# @Last Modified time: 2015-03-10 20:17:48
##########################################
## from http://redd.it/2y5ziw
##########################################
## Description at bottom of f... |
33add4aa9d0b1b5300e3de1109a1ed6ceb2a7593 | jeremiahmarks/dangerzone | /scripts/python/hackerrank/countingSort2.py | 448 | 3.75 | 4 |
# from https://www.hackerrank.com/challenges/countingsort2
def countingsort(ar):
results=[]
retString=""
for x in range(100):
results.append(ar.count(x))
for y in range(len(results)):
if (results[y]==0):
pass
else:
for t in range(results[y]):
retString +=str(y)+" "
return retString
m = input(... |
45a527fb97cf5941939193bad36dbdd18043cf6f | jeremiahmarks/dangerzone | /scripts/python/hackerrank/flowers.py | 1,446 | 3.96875 | 4 |
# from https://www.hackerrank.com/challenges/flowers
# Problem Statement
# You and your K-1 friends want to buy N flowers. Flower number i has cost ci.
# Unfortunately the seller does not want just one customer to buy a lot of
# flowers, so he tries to change the price of flowers for customers who have
# already... |
4f98250bf2ab379747dcd0aef4cda3549fa97889 | Yashwant-Code98/K-Means- | /K-Means !.py | 855 | 3.578125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# See first five records of dataset !
print(diabetic.head())
# Extract Age & Outcome Column from dataset !
diabetic = diabetic[['Age','Outcome']]
# Split the model into training & testing
x = diabetic[['Age']]
y = diabetic[['Outcome']]
from ... |
8755a482fa684a9b5be75fa765ba898ffc40e0da | ahrenstein/GPG-Bulk-File-Management | /SourceCode/gpg_files_bulk_manage.py | 9,061 | 3.578125 | 4 | #!/usr/bin/env python3
"""A simple Python script that allows you to encrypt/decrypt
multiple files in a path without them being zipped into a single encrypted archive."""
#
# Python Script:: gpg_files_bulk_manage.py
#
# Linter:: pylint
#
# Copyright 2019, Matthew Ahrenstein, All Rights Reserved.
#
# Maintainers:
# - Ma... |
380251594381d35c14e541274d4daeb42dedb762 | ziqingye0210/AI-with-Pyke | /src/object_box.py | 2,966 | 3.8125 | 4 | # -*- coding: utf-8 -*-
#####################################################################
# This program is free software. It comes without any warranty, to #
# the extent permitted by applicable law. You can redistribute it #
# and/or modify it under the terms of the Do What The Fuck You Want #
# To Public Lic... |
e574b36436cd33cad3eb9f5ef25e0952dc7748e0 | Tashwri93/Python-Exercise6 | /exercise6.4.py | 535 | 3.78125 | 4 | person_one = {
'name': 'dylan',
'lastname': 'kawende',
'age': '23',
'city': 'london'}
person_two = {
'name': 'tashan',
'lastname': 'wright-mckenzie',
'age': '26',
'city': 'london'}
person_three = {
... |
65871e3c53028c9d4a70e1b3aa99d02f4f5d139b | ChaoMa0459/MC-EC602 | /EC602/hw4/modeling.py | 3,513 | 3.890625 | 4 | # Copyright 2017 Chao Ma mc163@bu.edu
class Polynomial():
"My Polynomial"
# pass
def __init__(self, poly = []):
"constructor"
self.l = len(poly)
self.coef = poly[:]
self.power = []
for i in range (self.l):
self.power.append(self.l - i - 1)
def __add__(self, poly):
"addition"
result = Polynomial(... |
c596e7ace53eebd23476a744ce4e5773776c15b9 | drlsv91/first_python_lesson | /start_section/classes.py | 8,109 | 4.40625 | 4 | # CLASSES
# a class is a blueprint for creating new object
# an object is an instance of a class
# CREATING CUSTOME CLASS IN PYTHON
# class Point:
# def draw(self):
# print("draw")
# point = Point()
# print(point)
# class Point:
# def __init__(self, x, y): # this is the constructor function
# ... |
2d3c997897deb9b256162a4d52a1bdefb6020f91 | limiyou/Pyproject | /1python基础/class9_文件操作/demo4_readlines.py | 314 | 3.53125 | 4 | """
读取的另外两个方式:
readline readlins
"""
#readline 读取第一行
with open("demo.txt ",encoding='utf8')as f:
print(f.readline())
#readlins #读取多行,一列表的形式得到且可以展示出换行符
with open("demo.txt",encoding="utf8") as f1:
print(f1.readlines()) |
61472d40d926a7e7626bfc661260bf868b5e3ca7 | limiyou/Pyproject | /1python基础/class9_文件操作/demo3_w & a.py | 533 | 3.984375 | 4 | """
写入操作
"""
#写入:write w
#w模式比较危险,如果之前已有同名文件,用w会覆盖之前的内容
# with open ("demo.txt",mode='w',encoding="utf8")as f:
# print(f.write("小hong"))
#todo:a add 追加模式
with open("demo.txt",mode='a',encoding="utf8")as f1:
f1.write("李米柚啊aa ")
f1.write("小米柚1")
f1.write("小米柚2")
f1.write("小米柚3")
with o... |
f670d78cce8836c12c093e07235205afd8fe3496 | limiyou/Pyproject | /1python基础/class8_func2/d7_函数的作用域2.py | 351 | 3.9375 | 4 | # 修改变量
"""
def add(a,b):
#局部变量
c=a+b
return c
#todo:外面是不能修改函数内部变量
#c_copy #会报错
"""
#todo:函数内部可以修改全局变量,但是 要加上 global
c=8
def add(a,b):
#局部作用域
global c
c=c+3
#c+=3
return c+a+b
print(add(1,2))
|
204b494253ff4e4be502dbc0447ffc59485f8849 | limiyou/Pyproject | /1python基础/class4 list and dict/demo04_list _method.py | 416 | 3.96875 | 4 | """
列表的方法
-index 获取列表值
-count 计数
-sort 排序
-reverse
-clear
"""
lst=[1,2,3,5,3]
print(lst.index(3)) #查找第一次出现的索引值
print(lst.count(3))
#排序(正向)
#lst.sort()
#print(lst)
#逆序,反向倒序
#lst.reverse()
#print(lst)
#反向排序,相当于:[::-1]
lst.sort(reverse=True)
print(lst)
#清除列表:clear ()
lst.clear()
print(lst) |
66747b6056c5774b327d4918a3feebdc369b28da | limiyou/Pyproject | /1python基础/class1/homework/1.py | 278 | 3.671875 | 4 | """现在有字符串:str1 = 'python cainiao 666'
1、请找出第 5 个字符。
2、请找出第 3 到 第 8 个字符。
"""
str1 ="python cainiao 666"
#1、请找出第 5 个字符。
print(str1[4])
#请找出第 3 到 第 8 个字符。
print(str1[2:7]) |
c316ca4bdd591c2cdf545f8db725494a85cb4b85 | limiyou/Pyproject | /1python基础/class10_路径/homework.py | 1,877 | 4.28125 | 4 | #1. 异常捕获的语法是什么样的? 请列举你会的错误类型。
KeyError
IndexError
IOError
SyntaxError
ZeroDivisionError
#2输入用户的体重身高,计算 bmi, (考虑异常情况)
# 输入一个人的身高(m)和体重(kg),根据BMI公式(体重除以身高的平方)计算他的BMI指数
# a.例如:一个65公斤的人,身高是1.62m,则BMI为 : 65 / 1.62 ** 2 = 24.8
# b.根据BMI指数,给与相应提醒
# 低于18.5: 过轻,18.5-25:正常,25-28:过重,28-32:肥胖,高于32:严重肥胖
# def get_B... |
3f380cbafdcc2ea434cd0b8cc3c1a638fb7911ee | limiyou/Pyproject | /1python基础/class4 list and dict/homework.py | 465 | 3.5625 | 4 | """1、.删除如下列表中的"矮穷丑",写出 2 种或以上方法:
info = ["yuze", 18, "男", "矮穷丑", ["高", "富", "帅"], True, None, "狼的眼睛是啥样的"]
"""
info = ["yuze", 18, "男", "矮穷丑", ["高", "富", "帅"], True, None, "狼的眼睛是啥样的"]
info.remove("矮穷丑")
print(info)
info.insert(3,["矮穷丑"])
print(info)
info.pop(3)
print(info)
info.append("矮穷丑")
print(info)
de... |
6e96c0d1aaa91f99354aad8d2d04393dfbb23ddc | limiyou/Pyproject | /api_testing/testcases/practice/practice_正则.py | 2,232 | 3.609375 | 4 | import re
# todo:re.match与re.search的区别
# re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
#re.match(pattern,string,flags)
#pattern:匹配的正则表达式
#string:要匹配的字符串
#flags:标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配。。
print(re.match('www','www.rubbon.com').span()) #在起始位置匹配 (0,3)
print(re.... |
ba0a8e2900cc4f6f04288fb72f9c2914347489f0 | limiyou/Pyproject | /1python基础/class4 list and dict/homework2.py | 449 | 3.953125 | 4 | """2、现在有一个列表 li2=[1,2,3,4,5],
请通过相关的操作改成li2 = [0,1,2,3,66,4,5,11,22,33],
请写出删除列表中元素的方法,并说明每个方法的作用
"""
li2=[1,2,3,4,5]
li2.insert(0,0)
li2.insert(4,66)
li2.extend([11,22,33])
li2.append("name")
print(li2)
li2.remove(4)#删除列表内 值为 4的 值
li2.pop(2) #删除 索引为2的值
del li2[ 7]
print(li2)
|
932e862abd927e076036e61b4aaeaf90bbb968db | greenDNA/FoodsCooked | /modules/programstatus.py | 881 | 3.6875 | 4 | #Objective of class is to manage a while loop and have functions defined later be able to modify whether or not the loop should continue or end immediately
class ProgramStatus():
#constructor function. Set member variable running to True
def __init__(self):
self.running = True
self.account_mode ... |
911ee8e51731d18bcf1f8e2e66a933cfa23d414f | Akvanvig/Python-Oving | /IINI4014 Python for programmers/Øving 8 (eksamen)/assignment-8.py | 1,298 | 3.8125 | 4 | """
Title: assignment-8.py
Date: 13.11.2017
Author: Anders Kvanvig
"""
filePath = 'c:\\folder-1\\textfile.txt' #Filepath for the textfile you want to read
#Checkes if a word is added into list of dictionaries, and increments if it is
def addWord(word, wordsFound):
changed = False
for key in wordsFound.keys... |
0296e1ab83a0e9683a5db9666bd6e8ce39230967 | Akvanvig/Python-Oving | /IINI4014 Python for programmers/Øving 3/assignment-3.py | 1,790 | 4.28125 | 4 | """
Title: assignment-3.py
Date: 12.09.2017
Author: Anders Kvanvig
"""
import turtle
window = turtle.Screen()
asgeir = turtle.Turtle() #creates a turtle named 'asgeir'
#Settings
rad = -300 #Sets the radius to negative 100 so that the circle is drawn clockwise
points = 200 #Sets the number of points o... |
ff75d389d63b5f295823192fac612a912774ed27 | joaogomes95/Blue | /Módulo 1/15-06-for/tuplas.py | 2,216 | 4.28125 | 4 | # Tuplas (), Listas []
# A diferença entre eles
# sorted = ordenar em ordem alfabética e alfanuméricamente
# Em lista a função em .append() adiociona valor no final da lista
# o .insert altera um valor por outro
# .pop() apaga o ultimo valor
# .remove() apaga o valor selecionado
# Exercícios Tuplas:
# 01 - Crie um pr... |
63cc78bc7b380c452a358d13f0e6a0a4c0dd27c2 | AMK9978/ProgrammingProblems | /Kattis/Heritage-What Does It Mean/Main8.py | 661 | 3.734375 | 4 | _memo = {}
BIGPRIME = 1000000007
def count_meanings(d, word):
if word in _memo:
return _memo[word]
meaning = d[word] if word in d else 0
for i in range(1, len(word)):
f = word[:i]
l = word[i:]
if f in d:
meaning += d[f] * count_meanings(d, l)
_m... |
d36000b3b3e2980b28dcfc963abb2d8b52f0065a | DevChu/Python-Practice | /Lec02_vendingmachine.py | 577 | 3.859375 | 4 | print ("""What do you want to buy?
1. Soda 20
2. Rice ball 35
3. Pizza 300
4. Beef steak 350""")
good = int(input("I want to buy.. "))
print ("How much money do you give me?")
money = int(input(""))
if good ==1:
good = 20
elif good ==2:
good = 35
elif good ==3:
good = 300
elif good ==4:
good = 350
remain = money - ... |
3528996bc682bb0d24830264ef8865e42779e321 | jeremander/nerdcal | /nerdcal/positivist.py | 2,734 | 3.828125 | 4 | """Positivist Calendar
Devised by the philosopher Auguste Comte in 1849.
See: https://en.wikipedia.org/wiki/Positivist_calendar"""
from typing import List
from nerdcal._base import days_before_year, is_leap_year
from nerdcal.ifc import DAYS_IN_MONTH, DAYS_IN_WEEK, MIN_MONTH, MAX_MONTH, IFCDate, IFCDatetime
class ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.