blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7f15f9b93bc59bc557e18577b3f3a7d8de631708 | diegorafaelvieira/Programacao-1 | /Aula 06/QuantosNúmerosÍmpares.py | 176 | 3.71875 | 4 | contador = 0
while True:
if contador%7==0 and contador%2!=0:
print(contador)
if contador==100:
break
contador = contador+1
print(contador)
|
535462cebd52c86580bfa0dcbb7f7375c1fc3840 | diegorafaelvieira/Programacao-1 | /Aula 12/Calculadora.py | 448 | 3.953125 | 4 | def soma(a,b):
print(a+b)
def subtracao(a,b):
print(a-b)
def multiplicacao(a,b):
print(a*b)
def divisao(a,b):
print(a/b)
v1 = int(input("Valor 1:"))
v2 = int(input("Valor 2:"))
operacao = input("Informe soma, div, mult, sub:")
if operacao=="soma":
soma(v1,v2)
elif oper... |
c21c38a3dc2aa92fd60ad5974650e9dd462ace7a | diegorafaelvieira/Programacao-1 | /Aula 02/Códigos Professor/PizzariaADS.py | 329 | 3.90625 | 4 | quantidade = int(input("Informe a quantidade de pizzas consumidas:"))
valorPizzas = quantidade*10.00
imposto = valorPizzas*0.08
valorTotal = valorPizzas+imposto
print("O cliente comprou ",quantidade," pizzas.")
print("Preço das pizzas R$",valorPizzas)
print("Preço do imposto R$",imposto)
print("Preço total R$",valorTot... |
86fcbc0252fab24370a2b6e428a7b7f7b1271d50 | diegorafaelvieira/Programacao-1 | /Aula 12/Exercicio1a.py | 97 | 3.515625 | 4 | def maior (a,b):
if a > b:
print (a)
else:
print (b)
maior (10,-1)
|
34a197608f97a83dc1f54ec9f409cc9b8e332b00 | diegorafaelvieira/Programacao-1 | /Aula 03/MaiorIgualMenorQue3.py | 234 | 4.28125 | 4 | n = int(input("Informe um número:"))
if n > 3: #única verificação obrigatória
print ("O valor é maior a 3!")
elif n == 3:
print("O valor é igual a 3!")
else:
print("O valor é menor que 3!")
|
4ae55a7fe79cf67314ea3afecb1e2ca71cfd8874 | diegorafaelvieira/Programacao-1 | /Aula 12/Exercícios/Exerc5.py | 424 | 4.0625 | 4 | def tipoTriangulo(ld1,ld2,ld3):
if ld1==ld2 and ld1==ld3:
print("O triângulo é equilátero")
elif ld1==ld2 or ld2==ld3 or ld1== ld3:
print("O triângulo é isósceles")
else:
print("O triângulo é escaleno")
l1 = float(input("Informe o valor do 1° lado:"))
l2 = float(input("Informe o va... |
b0297d51da669526f68aa215cca3735d4497c553 | Meow-S/shiyanlou-code | /jump7.py | 119 | 3.53125 | 4 | a = 1
for _ in range(100):
if a % 7 == 0:
a = a + 1
elif '7' in str(a):
a = a + 1
else:
print(a)
a = a + 1
|
a33c36ec9a81afdfa1b9411044d72a126c5b02e6 | songguang-2010/k8s_installer | /scripts/common/lib/file.py | 2,458 | 3.703125 | 4 | #!/usr/bin/env python
# coding:utf-8
# -*- coding: UTF-8 -*-
# 该脚本提供了有关文件操作的一些工具函数
import os.path
class File(object):
def __init__(self):
pass
def __del__(self):
pass
@staticmethod
def read_line_first(filename):
# 从文件中读取第一行的内容, 无论是空行还是到达文件末尾还是文件不存在, 都返回False
# 如果文件不... |
748d23d08786854df7bf0229d2779d051ddbb819 | mapadebe/learning_python | /60001_F2016_ps1.py | 4,368 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 16:01:19 2020
@author: Martin
"""
#I commented out the user prompt crap because it is very annoying.
"Part A: House Hunting"
#annual_salary=120000#float(input("What is your annual salary (in $)?:"))
#portion_saved=0.10#float(input("What percentge of your salary would ... |
3adb358ae1d02f9de9a79a64938b840d27dd67d4 | tonylixu/devops | /algorithm/meeting-rooms/solution2.py | 386 | 3.5 | 4 | def can_attend_meetings(intervals):
length = len(intervals)
if length == 0 or length == 1:
return True
intervals.sort(key=lambda list:list[0])
for i in range(1,length):
if intervals[i][0] < intervals[i-1][1]:
print False
print True
if __name__ == '__main__':
interval... |
320b5d4a2bd40976323ad6d178a731ee8a637c10 | tonylixu/devops | /system/input-output/file/write-file-batch.py | 444 | 3.53125 | 4 | '''
How to write data into file as batches
'''
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started one day
In a relative way
And returned on the previous night.
'''
offset = 0
size = len(poem)
print size
chunk = 50
with open('poem.txt', 'xt') as f:
while True:
... |
d44af8a2e8befb3c9c500b305c6fc5f600197998 | tonylixu/devops | /algorithm/sorting/merge-sort.py | 1,201 | 4.28125 | 4 | # Mergesort is a divideand conquer algorithm
# which means we break the problem into sub-problems and
# find solution to sub-problems, and from the solution to
# sub-problems we construct a solution of the actual problem.
#
# Mergesort is a stable algorithm, it preserves the relative order
# of records with same key.
... |
4b74adef05a5d741461a859dccc33b2dbe36fae5 | otaviosouza/python3-quick-course-cod3r-cursos | /conditional/if_2.py | 233 | 3.8125 | 4 | # uncomment to see different results
# a = 'some text'
# a = 1
# a = 0
# a = -1
# a = 0.000001
# a = ''
# a = ' '
a = True
# a = False
if a:
print(f'Value exists: {a}.')
else:
print('Does not exist, False, zero or empty.')
|
56c7a495afba81f2491dae4ab369b4079e8e97a8 | MauxMaribel/Sebby | /shoot.py | 19,325 | 3.75 | 4 | import pygame
from random import randint
#Make a fireworks function and put at start screen and win screen
#Ask about error with pygame.quit() and how to quit game more naturally
#Create Player Healthbar
#Add Sounds
#Add Boss at stage 9
#Add explosion/shake when player is hit with bullet
#Add Powerups & Transporter sh... |
b9a594944a37e167516b2d62e4fe436b3bd8ad50 | Bhuvana11/py | /program2.py | 112 | 3.96875 | 4 | num2 =int(input())
flag = num2%2
if flag ==0:
print("Even")
elif flag ==1:
print("Odd")
else:
print(invalid)
|
5f6cb2d28f4e153c093df73730676d9c024660c5 | Tarthir/DNSPlotter | /graphmodel/Plotter.py | 5,312 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
from numpy import array
#########################
# This class is where data you pass in data in order to be made into graphs
#########################
class Plotter(object):
# Ths metho... |
8009cdd0ac22d97115341ed67458ff44c1ff969e | EmanuelFontelles/nn_numpy | /examples/xor.py | 611 | 3.640625 | 4 | """
The canonical example of a function that can't be
learned with a simple linear model in XOR
"""
import numpy as np
from nn_numpy.train import train
from nn_numpy.nn import NeuralNet
from nn_numpy.layers import Linear, Tanh
inputs = np.array([
[0,0],
[1,0],
[0,1],
[1,1]
])
targets = np.array([
... |
22d6e666391f39ad39bc19ee98843d5bef3c0da5 | Ishaan1342/Python_For_Everybody | /c3w5.py | 2,391 | 3.59375 | 4 | # # <!-- <receipe name = "bread" prep_time = "5 mins" cook_time = "3 hours">
# # <title>Basic bread</title>
# # <ingredient amount="8" unit="DL">Flour</ingredient>
# # <ingredient amount = "10" unit ="grams">Yeast</ingredient>
# # <instructions>
# # <step>Mix all ingredients together.</step>
# # <step>K... |
6fc22ada94bbe5b9277a3632cfe498fd3c01305b | lemy12/python_shorts | /odd_or_even.py | 305 | 4 | 4 | number = input("Enter number: ")
eoo = int(number)%4
if int(number)==0:
print (number + " is a zero.")
elif eoo==0:
print (number + " is an even number and a multiple of 4.")
elif eoo==2:
print (number + " is an even number.")
elif eoo==1 or eoo==3:
print (number + " is an odd number.")
|
d6f57385a6043910dba31770f6852a4c9e5f4304 | lemy12/python_shorts | /tictactoe1.py | 462 | 3.6875 | 4 | def create_x_h(x):
for i in range(0, x):
print (" ---", end="")
print ("")
def create_x_v(x):
for i in range(0, x):
print ("| ", end="")
print ("|")
def create_y(x,y):
for j in range(0, y):
create_x_h(x)
create_x_v(x)
if __name__ == "__main__":
input_x = int(... |
e22ac6c94be8e0bd04508ca9acfbe1a211eeba0d | lemy12/python_shorts | /rock_paper_scissors.py | 858 | 4.03125 | 4 | while True:
player_one = input("Player one choice: ")
player_two = input("Player one choice: ")
if player_one=="rock":
if player_two=="paper":
print ("Player two wins!")
elif player_two=="scissors":
print ("Player one wins!")
else:
print ... |
73a24c82616008c3b334d29334f9628b0c78132b | sanghyeop-na/Stock_python_study | /4. Stochastic_Oscillator 구현.py | 1,004 | 3.5 | 4 | # Stochastic(스토캐스틱)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from datetime import datetime
import pandas_datareader.data as wb
start = datetime(2018,1,1)
end = datetime(2018,12,30)
stock_data = wb.DataReader('005930.KS', 'yahoo',start,end)
stock_data['Close'].p... |
7cdba76eaae3a3b2229111a503f320775efa5e3c | danielrousseaug/CSE8A | /PA1/pa1.py | 556 | 4.0625 | 4 | def main():
weight_in_oz_str = input("Enter weight in oz: \n")
weight_in_oz = float(weight_in_oz_str)
weight_in_g = ounces_to_grams(weight_in_oz)
print("Weight in grams = ",weight_in_g)
print("Weight converted back to ounces = ", grams_to_ounces(weight_in_g))
def ounces_to_grams(weight_in_oz):... |
3bffeca18b67d001127e0ddfb92150ae0c39ea7e | guoyf5/actual_09_homework | /01/jcui/zuoye.py | 323 | 3.84375 | 4 | # -*- coding: UTF-8 -*-
sum = 0
num = 0
n = 0
while num != '' :
num = raw_input("please input num:")
if num.isdigit():
sum = sum + int(num)
n = n + 1.0
print sum / n
#九九乘法表
# for x in range(1,10):
# print
# for y in range(1,x+1):
# print '%d x %d = %2d' % (x,y,x*y) , |
96ca7ab65595984fa39ba9591cf939ebc57d8f26 | WaliedA/Python2018Course | /lecture 2/practice5.py | 383 | 4.0625 | 4 | '''
from Celsius to Fahrenheit
F = C * (9 / 5) + 32
from Fahrenheit to Celsius
C = (F - 32) * (5 / 9)
'''
# take C as an iput
C = raw_input("Celsius :")
C = int(C)
# print(C)
# from Celsius to Fahrenheit
F = C * (9.0/5.0) + 32
print("Fahrenheit: "+str(F))
# from Fahrenheit to Celsius
F = raw_input("Fahrenheit: ")
F =... |
73af789936161e35d22dc7823102318b2c1f2681 | nimishn2021/Day3 | /ex4.py | 765 | 4.28125 | 4 | # Using List comprehension flatten a List. Your Function will take 2 Lists namely ListA and List B.
# You need to pick elements from ListA which are divisible by any element in ListB.
# Note ListB must contain atleast 2 elements else dont process.
# Return the final list.
# Function to check if how many numbers a... |
2ce9963e2251254b62a9bdfa590fdd3875fba3b9 | hectorrdz98/prolog | /Primes/primesv3.py | 416 | 4.15625 | 4 | import math
def isPrime(n):
if n == 2: return True
if n % 2 == 0: return False
upper_lim = int(math.sqrt(n)) + 1
# check odd numbers from 3 to sqrt(n)
return len([i for i in range(3, upper_lim, 2) if n % i == 0]) == 0
n1 = int(input())
n2 = int(input())
total = 0
for i in range(n1, n2+1):
if... |
353e8085fb6333ff8d4fd3a762a0d63ea2e92283 | awilliams1991/training-modules | /dogweight.py | 330 | 3.6875 | 4 | def bark(name, weight):
if weight > 20:
print(name, 'says WOOF WOOF')
elif weight <= 20 and weight >= 2:
print(name, 'says woof woof')
elif weight < 2:
print(name, 'says yip yip')
bark('Codie', 40)
bark('Sparky', 9)
bark('Jackson', 12)
bark('Fido', 65)
bark('Scottie', -1)
bark('Spe... |
d12850aeecf5347163b4b3a0ca1d3a26be6695d6 | jbriales/toy-code | /python/function_arguments/main.py | 963 | 3.609375 | 4 | #!/usr/bin/env python3
# coding=utf-8
"""
Check syntactic sugar for different Python function calls
"""
import subprocess
import os
def foo(bar, quz, opt1='a def opt1 value', opt2='a def opt2 value'):
print(bar)
print(quz)
print(opt1)
print(opt2)
# Use function above with unpacked arguments
print('... |
41e5103fcf76c42fac4fc15da89472a50eed4199 | Cunillet/lab-code-simplicity-efficiency | /your-code/challenge-1.py | 1,418 | 3.9375 | 4 | import operator
class Calculate:
def __init__(self):
self.numbers = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
self.operations = {'plus': operator.add, 'minus': operator.sub}
self.val1 = ''
self.val2 = ''
self.op = ''
sel... |
0f4cf4b0b320027321d50954c2fa25c6ced373ae | charlottey820/calculator-project | /calc.py | 741 | 4.125 | 4 | initial = float(input("What is your initial investment?"))
rate = float(input("What is your interest rate?"))
time = float(input("How many years will you have this account?"))
def interest(money,rate,years):
ans = money*((100+rate)/100)**years
print(ans)
print(round(ans,3))
# if str(round(ans,0))[-1] !=... |
efbf1b3447152020253d23b2fcc0e541ee7c9fed | markmisener/udacity-deep-learning-ndf | /linear_regression/BMILifeExpectancyModel.py | 574 | 3.75 | 4 | import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# read data
bmi_life_data = pd.read_csv('bmi_and_life_expectancy.csv')
x_values = bmi_life_data[['Life expectancy']]
y_values = bmi_life_data[['BMI']]
# train model on data
bmi_life_model = LinearRegression()
bmi_li... |
332e2381c3f9e45b3a8a5381267732c84f35abae | sabdi21/bracket-matcher | /solution.py | 1,035 | 3.71875 | 4 |
def bracket_matcher(input):
open_list = ["[","{","("]
close_list = ["]","}",")"]
stack= []
for i in input:
if i in open_list:
stack.append(i)
elif i in close_list:
pos = close_list.index(i)
if ((len(stack) > 0) and (open_list[pos] == stack[len(stack)-1])):
... |
2c25145768e22c3b90fe16018c43126a6fce4dc3 | BlueFRJ/PythagorasTree | /PythagorasTree.py | 1,121 | 3.546875 | 4 | import turtle
import math
import random
def fractal(aturt, depth, maxdepth):
if depth > maxdepth:
return
length = 180*((math.sqrt(2)/2)**depth)
anotherturt = aturt.clone()
aturt.forward(length)
aturt.left(45)
fractal(aturt, depth+1, maxdepth)
anotherturt.right(90)
anotherturt.forward(len... |
bee1d5bbdc25dda50fd59291d7b190cb5607edf8 | Abhi135721/sample | /Stack.py | 484 | 4.1875 | 4 | Stack = []
top = -1
def push():
print "Enter an element to insert into stack:"
Stack.append(int(raw_input()))
def pop():
Stack.pop()
def display():
print Stack
while(True):
print "1.Insert an element into stack"
print "2.Pop operation"
print "3.Display Stack"
i = raw_input()
if i == "1":
push();
elif i == "... |
d36044e0105bf290bdc15ffc7f74d3f09a841629 | shalinibhandari/lets_upgrade-assingments | /list_to_dictonary.py | 153 | 3.703125 | 4 | list1=[1,2,3,4,5]
list2=["a","b","c","d","e"]
dict1={}
for i in range(0,len(list1)):
dict1[list1[i]]=(list2[i])
print(dict1,type(dict1))
|
ca3ed983e19b05af2ea66a135f56f81feb5a69c4 | criscross12/M-todos-N-mericos-Python | /App_Web/ejmplo.py | 325 | 3.734375 | 4 | import decimal
def EvaluarFuncion(funcion,x):
return eval(funcion)
h = decimal.Decimal(0.000001)
f= input('INgresa una funcion para derivar: ')
x = decimal.Decimal(input('Ingresa un valor para evaluar la funcion: '))
derivada = ((EvaluarFuncion(f,(x+h))) - (EvaluarFuncion(f,(x))))/h
print(deri... |
cfbf0ac61b4440ba085ecd1c4fc0e88f834c93c3 | akravets/python | /copyFiles.py | 1,715 | 3.5625 | 4 | """
Using Google Takeout to download photos from Google Photos we get album names as directories with file in them. Sometimes it's needed
explode all files in those directories into one directory, for example so that they can be used for import to another systems.
This script helps with this task.
"""
import os
import... |
5396f3818c834a0550b213c663bdf05ed9e5faeb | rlowrance/re-avm | /Timer.py | 2,577 | 3.859375 | 4 | import atexit
import os
import pdb
import time
class Timer(object):
def __init__(self):
# time.clock() returns:
# unix ==> processor time in seconds as float (cpu time)
# windows ==> wall-clock seconds since first call to this function
# NOTE: time.clock() is deprecated in pytho... |
236f676e6808e183c9261f11b70e07466560aa83 | johnnynieves/Kids_Math_Game | /menu.py | 1,936 | 4.0625 | 4 | from operation import add, multi_add, subtraction
import os
def level():
questions = int(input('How many questions to quiz? '))
levels = int(input('Enter max digits for equation? '))
return [questions,levels]
def console():
go = ('*' + ' ' * 28 + ' READY SET GO!!!! ' + ' ' * 28 + '*')
print... |
8f797e662166023a1f2ce28b7a70afe0458a8d1a | emrehaskilic/pyt4585 | /OOP/Lesson 2/2__init__.py | 1,012 | 4.125 | 4 | # __init__ constructor sınıfı bir örnek alığınızda yapılmas gereken konfigürasyon vs var ise __init__ içerisinde tanımlayabilirsiniz
class Personel:
Adi = ""
Soyadi = ""
Telefon= ""
Mail = ""
CreatedDate = ""
def __str__(self):
return f"{self.Adi}{self.Soyadi}\n Oluşturma Tarihi: {se... |
709cff85b778c1b105a3c5bb0528ea5bdc36229e | emrehaskilic/pyt4585 | /introduction/Lesson 3/kararYapilari2.py | 595 | 3.671875 | 4 | # Kullanici disardan not degeerini girecek ve girilen not 0 dan kucukse 0 dan kucuk not giremezsiniz uyarisi. 100 den büyükse 100 den buyuk not giremezsiniz uyarisi, girilen not 0a veya 100 e
# esit ve kucukse kullanıcıya girdigi notu gosteriniz.
try:
ders_not = int(input("Lutfen notu giriniz: "))
if(ders_no... |
de25c3dd091da044004b0d6b34dc13578665d4f3 | emrehaskilic/pyt4585 | /OOP/Lesson 1/3_Class.py | 766 | 4.09375 | 4 | class Student:
"""
self: Sınıf içerisinde yer alan metodların diğerlerinden farkı hangi sınıf içerisinde çalıştığını belirtmesidir.
Self anahtar kelimesini vererek metodun bu sınıf içeriinde çalıştığını belirtmiş oluruz.
Tanımlama yapılırken eklenir fakat kullanım sırasında python bunu bizim için kendi... |
f5da2a91352279a90907e301c5e312002ec0ed49 | emrehaskilic/pyt4585 | /introduction/odev1.py/func.py | 229 | 4 | 4 | # kullanıcı dışardan sayisal olarak bir dizi gönderecek siz bunu sayisal diziye çeviren bir metod yazınız
# "3 4 5 6 7 8 9 10 a b c d e" = [3,4,5,6,7,8,9,10]
a = str(input("sayi gir:"))
for i in a:
print(list(i))
|
d30b4a8178fbeb3c414f297b00d84fa1a70e2e46 | emrehaskilic/pyt4585 | /introduction/Lesson7/Void3.py | 253 | 3.828125 | 4 | # 1000 dahil 1 ile 1000 arasındaki sayiları ekrana yazdıran metod yazıdnız
def Say():
for i in range(1000,0,-1):
print(i)
Say()
# ya da
def Saydirici():
i = 1000
while (i>=1):
print(i)
i -= 1
Saydirici() |
9ade26abfe0beec6357dd6c6f9a7169cd90bc4d0 | emrehaskilic/pyt4585 | /OOP/Lesson 3/1_AccessModify.py | 1,553 | 4.15625 | 4 | class Cup1:
def __init__(self):
self.color = None # public variable
self.content = None # public variable
def fill(self,beverage):
self.content = beverage
def empyt(self):
self.content = None
def __str__(self):
return self.color + " " + self.content
cup1 = Cup1(... |
9373369d4202e9883d53ba71ea6f9ccbd9039d61 | jmarcos9/udemy | /cricao_arquivos/manipular_arquivos.py | 1,482 | 3.671875 | 4 | import os
import json
'''file = open('abcde.txt', 'w+')#w+ ler e escrever
file.write('Linha1\n')
file.write('Linha2\n')
file.write('Linha3\n')
file.seek(0, 0)#manipula o cursor do aquivo
print(file.read())
file.seek(0, 0)
print('#'*10)
print(file.readline(), end='')
print(file.readline(), end='')
print(file.readline(... |
48d422635c65fb7890a7aec85aab25bd03f3606a | jmarcos9/udemy | /intermediario/levantando_execoes.py | 653 | 3.859375 | 4 | '''def divide(n1, n2):
try:
return n1 / n2
except ZeroDivisionError as error:
print('log',error)#log do tratamento pode ser salvo em aruivo de log erro
raise#relançar a cxcerção para outro try
#esse try não vai funcionar mais... tem que incluir o raise no primeiro tratamento para este s... |
6c6f157c1bd6023b6d3812e7f39d82d04188a5df | hthuwal/ta-iitd | /fall-2017/gen-test-factors-and-prime-factors.py | 1,068 | 3.53125 | 4 | from random import randint
NUM_CASES = 50
MAX_NUMBER = 10000
RANGE_OF_NUMBERS = (2, MAX_NUMBER)
TEST_CASE_FORMAT = """
case = Test %d
input = %s
output = %s
"""
isPrime = [i for i in range(0, MAX_NUMBER)]
def sieve():
isPrime[1] = 0
for i in range(2, MAX_NUMBER):
if isPrime[i]:
for j in... |
84f9a63d94c8cc8874189203715da578db0f1260 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.037.py | 652 | 4.28125 | 4 | # 37. Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de
# conversão:
# - 1 para binário
# - 2 para octal
# - 3 para hexadecimal
num = int(input('Digite um número inteiro: '))
print('''Escolha uma das bases para conversão:
[1] Binário
[2] Octal
[3] Hexa... |
af1c72a1e33851217feb97bf56411d6db4409e7a | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.052.py | 515 | 3.953125 | 4 | # 52. 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: '))
nd = 0
for c in range(1, n + 1):
if n % c == 0:
print('\033[33m', end='')
nd += 1
else:
print('\033[31m', end='')
print('{}'.format(c), end... |
26b9b2cd69aefbd14ff7f3bbb05dc366e8573b6d | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.018.py | 497 | 4.0625 | 4 | # 18. Faça um programa que leia um ângulo qualquer e mostre na tela o valpor do seno, cosseno e tangente desse ângulo:
from math import sin, cos, tan, radians
a = int(input('Digite o valor de um ângulo qualquer: '))
print('O seno de \033[94m{}\033[m é \033[93m{:.2f}\033[m.'.format(a, sin(radians(a))))
print('O co... |
126ad8e95be1abb10fb27fe7754e5f3e38316016 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.023.py | 432 | 3.90625 | 4 | # 23. Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados:
num = int(input('Digite um número de 0 até 9999: '))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print('Unidade: \033[96m{}\033[m.'.format(u))
print('Dezena: \033[93m{}\033[m.... |
ffb653c1910026e73ccec44c100367d7bb1d1db3 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.056.py | 930 | 3.796875 | 4 | # 56. 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
# > Quantas mulheres têm menos de 20 anos
somaIdade = 0
medIdade = 0
maIdH = 0
nomeVelho = ''
totMul = 0
for p in range(1, 5):
print(... |
96ac4366f8b492db1c39466150cc24fb494dd032 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.055.py | 491 | 3.828125 | 4 | # 55. Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos
maior = 0
menor = 0
for p in range(1, 6):
pes = float(input('Peso da pessoa {}: '.format(p)))
if p == 1:
maior = pes
menor = pes
else:
if pes > maior:
... |
4f11e6cea0992b60598cd5044176b3fea341eeb8 | NathanRomero2005/Exercicios-Resolvidos-de-Python | /ex.053.py | 364 | 3.90625 | 4 | # 53. Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços
f = str(input('Digite uma frase: ')).strip().upper()
p = f.split()
j = ''.join(p)
i = ''
for l in range(len(j) -1, -1, -1):
i += j[l]
print(j, i)
if i == j:
print('É um palíndromo!!')
else:
... |
4ee02b009c43fafbd9be46aaa71cdef55ac73588 | tri2820/FuzzyCruiseControl | /environment.py | 4,307 | 4.28125 | 4 | #!/usr/bin/python39
from math import cos,pi
import numpy as np
import matplotlib.pyplot as plt
from random import random
from dataclasses import dataclass
"""
Simulate an adaptive cruising system over a bumpy road
controller(v) -> action (hit gas/brake) -> change car state -> new v -> controller(v) -> ...
Basic usag... |
038ee1863fb8b247412038b20dcdb4b332a45568 | simeiyu/python | /basic_knowledge/5.1-if.py | 660 | 4.09375 | 4 | '''
第5章 if语句
'''
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# 在Python中检查是否相等时区分大小写
print('Audi' != 'audi')
# 检查多个条件
age = 24
print(age >= 20 and age <= 40)
print(age >= 30 and age <= 40)
print(age >= 30 or age <= 40)... |
9d54ac5016eb766614d3616643064bd9cb42222e | simeiyu/python | /basic_knowledge/3.3-list.py | 751 | 4.46875 | 4 | '''
3.3 组织列表
3.3.1 使用方法sort()对列表进行永久性排序
'''
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# 按与字母顺序相反的顺序排序
cars.sort(reverse=True)
print(cars)
'''
3.3.2 使用方法sorted()对列表进行临时性排序
也可以向sorted()传递参数reverse=True
'''
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list: ")
print(ca... |
2ffe12ecc224dc3f545d32c67730736ed92245ad | simeiyu/python | /basic_knowledge/8.3-def.py | 2,175 | 3.9375 | 4 | '''
8.3 返回值
----------
函数返回的值被称为返回值。
在函数中,可使用return语句将值返回到调用函数的代码行。
返回值能够让你将程序的大部分繁重工作移到函数中去完成,从而简化主程序。
'''
# 简单返回值
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
# 让实参变成可选的 使用默认... |
85a83915543acef19c306d96f3556ad85d64c37b | Nikiforos2000/Programming1 | /Les 2/Strings.py | 372 | 3.578125 | 4 | print(len('supercalifragilisticexpialidocious'))
s = 'supercalifragilisticexpialidocious'
i = 'ice'
print(i in s)
a ='Antidisestablishmentarianism'
h = 'Honorificabilitudinitatibus'
print (a>h)
print(min('Berlioz', 'Borodin', 'Brian', 'Bartok', 'Bellini', 'Buxtehude', 'Bernstein'))
print(max('Berlioz', 'Borodin', 'Bria... |
46e439af9dd9d8717907622f4e9cf05c561fc9af | Nikiforos2000/Programming1 | /Les 3/Tuples.py | 186 | 3.578125 | 4 | letters = ('A', 'C', 'B', 'B', 'C', 'A', 'C', 'C', 'B')
#letters.sort()
#a = letters.count('A')
#b=
#print([a,b,c])
print([letters.count('A'), letters.count('B'), letters.count('C')])
|
f5663fcf6614998470527f924d09651a1246b496 | Nikiforos2000/Programming1 | /Les 8/8.5.py | 143 | 4.03125 | 4 | list=[1,2,3,4,5,6,7,8,9,10]
for number in list:
for number1 in list:
print("{} + {} = {}".format(number, number1, number*number1)) |
8659eee32fab75019b76dd99737ee35b822d77e3 | akumaraswamy/Python-projects | /Data Wrangler/word_cloud_trump.py | 779 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 01 21:57:36 2017
@author: aruna
"""
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
d = os.getcwd()
filepath="trumpSpeech.txt"
# Read the whole text.
def wordCloud(path):
text = open(path).read() #read the entire file in one go
... |
89cb9a0784ecfed0180a16733f129e36b4ec496f | akumaraswamy/Python-projects | /Spark Assignment/assignment2_spark_ak.py | 740 | 3.875 | 4 | """"
Using pyspark create a word count application of all the words of the file assignment_2_datafile.txt
Avoid counting trivial words such as vowels and pronouns.
@author Aruna Kumaraswamy
"""
from pyspark import SparkConf, SparkContext
print 'Assignment 2 - Spark Word Count Application'
conf = SparkConf().setMaster... |
84415d35244d2a910db4b1cd01ebc56f85da9613 | Currycurrycurry/interview_internal_reference | /06.头条篇/meituan4.py | 2,013 | 3.515625 | 4 | node_num, edge_num, start_node = list(map(int, input().split()))
graph = []
for i in range(node_num):
graph.append(list(map(int, input().split())))
expected_path = int(input())
dict_graph = {} # dict graph
for line_index in range(len(graph)):
for j in range(node_num):
if graph[line_index][0] == j + 1:
... |
9a55158c9e586510d600be01b5fea849d2bf015f | Currycurrycurry/interview_internal_reference | /06.头条篇/lru.py | 778 | 3.65625 | 4 | from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self:
return -1
else:
self.move_to_end(key)
return self[key]
... |
7dfad79892398feeb6b90ac9b800269c462e9b97 | tylerthecoder/CheckersAI | /src/drawing.py | 3,638 | 3.53125 | 4 | import pygame
import math
pygame.init()
pygame.display.set_caption("Checkers")
class Window():
#Define some colors
black = (30, 30, 30)
darkBlack = (0,0,0)
yellow = (255, 255, 0)
green = (0, 255, 20)
red = (255, 0, 0)
darkRed = (200,10,10)
white = (255,255,255)
brown1 = (139,69,19)... |
c3f27b08eea43c2c2f40b73c596a63cb24cec8de | borsemayur2/PyCalc | /PRIMER.PY | 524 | 3.96875 | 4 | from numberValidator import numberValidator
def primer(y):
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
else: # Normal exit
print(y, 'is prime')
... |
3079e4d459cc83714cd7d29e6350cdc98476efee | Alexxxtentancion/CMatrix | /py_matrix.py | 818 | 3.796875 | 4 | import myMatrix
def matrixmult(m1,m2):
s=0 #сумма
t=[] #временная матрица
m3=[] # конечная матрица
if len(m2)!=len(m1[0]):
print ("Матрицы не могут быть перемножены")
else:
r1=len(m1)
c1=len(m1[0])
r2=c1
c2=len(m2[0])
for z in range(0,r1):
... |
b4db118fb5471f2497cf17e62869e762d4941e1c | Talha-Ahmed-1/DSA-Labs | /Talha Ahmed(18B-024-SE) Lab # 04.py | 1,587 | 3.96875 | 4 | import random
class Sorting:
def __init__(self):
self.data=[]
def Print(self):
print(self.data)
def GenerateRandom(self,n):
for i in range(n):
x=random.randint(1,n)
self.data.append(x)
def BubbleSort(self):
n=len(self.data)
for i in range(1... |
3eb7cd401a75e10d38be88d6519848a09263a8d8 | Talha-Ahmed-1/DSA-Labs | /Practice/linklist.py | 1,908 | 4.0625 | 4 | class Node:
def __init__(self,value):
self.value=value
self.next=None
class LinkedList:
def __init__(self):
self.head=None
self.tail=None
def insertAtFirst(self,value):
newnode=Node(value)
if self.head == None:
self.head=newnode
self.ta... |
177dccdc9e622db0e6f210ee5be8d2cf5ba4eb92 | jnguyen326/Intro_To_Python | /Labs/6.2.2: Basic function call./minutestohours.py | 130 | 3.546875 | 4 | def output_minutes_as_hours(orig_minutes):
print(orig_minutes/60)
minutes = float(input())
output_minutes_as_hours(minutes)
|
58469cb2d319ac7e42be5c23f1590c04b9f4094d | domantasjurkus/python | /euler/02_euler.py | 975 | 3.921875 | 4 | last = 1 #last fibonacci term
fib = 2 #current fibonacci term
temp = 0 #temporary placeholder
finalSum = 2 #2 is even-valued, we have to add it manually here
while fib <= 4000000: ... |
9db1e22becc463cac9a5d9c7949ad2e1361e925b | domantasjurkus/python | /jp morgan dojo 2014/petrol.py | 1,852 | 3.828125 | 4 | def GasStation(strArr):
# how many stations do we have?
station_num = int(strArr[0])
# check wheter argument is valid
if len(strArr)-1 != station_num:
print "invalid argument"
return -1
# make a simplified array contaning the fuel values
array = []
for element in strArr... |
610161ddc2e5e36d5711a040ba466f24d71d4b6c | domantasjurkus/python | /hacker.org/xor/didactic_xor.py | 1,096 | 3.796875 | 4 | from xor import *
chal1 = "3d2e212b20226f3c2a2a2b"
chal2 = "948881859781c4979186898d90c4c68c85878f85808b8b808881c6c4828b96c4908c8d97c4878c858888818a8381"
chal3 = "31cf55aa0c91fb6fcb33f34793fe00c72ebc4c88fd57dc6ba71e71b759d83588"
# Challenge 2
for i in range(1, 256):
print i, xor_hex(chal2, i, 8)
# Challenge 3
... |
2f92e78a579b633a59dc4712033cc2f09fcbb914 | domantasjurkus/python | /euler/03_euler.py | 616 | 3.828125 | 4 | num = 600851475143 #number we're checking
i = 1 #variable for iteration
prime = 2
def isPrime(num):
j = 2
while j < num:
if num%j==0:
return False
j = j+1
return True
#let's find all the factors of num
while i <= ... |
383e3c05b912f792e7a6bc1232b4d4e108484119 | think-blue/kalman-filters | /knowledge.py | 507 | 3.765625 | 4 |
"""
This represents the map or the knowledge that the robot has about the environment. B1,B2, B3,... etc represents the beacon position info.
"""
from enum import Enum
class Beacon(Enum):
B1 = (0,0);
B2 = (0,100);
B3 = (100,0);
B4 = (100,100);
#More beacons
B5 = (40,60);#
#B6 = (70,80);
... |
eed5c15784e0f976f519b30734969286755dbca3 | DiogoTakayama/CodigosPython | /Questao3.py | 140 | 3.765625 | 4 |
a = int (input("a:"))
b = int (input("b:"))
c = int(a)/int (b)
d = a%b
e = float(a)/float(b)
print (int(c))
print (d)
print (e)
|
bff717490461bd0aa7e3c777d5483207ddbac13c | DiogoTakayama/CodigosPython | /Questao5.py | 105 | 3.859375 | 4 | N1 = int (input("Nota 1:"))
N2 = int(input("Nota 2:"))
print ("Media Ponderada: ", (N1*2+N2*3)/5)
|
9e81cf9beba55dc5d3494c99d51ca5f9fee21941 | DiogoTakayama/CodigosPython | /Macas.py | 187 | 3.640625 | 4 | QtdMacas = int (input ("N Macas"))
if QtdMacas <=11:
print (QtdMacas*1.30)
else:QtdMacas >11 and QtdMacas <50
print (QtdMacas*1)
if QtdMacas > 50:
print (QtdMacas*0.9)
|
20763d74536b84bbf05b089eb3522d65105dfb00 | tophep/SnapHack-Framework | /autosnapper/example.py | 1,065 | 3.53125 | 4 | from snapchat import Snapchat
import getpass
from pprint import pprint
# Enter your snapchat credentials (they will be used securely)
USERNAME = #Your Snapchat username
PASSWORD = #Your Snapchat password
TARGET = #Some other Snapchat username
SAVE_TO = "downloaded_snap"
UPLOAD_FROM = #some local file
s = Snapchat(U... |
b8d2ad3389d50d42117a6e177f7df804b065fddf | prajwal-shenoy42/The-Snake-Game | /snake.py | 5,163 | 3.953125 | 4 | #Snake.py
import pygame
import random
import time
pygame.init() #Initializes the modules present in pygame
def main_snake(snake_size, snake_list):
for a in snake_list:
pygame.draw.rect(dis, snake_color, [a[0], a[1], snake_size, snake_size])
def message(msg,color):
m = font_style.render(msg, True, c... |
5ca5f6e6524a3d5a1e415970a0a07e2cf0cc9a65 | uosoul/soul | /力扣题目/141环形链表.py | 786 | 3.796875 | 4 | class Solution:
def hasCycle(self, head: ListNode) -> bool:
a = set()
while head:
if head in a:
return True
a.add(head)
head = head.next
return False
def hasCycle(self,head):
try:
slow = head
... |
d111a8e0a0fe4e5d0b0d2ae6923512d53666dbc9 | uosoul/soul | /力扣题目/146LRU缓存机制.py | 2,373 | 3.5625 | 4 | class LRUCache:
def __init__(self, capacity: int):
self.dic= {}
self.lst = []
self.k = capacity
def get(self, key: int) -> int:
if key in self.dic:
self.lst.remove(key)
self.lst.append(key)
return self.dic[key]
else:
retu... |
573ebdbbea159789d6b13e84bed7991d64de3de9 | uosoul/soul | /力扣题目/98验证二叉搜索树.py | 640 | 3.578125 | 4 | # 一个办法就是中序遍历,是从小到大的数组
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
def isValidBST(root):
self.res = [ ]
self.inorder(root)
for i in range(len(self.res)-1): # 判断一下是不是有序的数组,而且不能相等。
if self.res[i] >= self.... |
200088595cd3e3cff93c47e321bf4c7b816c506b | uosoul/soul | /力扣题目/283移动零.py | 850 | 3.640625 | 4 | def moveZero(nums):
zero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i],nums[zero] = nums[zero],nums[i]
zero +=1
print(nums)
nums=[0,2,0,5,0,4,0,1,0,5,0]
moveZero(nums)
#第二次
def f2(nums):
for i in range(len(num... |
8d4e455506ab2868353957603de7346d67ddc4e8 | uosoul/soul | /力扣题目/递归模板.py | 326 | 3.65625 | 4 | # 泛型的递归模板,
def recursion(level,param1,param2,...):
# recursion terminator
if level > max_level:
process_result
return
# process logic in current level
process(level,data..)
# drill down
self.recursion(level+1,p1,...)
# reverse the current level status if needed
|
872600b243d5228596c1a5f98a387072afb1cd17 | ujtakk/sampling | /hoge.py | 387 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
def main():
# 処理前の時刻(t0)を取得
t0 = time.clock()
# 計測したい処理
time.sleep(3)
# 処理後の時刻(t1)を取得
t1 = time.clock()
# 処理後の時刻(t1)-処理前の時刻(t0)で処理時間を計算
print("dt="+str(t1-t0)+"[s]")
if __name__ == '__main__':
main()
|
0701c3deb87930ae2e9d73d5d21e06dc106d52d9 | restlesspuppet/PracticePython | /11-CheckPrimalityFunctions.py | 620 | 4.09375 | 4 | #############################
# Check Primality Functions
# By RestlessPuppet
# 11/23/19
#############################
def get_num(txt):
return input(txt)
num = get_num("Please enter a number: ")
while num != "":
print("\n")
i = 2
l = []
while i < int(num):
if int(num) % i ==0:
... |
b655ec527420438d4fe18c7b75266c3c629580e3 | restlesspuppet/PracticePython | /01-CharacterInput2.0.py | 615 | 3.8125 | 4 | # CharacterInput
# RestlessPuppet
# 11-9-2019
import datetime
while True:
name = input("What name do you go by? ")
c = input("Is " + name +" correct? (y/n) ")
if c == "y":
break
age = input("How old are you? ")
age = int(age)
b = input("Have you had your birthday yet this ccalander year? (y/n) ")
... |
607ae1c429196b9db90acb6b555114e5478eeff0 | kuroroblog/atcoder221 | /B.py | 701 | 3.546875 | 4 | # 標準入力を受け付ける。
S = input()
T = input()
# Sを操作することなく、S = Tになる場合は、即座にYesを出力する。
if S == T:
print('Yes')
exit()
S = list(S)
for i in range(len(S) - 1):
# S[0]とS[1]を入れ替え、S[1]とS[2]を入れ替え、S[2]とS[3]を入れ替え、、、の場合を検証する。
tmp = S[i + 1]
S[i + 1] = S[i]
S[i] = tmp
# 入れ替えた場合にS = Tになるか検証する。
if ''.join(S... |
fef8c5d6e23cb827b44bb8ac15df6118a7908a5f | VONO1/lesson4 | /main.py | 784 | 3.796875 | 4 | from random import randint
spisok = ['Паша','Маша', 'Галя','Инна','Марина',"Никита",'Петя','Витя','Миша','Лера','Таня','Аня','Соня','Полина']
#функция создания списка
def FFF (sp, num):
newsp= []
for i in range(num):
rn=randint(0, len(sp)-1)
newsp.append(sp[rn])
return newsp
#создаём спи... |
d7327c5400b860773389d59b616cb8803277fe05 | ad-1/SortingVisualisation | /solver.py | 4,567 | 3.890625 | 4 | # Sorting Algorithms Solver Class
class Solver:
def __init__(self, unsorted, n, solve_mode, subscriber):
self.subscriber = subscriber
if solve_mode == 0:
self.selection_sort(unsorted, n)
elif solve_mode == 1:
self.insertion_sort(unsorted, n)
elif solve_mode... |
fd55161590a4e1cbf408aafc270f30c7f9cd0b01 | JuanGuillermoTinoco/Programaci-n-Python | /indice.py | 470 | 3.890625 | 4 | #Trabajo 1. Ejercicio 6.
#Juan Guillermo Urincho Tinoco.
n=input('Introduce tu estatura en m: ')
m=input('Introduce tu peso en kg: ')
imc=m/(n*n)
print "IMC=",imc
if imc<16:
print ("Delgadez severa.")
elif 16<imc<16.99:
print ("Delgadez moderada")
elif 17<imc<18.49:
print ("Delgadez leve")
eli... |
f59b8c4cb4f3434714bd17b9517abc810213472e | gregorysimpson13/machine_learning | /house_prediction/read_descriptions.py | 617 | 3.53125 | 4 | from typing import List, Dict
from collections import defaultdict
FILENAME = 'data_description.txt'
def read_file(filename: str=FILENAME) -> List[str]:
with open(filename) as f:
content = f.readlines()
return [x.strip() for x in content]
def parse_file(contents: List[str]) -> Dict[str, List[str]]:
... |
210f7884719d80449bb4e078ae70c435bfe40d70 | hwynn/gridprint | /printBreakList.py | 88 | 3.5 | 4 | myList = ["x"]*23;
for i in range(23):
if(i%10 == 0):
print("");
print(i, end=" "); |
c6193d151181b23436146867c3ad41651cf166d9 | sresis/practice-2021 | /sortStack/sortStack.py | 313 | 3.953125 | 4 | def sortStack(stack):
if len(stack) == 0:
return stack
first = stack.pop()
sortStack(stack)
insertInSorted(stack, first)
return stack
def insertInSorted(stack, val):
if stack == [] or stack[-1] <= val:
stack.append(val)
return
first = stack.pop()
insertInSorted(stack, val)
stack.append(first)
|
e82b0a42b56e79b2f56cd82df32b8b03a43f32e6 | sresis/practice-2021 | /reverse-words/reverse-words.py | 434 | 3.796875 | 4 | def reverseWordsInString(string):
# loop through char until reach a space
output = []
curr = ''
for char in string:
if char != ' ':
curr += char
else:
output.append(curr)
output.append(' ')
curr = ''
output.append(curr)
# now need to reverse in place
start = 0
end = len(output) -1
while start <... |
694f0b79cbf9c7b7e53c500035b8a6e76e5319e4 | parkerbxyz/exercism | /python/leap/leap.py | 155 | 4.1875 | 4 | def is_leap_year(year: int) -> bool:
"""Return True if a given year is a leap year."""
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.