blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
81bc1a9286b8d13acf0ee2d1c1a03e45b32e1c01 | polowis/ping-_pong_game | /ball3.py | 2,019 | 3.875 | 4 | '''
v3.0.0
@author Polowis
this code works better than the other two, but still results in run time error: maximum recursion depth exceeded because we're using
tail recrusion in the code due to the fact that python prevents inifinte recursions to avoid stack overflow. ( which is good)
V3.0.0 improves the caculation for the ball direction by adding some maths.
There are a few ways to fix this problem:
use setrecursionlimit() to increase the value of recursion limit but this is dangerous because
it will change the memory allocation space for stack which is responsible for storing values of programming counter during recursion process
or we can do it manually to bounce the ball which is not recommended.
Because the ball need to bounce infinitely, I cannot figure out any other ways to perform this without using recursion.
I will try to find errors in my algorithm and see if I can stop the program before it reaches its limit
P/S This piece of code work perfecly in processing programming language. However, some adjustments have been made so it
can work with microbit.
'''
from microbit import *
import math
import random
class Ball:
def __init__(self, x=2, y=2, xspeed = 1, yspeed = 1):
self.x = x
self.y = y
self.xspeed = xspeed
self.yspeed = yspeed
self.reset()
def reset(self):
self.x = 2
self.y = 2
angle = int(random.uniform(- math.pi / 4, math.pi / 4))
self.xspeed = 2 * math.cos(angle)
self.yspeed = 2 * math.sin(angle)
if random.random() < 0.5:
self.xspeed *= -1
def show(self):
display.set_pixel(int(self.x), int(self.y), 9)
sleep(100)
display.set_pixel(int(self.x), int(self.y), 0)
def update(self):
self.x += self.xspeed
self.y += self.yspeed
def edges(self):
if self.y < 0:
self.yspeed *= -1
if self.y > 4:
self.yspeed *= 1
if self.x > 4 or self.x < 0:
self.reset()
|
23edf34203bc79e97dc242b7533b39d0c0422614 | Mauro-mc/Python-pr-cticas | /clase 5.py | 1,038 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 18:30:14 2021
@author: Usuario
"""
def uno(a,b):
return (a*b)
print (uno(5,2))
w=uno(5,2)
suma=w+5
print(suma)
#practica 5 funciones
def multiply(a,b):
return(a*b)
print(multiply(5,4))
x=multiply(5, 4)
nuevax=x*100
print(nuevax)
def resta(a,b):
return(a-b)
print(resta(10,8))
y=resta(10,8)
nuevay=y*100
print(nuevay)
def suma(a,b):
return(a+b)
print(suma(5,12))
z=suma(5,12)
nuevaz=z*100
print(nuevaz)
def division(a,b):
return(a/b)
print(division(40,8))
u=division(40,8)
nuevau=u*100
print(nuevau)
def exponencial(a,b):
return(a**b)
print(exponencial(5,9))
o=exponencial(5,9)
nuevao=o*100
print(nuevao)
#def en LISTA
def saludos(lista):
for i in lista:
print("Hola", i)
saludos(["Juan"])
saludos(["luis"",carlos"])
#ejercicio
def crealista(n):
lista=[]
for i in range(n):
lista.append(i)
return lista
print(crealista(5))
resultado=crealista(20)
|
3735f2e08803537b4f8c1ba5fa4ad92e6109e16b | Jacalin/Algorithms | /Python/hash_pyramid.py | 661 | 4.5 | 4 | '''
Implement a program that prints out a double half-pyramid of a specified height, per the below.
The num must be between 1 - 23.
Height: 4
# #
## ##
### ###
#### ####
'''
def hash_pyramid():
# request user input, must be num bewtween 1 - 23
n = int(input("please type in a number between 1 - 23: "))
# check if num is in bounds
if n > 23 or n < 1:
n = int(input("please type in a number between 1 - 23: "))
# if num in bounds, loop through usernum(n), and print properly formated pyramid.
else:
for i in range(1,n+1):
print (((" " * ((n - (i-1)) - 1)) + ("#" * i) ) , " " , ("#" * i) )
|
e1d3d3db61840fb42b01f1679531ac26139d005b | julesjacobs/julesjacobs.github.io | /notes/quantum/qsim.py | 1,175 | 3.625 | 4 | from math import sqrt
n = 5 # number of bits in our state
# we represent bit strings as integers
def print_state(s):
print(" + ".join([f'{s[i]:.5f}|{bin(i)[2:].zfill(n)}>'
for i in range(len(s)) if s[i] != 0]))
# gives the basis state |x>, where x is a string of 0's and 1's
def basis(x):
s = [0]*2**n
s[int(x,base=2)] = 1
return s
# apply the classical gate C_f, where f is a bijective function on bit strings
def classical(s,f):
s2 = [0]*2**n
for x in range(2**n):
s2[f(x)] = s[x]
return s2
# apply the Hadamard gate H_k, where k is the bit to apply the gate to
def hadamard(s,k):
bitk = 1 << k
s2 = [0]*2**n
for x in range(2**n):
sign = (-1)**((x >> k) & 1)
s2[x] = (s[x & ~bitk] + sign*s[x | bitk])/sqrt(2)
return s2
# example
s = basis("10101")
print_state(s) # 1.00000|10101>
s = hadamard(s,1)
print_state(s) # 0.70711|10101> + 0.70711|10111>
s = classical(s, lambda x: ~x)
print_state(s) # 0.70711|01000> + 0.70711|01010>
s = hadamard(s,3)
print_state(s) # 0.50000|00000> + 0.50000|00010> + -0.50000|01000> + -0.50000|01010>
s = hadamard(s,1)
print_state(s) # 0.70711|00000> + -0.70711|01000> |
78cadd51457c5ad5c8078d715da8b086c2674368 | rickvig/senai-tds | /paradgmas/atividade_oo.py | 1,711 | 3.84375 | 4 | print('Atividade OO')
class Mamifero():
mamilos = True
olhos = True
nome = ''
cor = ''
def __init__(self, nome_parametro, cor_parametro):
self.nome = nome_parametro
self.cor = cor_parametro
def mama(self):
print('%s está mamando e é %s...' % (self.nome, self.cor))
class Aquatico(Mamifero):
barbatana = True
def nada(self):
print("%s esta nadando" % self.nome)
class Baleia(Aquatico):
espiraculo = True
def solta_leite_na_agua(self):
print("%s esta soltando leite na água" % self.nome)
class Terrestre(Mamifero):
pernas = True
pes = True
def caminha(self):
print("%s esta caminhando" % self.nome)
class Pessoa(Terrestre):
conciencia = True
def fala(self):
print('%s está falando' % self.nome)
class Cachorro(Terrestre):
pelo = True
rabo = True
def late(self):
print('Au AU')
def main():
print('Olá estamos no main')
cachorra_henrique = Cachorro('Laila', 'cinza')
print('qual é o nome da cachorra do henrique:', cachorra_henrique.nome)
print('a laila tem mamilos:', cachorra_henrique.mamilos)
print('a laila tem olhos:', cachorra_henrique.olhos)
print(cachorra_henrique.late())
print('Acidente da laila')
cachorra_henrique.mamilos = False
cachorra_henrique.olhos = False
print('a laila tem mamilos e olhos depois do acidente:', cachorra_henrique.mamilos, cachorra_henrique.olhos)
print(cachorra_henrique.mama())
cachorro_diego = Cachorro("Yuki", 'branco')
print(cachorro_diego.mama())
cachorro_atalaia = Cachorro("Fofinho", 'branco')
print(cachorro_atalaia.mama())
main() |
b11c49d7b500cfb73199c71755cbe9919714351f | rickvig/senai-tds | /paradgmas/paradgma-estruturado.py | 986 | 3.90625 | 4 | print('Aula de Paradgma estruturado')
# váriavel numérica
idade = 30
print(idade)
# váriavel de texto
nome = 'Henrique'
print(nome)
# váriavel boolean
status = True
print(status)
lista_idades = []
print(lista_idades)
lista_idades.append(idade)
lista_idades.append(45)
lista_idades.append(55)
print(lista_idades)
print(lista_idades[1])
print("##################")
for elemento in lista_idades:
print(elemento)
def verifica_idade(idade_a_verificar):
print("função verifica_idade:", idade_a_verificar)
if idade_a_verificar > 55:
mensagem = 'Vá ao médico porque sua idade é: %d' % idade_a_verificar
print(mensagem)
else :
mensagem = 'Voce não precisa ir ao médico pq sua idade é: %d' % idade_a_verificar
print(mensagem)
verifica_idade(67)
# declaração da função
def soma_idade(idade1, idade2):
return idade1 + idade2
# invocação da função
soma_das_idades = soma_idade(15, 55)
print(soma_das_idades) |
31fc3087cab6005638007c911291d6c23ae293ee | kyledavv/lpthw | /ex24.py | 1,725 | 4.125 | 4 | print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("--------")
print(poem)
print("--------")
five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 1000
beans, jars, crates = secret_formula(start_point)
#remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
#it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
start_point = start_point / 10
print("We can also do that this way:")
formula = secret_formula(start_point)
#this is an easy way to apply a list to a format string
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
print("Now to practice with my work schedule and payment per week.")
chad = 65 * 3
jacinda = 65
raina = 65 * 2
jrs = 25 * 12
syd = 65
payment = chad + jacinda + raina + jrs + syd
print("\tThis is the gross amount that I earn from my private lessons and juniors.")
print("===>", payment)
print("This is the payment after the percentage is taken out.")
actual_pmt = payment * .65
print("\t====>", actual_pmt)
lost_pmt = payment - actual_pmt
print(f"This is the amount I lost from the percentage taken out: {lost_pmt}")
print("Country Club's really get you with what they take out. \n:-(")
|
b117af5971a3aebe95eea39f4d90141bfd7a9dd5 | kyledavv/lpthw | /ex17.py | 1,031 | 3.703125 | 4 | #imports argv function
from sys import argv
from os.path import exists
#imports exist function, returns true if does exist
script, from_file, to_file = argv
#prints Copying from 1st argument to 2nd argument
print(f"Copying from {from_file} to {to_file}")
# could do on one line
#opens from_file and makes it in_file
in_file = open(from_file)
indata = in_file.read()
#reads in_file and makes it indata
print(f"The input file is {len(indata)} bytes long")
#prints length of indata
print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
#line 16 runs exist command to see if to_file exists. comes back true.
#line 17 prints hit Return to continue, or ctrl c to abort.
#line 18 gives user input command to hit return or ctrl c
out_file = open(to_file, 'w')
out_file.write(indata)
#opens to_file to write, makes it out_file
#out_file writes indata
print("Arlight, all done.")
#prints alright, all done
out_file.close()
in_file.close()
#closed out_file
#closes in_file
|
c952b31d5c726ae2a12cec3570a4e6efdf7a2184 | Linuzs/Pythonwork | /2020-09-01.py | 2,658 | 3.640625 | 4 | ip = '192.168.1.3'
list = ip.split('.')
print(list)
str = 'bad luck'
new_str = str.replace('bad','good')
print(new_str)
str1 = 'bad bad luck'
list_str = str1.split()
list_str[1] = 'good'
print(" ".join(list_str))
import random
strlist = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'
code = ""
for i in range(4):
num = random.randint(0,len(strlist))
code += strlist[num]
print(code)
username = input("Please input your name:")
password = input("Please input your password:")
hide_password = len(password)
if username == "":
username = "Player1"
if password == "":
print("Please input your password!!!")
exit()
print("########################################")
print("#Welcome to the invincible Heroes game!#")
print("#Your username is %s!"%(username))
print("#Your password is %s!"%(hide_password * "*"))
print("########################################")
https://www.cloudflare.com/
username = input("Please input your name:")
password = input("Please input your password:")
repeat_password = input("Please input your repeat password:")
error_password = 0
while error_password < 3:
if username.strip() == "":
username = "Player1"
elif password.strip() != "" and repeat_password.strip() != "" and repeat_password.strip() == password.strip():
print("register success")
f = open("info.txt", 'a+')
f.write(username + ' ' + password + '\n')
f.close()
print("Please login")
username = input("username:")
password = input("password:")
f2 = open("info.txt",'r')
res = f2.read()
#res.close()
user_list = res.split()
user_dict = {}
for i in user_list:
username = i.split(',')[0]
password = i.split(',')[1]
user_dict[username] = password
print(user_dict)
break
else:
print("error pass")
break
'''
info = {}
info['username'] = username
info['password'] = password
print(info)
break
info = {}
info['username'] = username
info['password'] = password
print(info)
'''
'''
print("########################################")
print("#Welcome to the invincible Heroes game!#")
print("#Your username is %s!"%(username))
print("#Your password is %s!"%(len(password) * "*"))
print("########################################")
info = {}
info['username'] = username
info['password'] = password
print(info)
dict = {'username':'admin','password':'123456'}
username = 'admin'
if username in dict:
print("x")
else:
print("dui")
'''
|
6ba06d4a767c669227aaf6b7c5b7e7669b5bac4b | kiranreddy9183/new-project | /serchinhg a dictionary.py | 296 | 3.59375 | 4 | n=int(input("enter limit:"))
d={}
for i in range(0,n):
k=input("enter keys:")
v=int(input("enter values:"))
d[k]=v
v=d.values()
r=sorted(list(set(v)))[1]
r1=[]
for k,v in d.items():
while r==v:
r1.append(k)
break
#r1.sort()
for n in r1:
print(n)
|
0d711d02d064282983035023398a34501ee752f0 | akanksh123/Programs | /py7.py | 154 | 3.828125 | 4 | dicto={'john':85,'mark':90,'smith':100}
for i in sorted(dicto,reverse=True)[:2]:
print(i,dicto[i])
sum=0
for i in dicto:
sum+=dicto[i]
print(sum) |
8658126e3b2a1d4c63cd6550fc91ce31de7e2189 | mafrasiabi/rsa | /rsa/viz.py | 1,430 | 3.703125 | 4 | from scipy.spatial import distance
from matplotlib import pyplot as plt
import numpy as np
def plot_dsms(dsms, items=None, n_rows=1):
"""Plot one or more DSMs
Parameters
----------
dsms : ndarray | list of ndarray
The DSM or list of DSMs to plot. The DSMs can either be two-dimensional
(n_items x n_iterms) matrices or be in condensed form.
items : list of str | None
The each item (row/col) in the DSM, a string description. This will be
displayed along the axes. Defaults to None which means the items will
be numbered.
n_rows : int
Number of rows to use when plotting multiple DSMs at once. Defaults to
1.
Returns
-------
fig : matplotlib figure
The figure produced by matplotlib
"""
if not isinstance(dsms, list):
dsms = [dsms]
n_cols = int(np.ceil(len(dsms) / n_rows))
fig = plt.figure(figsize=(2 * n_rows, 2 * n_cols))
ax = fig.subplots(n_rows, n_cols, sharex=True, sharey=True, squeeze=False)
for row in range(n_rows):
for col in range(n_cols):
dsm = dsms[row * n_cols + col % n_cols]
if dsm.ndim == 1:
dsm = distance.squareform(dsm)
elif dsm.ndim > 2:
raise ValueError(f'Invalid shape {dsm.shape} for DSM')
im = ax[row, col].imshow(dsm, cmap='RdBu_r')
plt.colorbar(im, ax=ax)
return fig
|
aa673ad99e3adc6a02d9e49a1c7d6b9d82ad2d2d | rawswift/python-collections | /tuple/cli-basic-tuple.py | 467 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# create tuple
a = ("one", "two", "three")
# print 'em
print a
# how many node/element we have?
print len(a) # 3
# print using format
print "Counting %s, %s, %s..." % a
# iterate
for x in a:
print x
# print value from specific index
print a[1] # 'two'
# create another tuple (using previous tuple)
b = (a, "four")
print b[1] # 'four'
print b[0][2] # 'three'
# how many node/element we have?
print len(b) # 2
|
8e55c707612389eabdd24563aa537477b688cb16 | kjunsong/tensorflow_project | /tensorflow_learning/3_2MNIST数据集分类简单版本.py | 4,358 | 3.609375 | 4 | """
MNIST数据集:
MNIST数据集可在官网下载,这里用python源码自动下载和安装这个数据集
数据集分为60000行的训练集(mnist.train)和10000行的测试集(mnist.test)。数据集中图片是mnist.train.images,标签是mnist.train.labels。
每一张图片包含28*28像素,数组展成向量长度为784。展平图片丢失二维结构信息,但最优秀的计算机视觉方法会挖掘并利用这些结构信息。
Softmax回归:
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot = True) #第一个参数为路径,one_hot把标签转化为只由0和1表示
#每个批次的大小:训练时候放入一个批次
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size # //为整除,总的数量整除批次
"""实现回归模型"""
#定义两个placeholder(占位符),用2维的浮点张量来表示这些图,这个张量形状是[None,784]。(这里的None表示此张量的第一个维度可以是任何长度)
#在tensorflow运行计算时输入这个值,我们希望能够输入任意变量的MNIST图像,每一张图展平成784维的向量。
x = tf.placeholder(tf.float32,[None, 784]) #当传入参数的时候,None->100(批次大小)
y = tf.placeholder(tf.float32,[None, 10])
#一个Variable代表一个可修改的张量,在这里用全为零的张量来初始化w和b
W = tf.Variable(tf.zeros([784,10])) #w的维度是[784,10]因为我们想要用784维的图片向量乘以它,得到一个10维的证据值向量,每一对对应不同数字类。
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b) #返回的是概率,tf.matmul(x,W)表示x乘以W
"""训练模型"""
#需要定义一个指标来评估这个模型好坏,用一个指标称为成本(cost)或者损失(loss),在此使用二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#已经设置好了模型。运算之前,添加一个操作来初始化我们创建的变量
init = tf.global_variables_initializer()
"""评估我们的模型"""
# tf.equal 比较变量 标签一样返回true,不一样返回false,结果存放在一个bool型列表中
# tf.argmax 返回概率最大的那个值的位置,相当于数字标签
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
#求准确率 tf.reduce_mean求平均值 tf.cast将bool类型转化为tf.float32类型,true->1.0 false->0
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #例如:[True,False,True,True]会变成[1,0,1,1],取平均得到0.75
#在一个Session里启动我们的模型,并初始化变量
with tf.Session() as sess:
sess.run(init)
for epoch in range(21): #迭代21个周期
for batch in range(n_batch): #每个周期中批次数
batch_xs, batch_ys = mnist.train.next_batch(batch_size) #获得批次 batch_xs保存数据 batch_ys保存标签
sess.run(train_step, feed_dict = {x:batch_xs, y:batch_ys}) #进行一次训练
#求准确率
#mnist.test.images测试集图片 mnist.test.labels测试集标签
acc = sess.run(accuracy, feed_dict = {x:mnist.test.images, y:mnist.test.labels})
print("Iter" + str(epoch)+",Testing Accuracy" + str(acc))
#最终结果大约是91%,并不好,需要改进
"""
Extracting MNIST_data\train-images-idx3-ubyte.gz
Extracting MNIST_data\train-labels-idx1-ubyte.gz
Extracting MNIST_data\t10k-images-idx3-ubyte.gz
Extracting MNIST_data\t10k-labels-idx1-ubyte.gz
Iter0,Testing Accuracy0.8306
Iter1,Testing Accuracy0.8709
Iter2,Testing Accuracy0.8819
Iter3,Testing Accuracy0.8883
Iter4,Testing Accuracy0.8947
Iter5,Testing Accuracy0.8972
Iter6,Testing Accuracy0.9002
Iter7,Testing Accuracy0.9012
Iter8,Testing Accuracy0.904
Iter9,Testing Accuracy0.905
Iter10,Testing Accuracy0.9064
Iter11,Testing Accuracy0.9073
Iter12,Testing Accuracy0.9087
Iter13,Testing Accuracy0.9095
Iter14,Testing Accuracy0.9096
Iter15,Testing Accuracy0.911
Iter16,Testing Accuracy0.9113
Iter17,Testing Accuracy0.9122
Iter18,Testing Accuracy0.9138
Iter19,Testing Accuracy0.9136
Iter20,Testing Accuracy0.9135
"""
|
62394e0fa3de73dfbe1f514e95104aa2d6cc5ead | kjunsong/tensorflow_project | /tensorflow_learning/4_1交叉熵.py | 2,153 | 3.5625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNISTZ_data",one_hot = True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32,[None, 784])
y = tf.placeholder(tf.float32,[None,10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
#二次代价函数 loss = tf.reduce_mean(tf.square(y-prediction))
#使用交叉熵定义代价函数,加速模型收敛速度
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
for epoch in range(21):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size) #batch_xs保存数据 batch_ys保存标签
sess.run(train_step,feed_dict = {x:batch_xs, y:batch_ys}) #进行一次训练
acc = sess.run(accuracy, feed_dict = {x:mnist.test.images, y:mnist.test.labels})
print("Iter"+str(epoch)+",Testing Accuracy"+str(acc))
"""
Extracting MNISTZ_data\train-images-idx3-ubyte.gz
Extracting MNISTZ_data\train-labels-idx1-ubyte.gz
Extracting MNISTZ_data\t10k-images-idx3-ubyte.gz
Extracting MNISTZ_data\t10k-labels-idx1-ubyte.gz
Iter0,Testing Accuracy0.8255
Iter1,Testing Accuracy0.8816
Iter2,Testing Accuracy0.9006
Iter3,Testing Accuracy0.9048
Iter4,Testing Accuracy0.9085
Iter5,Testing Accuracy0.9107
Iter6,Testing Accuracy0.9119
Iter7,Testing Accuracy0.9126
Iter8,Testing Accuracy0.9143
Iter9,Testing Accuracy0.916
Iter10,Testing Accuracy0.9169
Iter11,Testing Accuracy0.918
Iter12,Testing Accuracy0.9194
Iter13,Testing Accuracy0.9197
Iter14,Testing Accuracy0.9196
Iter15,Testing Accuracy0.9192
Iter16,Testing Accuracy0.9206
Iter17,Testing Accuracy0.9209
Iter18,Testing Accuracy0.9209
Iter19,Testing Accuracy0.9213
Iter20,Testing Accuracy0.9217
"""
|
cad92d1813f7fef775e139082c7ca93ed18c7bc6 | Emassei/tutorial | /notes/data_structures.py | 273 | 3.890625 | 4 | # Tuples, these items cannot be changed
guy = ('a', 'b', 'c')
guy[1]
# outputs 'b'
# ------------
# Dictionaries, these are key value pairs
guy1 = {'a': 1, 'b': 2, 'c': 3}
guy1['a']
# outputs 1
# ---------------
# Lists
guy2 = ['a', 'b', 'c']
guy[1]
# outputs 'b'
|
b462ebac876184cadf7184b48f8db74dc80a95a4 | adam-mcdaniel/turing-15 | /testing.py | 197 | 3.6875 | 4 | condition = 1
# the variable condition is now 1
while condition < 10:
# while the variable condition is less than 10
print(condition)
condition += 1
# add one to condition
# back to line 5 |
c5d8e6e5d681ce56655ae84abd1018fbae43cd03 | rafaelbeirigo/mjlstd | /Parameters.py | 2,729 | 3.5625 | 4 | class Parameters:
"""Parameters for the MJLS TD(\lambda) algorithm."""
def __init__(self, L, T, K, lambda_, epsilon, c, eta, seed):
"""
Args:
L (:obj:`int`): max iterations for calculating Y.
T (:obj:`int`): max interations for calculating each Y candidate.
K (:obj:`int`): max iterations for calculating the sum used to
calculate each Y candidate.
lambda_ (:obj:`float`): coefficient for the sum used to
calculate each Y candidate.
epsilon (:obj:`float`): minimum difference between two numbers to
consider them equal when testing for convergence.
c (:obj:`float`): coefficient used to calculate the step size.
eta (:obj:`float`): exponent used to calculate the step size.
seed (:obj:`int`): value used to initialize the random number
generator.
"""
self.L = L
self.T = T
self.K = K
self.lambda_ = lambda_
self.epsilon = epsilon
self.c = c
self.eta = eta
self.seed = seed
def positive_or_error(self, value, name):
"""Raises an error if value is not positive."""
if value < 0:
raise ValueError(''.join((name, " must be positive.")))
@property
def L(self):
return self._L
@L.setter
def L(self, value):
self.positive_or_error(value, "`L'")
self._L = value
@property
def T(self):
return self._T
@T.setter
def T(self, value):
self.positive_or_error(value, "`T'")
self._T = value
@property
def K(self):
return self._K
@K.setter
def K(self, value):
self.positive_or_error(value, "`K'")
self._K = value
@property
def lambda_(self):
return self._lambda_
@lambda_.setter
def lambda_(self, value):
self.positive_or_error(value, "`lambda_'")
self._lambda_ = value
@property
def epsilon(self):
return self._epsilon
@epsilon.setter
def epsilon(self, value):
self.positive_or_error(value, "`epsilon'")
self._epsilon = value
@property
def c(self):
return self._c
@c.setter
def c(self, value):
self.positive_or_error(value, "`c'")
self._c = value
@property
def eta(self):
return self._eta
@eta.setter
def eta(self, value):
self.positive_or_error(value, "`eta'")
self._eta = value
@property
def seed(self):
return self._seed
@seed.setter
def seed(self, value):
self.positive_or_error(value, "`seed'")
self._seed = value
|
8829140909b516941d6ffc563cc083262210d3a0 | v200510/Python_basics_and_application | /3.3 task-3.py | 452 | 4.15625 | 4 | # 3.3 Регулярные выражения в Python
# Вам дана последовательность строк.
# Выведите строки, содержащие две буквы "z", между которыми ровно три символа.
# Sample Input:
# zabcz
# zzz
# zzxzz
# zz
# zxz
# zzxzxxz
# Sample Output:
# zabcz
# zzxzz
import re, sys
[print(line.rstrip()) for line in sys.stdin if re.search(r'z.{3}z', line)]
|
688fdc8e8babe2268dba8471c1dbde4697b17d63 | ayushxx7/hacker_rank | /counting_clouds.py | 993 | 3.890625 | 4 | #!/bin/python3
import os
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
index = 0
step = -1
size = len(c)
while index < size:
print(c[index])
if index + 2 < size and c[index] == 0: ## the logic is simple, you are going to jump either 1 step or 2 step, based on if 2 step jump is leading to a 0(safe) or 1.
index = index + 1
step += 1
index += 1
return step
# step_count = -1
# print(c)
# for index,step in enumerate(c):
# print(c[index])
# if index+2 < len(c):
# if c[index+2] == 0:
# index = index+1
# step_count += 1
# else:
# step_count += 1
# return step_count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
c = list(map(int, input().rstrip().split()))
result = jumpingOnClouds(c)
fptr.write(str(result) + '\n')
fptr.close()
|
3536d8d4537f8a4b215dd7186dec4bb59e33236d | ornwipa/ComIT_django | /lecture_examples/inheritance.py | 729 | 3.703125 | 4 | class Person:
def __init__(self, fname, lname, *args, **kwargs):
self.first_name = fname
self.last_name = lname
super().__init__(*args, **kwargs)
def print_name(self):
print(f"{self.first_name} {self.last_name}")
class Student(Person):
pass
class Employee(object):
def __init__(self, id, employer):
self.id = id
self.employer = employer
def print_employer(self):
print(f"Employer: {self.employer}")
class Teacher(Student, Employee):
def print_name(self):
super().print_name()
print(" is a teacher.")
teacher = Teacher(fname="Jack", lname="Black", id="007", employer="M16")
teacher.print_name()
teacher.print_employer()
|
5caf2defe75b91c024c097d908ce5ed20c0b02e5 | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao19.py | 428 | 4.25 | 4 | """
19) Faça um programa para verificar se um determinado número
inteiro é divisível por 3 ou 5, mas não simultaneamente pelos dois.
"""
numero = int(input("Digite um número: "))
if numero % 3 == 0 and not (numero % 5 == 0):
print("Divisível por 3.")
elif numero % 5 == 0 and not(numero % 3 == 0):
print("Divisível por 5.")
else:
print("Não divisível por 3 ou 5 / Não pode ser divisível pelos dois ") |
d798a6cdfe7e3f785f44ceee8e19daf6f57693c2 | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao2.py | 386 | 4.15625 | 4 | """
2) Leia um número fornecido pelo usuário. Se esse númerro for positivo,
calcule a raiz quadrada do número. Se o número for negativo, mostre
uma mensagem dizendo que o número é inválido.
"""
numero = int(input("Digite um número: "))
if numero > 0:
print(f"\n{numero ** 2}")
elif numero < 0:
print("\nNúmero inválido")
else:
print("\nNúmero igual a zero")
|
0d0a9b18fede86ea9b3afec3a588bc3920856e0e | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao11.py | 592 | 4.125 | 4 | """
11) Escreva um programa que leia um número inteiro maior do que zero
e devolva, na tela, a soma de todos os seus algarismos. Por exemplo, ao número
251 corresponderá o valor 8 (2 + 5 + 1). Se o número lido não dor maior do que
zero, programa terminará com a mensagem 'Número inválido'
"""
numero = int(input("Digite um número inteiro maior que zero: "))
print()
if numero > 0:
numero = str(numero)
soma = 0
for indice in range(len(numero)):
soma += int(numero[indice])
print(f"A soma de seus algorismos é {soma}")
else:
print('Número inválido') |
ddbad1dbb4c52686a837700662e562d5a10fe720 | RianMarlon/Python-Geek-University | /secao3_introducao/recebendo_dados.py | 973 | 4.15625 | 4 | """
Recebendo dados do usuário
input() -> Todo dado recebido via input é do tipo String
Em Python, string é tudo que estiver entrw:
- Aspas simples;
- Aspas duplas;
- Aspas simples triplas;
- Aspas duplas triplas;
Exemplos:
- Aspas Simples -> 'Angelina Jolie'
- Aspas duplas -> "Angelina Jolie"
- Aspas simples tripla -> '''Angelina Jolie
"""
# - Aspas duplas triplas -> """Angelina Jolie"""
# Entrada de dados
nome = input("Qual o seu nome?")
# Exemplo de print 'antigo' 2x
# print("Seja bem-vindo %s" %(nome))
# Exemplo de print 'moderno' 3x
# print("Seja bem-vindo {0}".format(nome))
# Exemplo de print 'mais atual' 3.7
print(f"Seja bem-vindo {nome}")
idade = int (input("Qual sua idade?"))
# Processamento
# Saida
# Exemplo de print 'antigo' 2x
# print("O %s tem %d anos" %(nome, idade))
# Exemplo de print 'moderno' 3x
# print("O {0} tem {1} anos".format(nome, idade))
# Exemplo de print 'mais atual' 3.7
print(f"O {nome} tem {idade} anos")
print(f"O {nome} nasceu {2019 - idade}")
|
5f3b816c0dad6a85f6f79ed2f49a928aff9dc750 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao23.py | 740 | 4.125 | 4 | """
23) Ler dois conjuntos de números reais, armazenando-os em vetores
e calcular o produto escalar entre eles. Os conjuntos têm 5 elementos
cada. Imprimir os dois conjuntos e o produto escalar, sendo que o produto
escalar é dado por: x1 * y1 + x2 * y2 + ... + xn * yn
"""
lista1 = []
lista2 = []
for i in range(5):
lista1.append(float(input("Digite um valor para o primeiro vetor: ")))
print()
for i in range(5):
lista2.append(float(input("Digite um valor para o segundo vetor: ")))
print(f"\nPrimeiro vetor: {lista1}")
print(f"Segundo vetor: {lista2}")
produto_escalar = 0
for i in range(5):
produto_escalar += (lista1[i] * (i+1)) * (lista2[i] * (i+1))
print(f"Produto escalar dos dois conjuntos: {produto_escalar}")
|
d3eeca6931077e52d8af4fc26eebfb7f03855630 | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao8.py | 638 | 4.09375 | 4 | """
8) Faça um programa que leia 2 notas de um aluno, verifique se as notas são válidas
e exiba na tela a média destas notas. Uma nota válida deve ser, obrigatoriamente,
um valor entre 0.0 e 10.0, onde caso a nota não possua um valor válido, este
fato deve ser informado ao usuário e o programa termina.
"""
nota1 = float(input("Digite a primeira nota do aluno: "))
nota2 = float(input("Digite s segunda nota do aluno: "))
print()
if (nota1 >= 0.00) and (nota1 <= 10) and (nota2 >= 0.0) and (nota2 <= 10):
media = (nota1 + nota2) / 2
print("Média: %.2f" % media)
else:
print("A nota não possue um valor válido")
|
31695a819b6604cebfe71d293413c3d0c0a2e8ec | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao9.py | 466 | 3.890625 | 4 | """
9) Leia o salário de um trabalhador e o valor da prestação
de um empréstimo. Se a prestação for maior que 20% do salário imprima:
'Empréstimo não concedido', caso contrário imprima: 'Empréstimo concedido'
"""
salario = float(input("Digite o salário do trabalhador: "))
prestacao = float(input("Digite o valor da prestação: "))
print()
if prestacao > salario * 0.2:
print("Empréstimo não concedido")
else:
print("Empréstimo concedido") |
6b688b370005968d080e17f61734a9c649e7b31f | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao23.py | 339 | 3.890625 | 4 | """
23) Leia um valro de comprimento em metros e apresente-o convertido em jardas.
a fórmula de conversão é: J = M/0.91, snedo J o comprimento em jardas e
M o comprimento em metros.
"""
metros = float(input("Digite o valor de comrpimento em metros: "))
jardas = metros / 0.91
print(f"\nO valor do comprimento em jardas é {jardas}")
|
0f67eccd7468b04fb0121435107147db731a894b | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/exercicio/questao18.py | 1,126 | 3.921875 | 4 | """
18) Faça um programa que leia um arquivo contendo o nome e o preço de diversos
produtos (separados por linha), e calcule o total da compra.
"""
nome_arquivo = str(input("Digite o caminho do arquivo ou seu nome "
"(caso o arquivo esteja no mesmo local do programa): "))
nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo+".txt"
try:
with open(nome_arquivo, "r", encoding="utf-8") as arquivo:
linhas = arquivo.read().lower().strip().splitlines()
valor_total = 0.0
for linha in range(len(linhas)):
if linha % 2 == 1:
preco = linhas[linha].replace(",", ".") if "," in linhas[linha] else linhas[linha]
preco = float(preco)
valor_total += abs(preco)
print("\nO valor total da compra: {:.2f}".format(valor_total))
except FileNotFoundError:
print("\nArquivo não encontrado!")
except OSError:
print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
except ValueError:
print("\nO modo que as informações se encontram no arquivo é inválido!")
|
a5ea00a5b2bb36240557f80633cf45fcbd83f9fa | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao7.py | 391 | 4.1875 | 4 | """
7) Escreva um programa que leia 10 números inteiros e os armazene em um vetor.
Imprima o vetor, o maior elemento e a posição que ele se encontra.
"""
lista = []
for i in range(10):
lista.append(int(input("Digite um número: ")))
print(f"\nVetor: {lista}")
print(f"Maior elemento: {max(lista)}")
print(f"Posição em que se encotra o maior elemento: {lista.index(max(lista))}")
|
1f5d94314af8c9c886db5887ccc6a78c9d2c77cd | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao29.py | 355 | 3.65625 | 4 | """
29) Leia quatro notas, calcule a média aritmética e imprima o resultado.
"""
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
nota3 = float(input("Digite a terceira nota: "))
nota4 = float(input("Digite a quarta nota: "))
media = (nota1 + nota2 + nota3 + nota4) / 4
print(f"\nA média é {media}")
|
3250b325719b209728daea7385250d249978a63c | RianMarlon/Python-Geek-University | /secao17_heranca_polimorfismo/exercicios1/questao9.py | 4,844 | 3.890625 | 4 | """
9) Escreva um código que apresente a classe Moto, com
atributos marca, modelo, cor e marcha e, o método imprimir. O método
imprimir deve mostrar na tela os valores de todos os atributos. O
atributos marcha indica em que a marcha a Moto se encontra no momento, sendo
representado de forma inteira, onde 0 - neutro, 1 - primeira, 2 - segunda, etc.
"""
from verificacao import verificar_nome
class Veiculo:
def __init__(self, marca, modelo, cor):
"""Construtor que recebe a marca, modelo e cor do veiculo, verificando
se os mesmos são válidos ou não"""
try:
if type(marca) == str and type(modelo) == str and type(cor) == str:
self.__marca = marca.strip().title()
self.__modelo = modelo.strip().title()
if verificar_nome(cor):
self.__cor = cor.strip().title()
else:
print("\nCor inválida")
else:
raise ValueError
except ValueError:
print("\nValores inválidos")
exit(1)
@property
def marca(self):
"""Retorna o valor contido no atributo de instância 'marca'"""
return self.__marca
@property
def modelo(self):
"""Retorna o valor contido no atributo de instância 'modelo'"""
return self.__modelo
@property
def cor(self):
"""Retorna o valor contido no atributo de instância 'cor'"""
return self.__cor
@marca.setter
def marca(self, nova_marca):
"""Recebe um valor que irá ser o novo valor do atributo de instância 'marca'"""
try:
if type(nova_marca) == str:
if self.__marca.strip() == "":
self.__marca = nova_marca.strip().title()
else:
print("\nMarca já definida")
else:
raise ValueError
except ValueError:
print("\nMarca inválida")
@modelo.setter
def modelo(self, novo_modelo):
"""Recebe um valor que irá ser o novo valor do atributo de instância 'modelo'"""
try:
if type(novo_modelo) == str:
if self.__modelo.strip() == "":
self.__modelo = novo_modelo.strip().title()
else:
print("\nModelo já definido")
else:
raise ValueError
except ValueError:
print("\nModelo inválido")
@cor.setter
def cor(self, nova_cor):
"""Recebe um valor que irá ser o novo valor do atributo de instância 'cor'"""
try:
if type(nova_cor) == str and verificar_nome(nova_cor):
if self.__cor.strip() == "":
self.__cor = nova_cor.strip().title()
else:
print("\nCor já definida")
else:
raise ValueError
except ValueError:
print("\nCor inválida")
def imprimir(self):
"""Método Abstrato"""
raise NotImplementedError
class Moto(Veiculo):
def __init__(self, marca, modelo, cor, marcha):
"""Construtor que recebe a marca, o modelo, a cor e a marcha da moto,
chama a Classe Pai e verifica se os valores recebidos são válidos ou não"""
super().__init__(marca, modelo, cor)
try:
if type(marcha) != bool:
if int(marcha) >= 0:
self.__marcha = int(marcha)
else:
raise ValueError
else:
raise ValueError
except ValueError:
print("\nValor inválido")
exit(1)
@property
def marcha(self):
"""Retorna o valor contido no atributo de instância 'marcha'"""
return self.__marcha
@marcha.setter
def marcha(self, nova_marcha):
"""Recebe um valor que irá ser o novo valor do atributo de instância 'marcha'"""
try:
if type(nova_marcha) != bool:
if int(nova_marcha) >= 0:
self.__marcha = int(nova_marcha)
else:
raise ValueError
else:
raise ValueError
except ValueError:
print("\nValor inválido")
def imprimir(self):
"""Imprimi todos os valores de todos os atributos"""
print(f"\nMarca: {self.marca}")
print(f"Modelo: {self.modelo}")
print(f"Cor: {self.cor}")
print(f"Marcha atual: {self.marcha}")
if __name__ == "__main__":
moto1 = Moto("Yamaha", "Xj6", "Branco", 6)
moto1.imprimir()
moto2 = Moto("Kawasaki", "Ninja H2 Carbon", "Prata", 8)
moto2.imprimir()
moto3 = Moto("Kawasaki", "Ninja H2R", "Prata", 8)
moto3.imprimir()
|
87a50a44cff3abac564d6b98587beb4d73654016 | RianMarlon/Python-Geek-University | /secao8_funcoes/exercicios/questao28.py | 1,405 | 4.46875 | 4 | """
28) Faça uma função que receba como parâmetro o valor de um ângulo em grau
e calcule o valor do cosseno desse ângulo usando sua respectiva série de Taylor:
cos x = E(n=0) = (-1) ^ n / (2 * n)! * (x ^ 2 * n) = 1 - (x^2 / 2!) + (x^4 / 4!) - ...
para todo x, onde x é o valor do ângulo em radianos. Considerar pi = 3.141593 e n variando
de 0 até 5.
"""
from math import factorial
def cosseno(angulo):
"""
Função que recebe o valor de um ângulo em graus, trasnforma o ângulo de graus para
radianos e calcula o valor do seno do ângulo em radianos usando a série de Taylor.
Retorna uma mensagem informando o resultado do calculo
:param angulo: Recebe o valor do ângulo em graus
:return: Retorna uma mensagem informando o valor do ângulo em radianos e o resultado do cálculo.
Se o ângulo for negativo, retorna uma mensagem informando que o ângulo é inválido
"""
if angulo > 0:
pi = 3.141593
x = angulo * pi / 180
cos = 0
for n in range(6):
numerador = x ** (2 * n)
denominador = factorial(2 * n)
cos += (-1) ** n / denominador * numerador
return f"{angulo}° em radianos: {x}" \
f"\nCosseno de {x}: {cos}"
return "Valor inválido"
angulo_em_graus = int(input("Digite o valor do ângulo em graus: "))
print(f"\n{cosseno(angulo_em_graus)}")
|
33f5a78f58f95f83dd7a55d5fcaa340a43378933 | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao25.py | 362 | 3.84375 | 4 | """
25) Leia um valor de área em acres e apresente-o convertido
em metros quadrados m². A fórmula da conversão é: M = A*4048.58,
sendo M a área em metros quadrados e A a área em acres
"""
acres = float(input("Digite o valor da área em acres: "))
metros_quadrados = acres*4048.58
print(f"O valor da área em metros quadrados m² é {metros_quadrados}") |
ff7a3f2d4d418c8131e04c1b2b08348e5ee22552 | RianMarlon/Python-Geek-University | /secao17_heranca_polimorfismo/exercicios1/questao25.py | 2,206 | 3.859375 | 4 | """
25) Baseando-se no exercício 24 adicione os métodos volumeAcima
e volumeAbaixo, sendo que o método volumeAcima deve modificar
o volume para o próximo nível de volume possível, onde ao chegar
ao volumeMaximo não poderá possibilitar que o volume seja alterado.
O método volumeAbaixo deve modificar o volume para o nível imediatamente
inferior de volume me relação ao volume atual, não podendo ser menor do
que 0, simulando desta forma o funcionamento de um televisor.
"""
from secao17_heranca_polimorfismo.exercicios1.questao24 import Televisor5
class Televisor6(Televisor5):
def __init__(self, numero_canais, volume_maximo):
"""Construtor que recebe as informações referente ao número de canais,
volume máximo, chama a Classe Pai e manda os valores para a mesma"""
super().__init__(numero_canais, volume_maximo)
@Televisor5.volume.setter
def volume(self, novo_valor):
"""Impedindo a mudança de valor do atributo de instância 'volume'"""
print('\nNão pode alterar o volume desse modo')
def volume_acima(self):
"""Irá para o próximo nível de volume possível em relação ao atual"""
if self.ligado:
if self.volume < self.volume_maximo:
self._Televisor__volume += 1
else:
print("\nNão pode aumentar o volume")
else:
print("\nO televisor está desligado")
def volume_abaixo(self):
"""Irá para o nível inferior de volume em relação ao atual"""
if self.ligado:
if self.volume > 0:
self._Televisor__volume -= 1
else:
print("\nNão pode diminuir o volume")
else:
print("\nO televisor está desligado")
if __name__ == "__main__":
tv1 = Televisor6(800, 200)
tv1.imprimir()
tv1.ligar()
tv1.canal = 800
tv1.volume_abaixo()
tv1.imprimir()
tv1.canal_acima()
tv1.imprimir()
tv1.canal_abaixo()
tv1.imprimir()
tv1.ligar()
tv1.volume = 41
[tv1.canal_acima() for _ in range(15)]
tv1.volume = 100
[tv1.volume_acima() for _ in range(90)]
tv1.desligar()
tv1.imprimir()
|
2b6fb7c8bed6f3e072a808a9b3ee9c5dce5d89f3 | RianMarlon/Python-Geek-University | /secao8_funcoes/exercicios/questao27.py | 1,388 | 4.375 | 4 | """
27) Faça uma função que receba como parâmetro o valor de um ângulo em
graus e calcule o valor do seno desse ângulo usando sua respectiva serie de Taylor:
sin x = E (n = 0) = (-1) ^ n / (2n + 1)! * x ^ 2n + 1 = x - (x ^ 3 / 3!) + (x ^ 5 / 5!) - ...
para todo x, onde x é o valor do ângulo em radianos. Considerar r = 3.141593 e n variando
de 0 até 5
"""
from math import factorial
def seno(angulo):
"""
Função que recebe um valor de um ângulo em graus, transforma o ângulo em graus para radianos e
calcula o valor do seno do ângulo em radianos usando a série de Taylor. Retorna o resultado do calculo
:param angulo: Recebe o valor do ângulo em graus
:return: Retorna uma mensagem informando o valor do ângulo em radianos e o resultado do cálculo.
Se o ângulo não for negativo, retorna uma mensagem informando que o ângulo é inválido.
"""
if angulo > 0:
pi = 3.141593
x = angulo * pi / 180
sen = 0.0
for n in range(6):
numerador = x ** (2 * n + 1)
denominador = factorial(2 * n + 1)
sen += (-1) ** n / denominador * numerador
return f"{angulo}° em radianos: {x}" \
f"\nSeno de {x}: {sen}"
return "Valor inválido"
angulo_em_graus = int(input("Digite o valor do ângulo em graus: "))
print(f"\n{seno(angulo_em_graus)}")
|
83a55fd6122de72ec95ef98dc45dbe1bcc90a240 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao54.py | 406 | 3.953125 | 4 | """
54) Faça um programa que receba um número inteiro maior do que 1,
e verifique se o número fornecido é primo ou não.
"""
numero = int(input("Digite um número: "))
cont = 0
if numero > 1:
for i in range(1, numero+1):
if (numero % 1 == 0) and (numero % i == 0):
cont += 1
if cont <= 2:
print("Número primo")
else:
print("Não é número primo")
|
ce9fd12e432434d8bb323b9de2cc021686e50de9 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios2/questao25.py | 3,443 | 4.34375 | 4 | """
25) Faça um programa para determnar a próxima jogada em um Jogo da Velha.
Assumir que o tabuleiro é representado por uma matriz de 3 x 3, onde cada
posição representa uma das casas do tabuleiro. A matriz pode conter os
seguintes valores -1, 0, 1 representando respectivamente uma casa contendo uma
peça minha (-1), uma casa vazia do tabuleiro (0), e uma casa contendo uma peça
do seu oponente (1)
Exemplo:
-1 | 1 | 1
-1 | -1 | 0
0 | 1 | 0
OBS: PREFERI FAZER UM JOGO DA VELHA COMPLETO
"""
jogo = []
for i in range(3):
velha = []
for j in range(3):
velha.append(0)
jogo.append(velha)
cont = 1
# Indicador se o jogo continua ou não
continua = True
vezes = 0
while continua:
# Imprimir como o jogo está antes de cada jogada
for i in range(3):
for j in range(3):
print(jogo[i][j], end=' ')
print()
if cont % 2 == 0:
print("\nVez do jogador '-1'")
elif cont % 2 == 1:
print("\nVez do jogador '1'")
linha = int(input("Digite a linha que você deseja colocar a peça (1 à 3): "))
if (linha >= 1) and (linha <= 3):
coluna = int(input("Digite a coluna que você deseja colocar a peça (1 à 3): "))
if (coluna >= 1) and (coluna <= 3):
if cont % 2 == 0:
if jogo[linha-1][coluna-1] == 0:
jogo[linha-1][coluna-1] = -1
vezes += 1
else:
print("Perdeu a vez: existe uma peça nesse local\n")
elif cont % 2 == 1:
if jogo[linha-1][coluna-1] == 0:
jogo[linha-1][coluna-1] = 1
vezes += 1
else:
print("Perdeu a vez: existe uma peça nesse local\n")
else:
print("Perdeu a vez: coluna inválida\n")
cont += 1
continue
else:
print("Perdeu a vez: linha inválida\n")
cont += 1
continue
for i in range(-1, 2, 1):
if (i == -1) or (i == 1):
for j in range(3):
# Caso dê velha na horizontal
if jogo[j][0] == i and jogo[j][1] == i and jogo[j][2] == i:
print(f"\nO jogador '{i}' venceu")
continua = False
break
# Caso dê velha na vertical
elif jogo[0][j] == i and jogo[1][j] == i and jogo[2][j] == i:
print(f"\nO jogador '{i}' venceu")
continua = False
break
# Caso dê velha na diagonal principal
elif jogo[0][0] == i and jogo[1][1] == i and jogo[2][2] == i:
print(f"\nO jogador '{i}' venceu")
continua = False
break
# Caso dê velha na diagonal inversa
elif jogo[0][2] == i and jogo[1][1] == i and jogo[2][0] == i:
print(f"\nO jogador '{i}' venceu")
continua = False
break
# Indicar se deu empate ou não
if continua and vezes >= 9:
print("\nEmpate")
continua = False
# Imprimir o jogo da velha após algum jogador vencer
if not continua:
print()
for i in range(3):
for j in range(3):
print(jogo[i][j], end=' ')
print()
cont += 1
|
7d0a180f5dbeafac354ba2bed3368520f4cb6e39 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao21.py | 431 | 3.96875 | 4 | """
21) Faça um programa que receba do usuário dois vetores, A e B,
com 10 números inteiros cada. Crie um novo vetor denominado C
calculando C = A - B. Mostre na tela os dados do vetor C
"""
a = []
b = []
for i in range(10):
a.append(int(input("Digite um valor A: ")))
b.append(int(input("Digite um valor B: ")))
c = []
for i in range(10):
c.append(a[i] - b[i])
print(f"\nDados do vetor C:")
print(*c, sep=', ')
|
6d586cda0717f45a710b3ad05c1a464ea024d040 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao31.py | 574 | 4.21875 | 4 | """
31) Faça um programa que leia dois vetores de 10 elementos. Crie
um vetor que seja a união entre os 2 vetores anteriores, ou seja,
que contém os números dos dois vetores. Não deve conter números
repetidos.
"""
vetor1 = []
vetor2 = []
for i in range(10):
vetor1.append(int(input("Digite um elemento do primeiro vetor: ")))
print()
for i in range(10):
vetor2.append(int(input("Digite um elemento do segundo vetor: ")))
conjunto1 = set(vetor1)
conjunto2 = set(vetor2)
uniao = conjunto1.union(conjunto2)
print(f"\nOs números dos dois vetores: {uniao}")
|
0b86829b854e0c4d7ee2a34513d96bcb4dac423c | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/seek_e_cursors.py | 1,665 | 4.4375 | 4 | """
Seek e Cursors
seek() -> é utilizada para moviementar o cursor pelo arquivo
arquivo = open('texto.txt', encoding='utf-8')
print(arquivo.read())
# seek() -> A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela
# recebe um parâmetro que indica onde queremos colocar o cursor
# Movimentando o cursor pelo arquivo com a função seek() -> Procurar
arquivo.seek(0)
print(arquivo.read())
arquivo.seek(22)
print(arquivo.read())
# readline() -> Função que lê o arquivo linha a (readline -> lê linha)
ret = arquivo.readline()
print(type(ret))
print(ret)
print(ret.split(' '))
# readlines()
linhas = arquivo.readlines()
print(len(linhas))
# OBS: Quando abrimos um arquivo com a função open() é criada uma conexão entre o arquivo
# no disco do computador e o seu programa. Esssa conexão é chamada de streaming. Ao finalizar
# o trabalho com o arquivo devemos fechar a conexão. Para isso devemos usar a função close()
Passos para se trabalhar com um arquivo
1 - Abrir o arquivo;
2 - Trabalhar o arquivo;
3 - Fechar o arquivo;
# 1 - Abrir o arquivo
arquivo = open('texto.txt', encoding='utf-8')
# 2 - Trabalhar o arquivo
print(arquivo.read())
print(arquivo.closed) # False Verifica se o arquivo está aberto ou fechado
# 3 - Fechar o arquivo
arquivo.close()
print(arquivo.closed) # True Verifica se o arquivo está aberto ou fechado
print(arquivo.read())
# OBS: Se tentarmos manipular o arquivo após seu fechamento, teremos um ValueError
"""
arquivo = open('texto.txt', encoding='utf-8')
# Com a função read, pdoemos limitar a quantidade de caracteres a serem lidos no arquivo
print(arquivo.read(50))
|
5ab8e65c7d7a97cde2d988e603e7a9937ed6f369 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao43.py | 560 | 3.96875 | 4 | """
43) Faça um programa que leia um número inderterminado de idades de
indivíduos (pare quando for informada a idade 0), e calcule a idade
média desse grupo.
"""
idade = int(input("Digite uma idade: "))
if idade != 0:
media = idade
cont = 1
while True:
idade = int(input("Digite uma idade: "))
if idade != 0:
media += idade
cont += 1
else:
break
print()
print("Idade média do grupo: %.0f " % (media / cont))
else:
print()
print("A idade não pode ser zero!")
|
1e739098f5ed23750ecf47efd91e4f4d75c0ddc7 | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/exercicio/questao7.py | 1,425 | 4.53125 | 5 | """
7) Faça um programa que receba do usuário um arquivo texto. Crie outro arquivo
texto contendo o texto do arquivo de entrada, mas com as vogais substituídas por '*'
"""
def substitui_vogais(txt):
"""Recebe um texto e retorna o mesmo com as vogais substituidas por '*'.
Caso não seja passado um texto por parâmetro, retornará uma string vazia"""
try:
vogais = ['a', 'e', 'i', 'o', 'u']
for vogal in vogais:
txt = txt.replace(vogal.lower(), "*")
txt = txt.replace(vogal.upper(), "*")
return txt
except AttributeError:
return ""
if __name__ == "__main__":
nome_arquivo = str(input("Digite o caminho do arquivo ou o seu nome "
"(caso o arquivo esteja no mesmo local do programa): "))
nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt"
try:
with open(nome_arquivo, "r", encoding="utf-8") as arquivo:
with open("arquivos/arq2.txt", "w", encoding="utf-8") as arquivo_novo:
arquivo_novo.write(substitui_vogais(arquivo.read()))
print("\nTexto inserido no arquivo com sucesso!")
except FileNotFoundError:
print("\nO arquivo não foi encontrado ou o programa não tem permissão para criar um diretório/pasta!")
except OSError:
print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
|
629da32c39ed294f0223f4f6903da2c132c83507 | RianMarlon/Python-Geek-University | /secao17_heranca_polimorfismo/exercicios1/questao28.py | 1,171 | 3.859375 | 4 | """
28) Baseando-se no exercício 27 adicione os métodos ligar e desligar
que deverão mudar o conteúdo do atributo ligado conforme o caso.
"""
from secao17_heranca_polimorfismo.exercicios1.questao27 import Microondas2
class Microondas3(Microondas2):
def __init__(self):
"""Construtor que chama a Classe Pai"""
super().__init__()
@Microondas2.ligado.setter
def ligado(self, novo_valor):
"""Impedindo a mudança de valor do atributo de instância 'ligado'"""
print("\nNão pode ligar ou desligar o microondas desse modo")
def ligar(self):
"""Liga o microondas"""
if self.ligado:
print("\nO microondas já está ligado")
else:
self._Eletrodomestico__ligado = True
def desligar(self):
"""Desliga o microondas"""
if self.ligado:
self._Eletrodomestico__ligado = False
else:
print("\nO microondas já está desligado")
if __name__ == "__main__":
microondas1 = Microondas3()
microondas1.ligado = "False"
microondas1.desligar()
microondas1.imprimir()
microondas1.ligar()
microondas1.imprimir()
|
ad10adfa010da02474fca887fa9c0b77e4f747f4 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao11.py | 516 | 3.890625 | 4 | """
11) Faça um programa que preencha um vetor com 10 números reais,
calcule e mostre a quantidade de números negativos e a soma dos números
positivos desse vetor.
"""
lista = []
contador = []
somador = []
for i in range(10):
lista.append(float(input(f"Digite um número decimal: ")))
if lista[i] < 0:
contador.append(lista[i])
else:
somador.append(lista[i])
print(f"\nA quantidade de números negativos: {len(contador)}")
print(f"A soma dos números positivos: {sum(somador)}")
|
47645d6a687deb9f460bd140cfd91a624c245762 | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao31.py | 214 | 4.09375 | 4 | """
31) Leia um número inteiro e imprima o seu antecessor e o seu sucessor.
"""
numero = int(input("Digite um número: "))
print(f"\nO antecessor deste número é {(numero-1)} e o seu sucessor é {(numero+1)}")
|
59ac398bcd634b7e5e4e8456fd8de56da39ae1ed | RianMarlon/Python-Geek-University | /secao8_funcoes/exercicios/questao14.py | 1,181 | 4.40625 | 4 | """
14) Faça uma função que receba a distância em Km e a quantidade de litros de gasolina
consumidos por um carro em um percurso, calcule o consumo em km/l e escreva uma mensagem
de acordo com a tabela abaixo:
| CONSUMO | (km/l) | MENSAGEM
| menor que | 8 | Venda o carro!
| entre | 8 e 12 | Econômico
| maior que | 12 | Super econômico!
"""
def consumo_km_l(distancia, gasolina):
"""
Função que recebe a distância percorrida por um carro e a quantidade da gasolina consumida
por um carro, e imprimi uma mensagem de acordo com a quantidade de quilometros por litros usado
:param distancia: Recebe a distância em quilometros percorrida pelo carro
:param gasolina: Recebe a quantidade de gasolina em litros
"""
consumo = distancia / gasolina
print()
if consumo < 8:
print("Venda o carro!")
elif (consumo >= 8) and (consumo <= 14):
print("Econômico")
elif consumo > 12:
print("Super econômico!")
distan = float(input("Digite a distância em km: "))
gasoli = float(input("Digite o consumo da gasolina consumida pelo carro: "))
consumo_km_l(distan, gasoli)
|
8f424daaccef26911fa802ceed2132b91f21bf68 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao56.py | 373 | 3.5 | 4 | """
56) Faça um programa que calcule a soma de todos os números primos
abaixo de dois milhões.
"""
qtd = 2000000
soma = 0
for i in range(1, qtd):
cont = 0
for j in range(1, i+1):
if (i % 1 == 0) and (i % j == 0):
cont += 1
if cont <= 2:
soma += i
print(f"A soma de todos os números primos abaixo de dois milhões: {soma}")
|
88031aed31fea6d609f9acd965be590139a1eb86 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao61.py | 514 | 4.0625 | 4 | """
61) Faça um programa que calcule o maior número palíndromo feito
a partir do produto de dois números de 3 dígitos. Ex: O maior palíndromo feito
a partir do produto de dois números de dois dígitos é 9009 = 91*99
"""
for i in range(999, 100, -1):
polindromo = ''
for j in range(i, 100, -1):
polindromo = str(i * j)
if polindromo[::1] == polindromo[::-1]:
break
if polindromo[::1] == polindromo[::-1]:
print(f'{polindromo} = {i} * {j}')
break
|
1063c487861ca1a0714420b887f4bc406225dc8f | RianMarlon/Python-Geek-University | /secao8_funcoes/exercicios/questao7.py | 694 | 4.28125 | 4 | """
7) Faça uma função que receba uma temperatura en graus Celsius e retorne-a
convertida em graus Fahrenheit. A fórmula de conversão é: F = C * (9.0/5.0) + 32.0,
sendo F a temperatura em Fahrenheit e C a temperatura em Celsius.
"""
def converte_em_fahrenheit(celsius):
"""
Função que recebe uma temperatura em graus Celsius e retorna em graus Fahrenheit
:param celsius: recebe os graus celsius
:return: retorna o resultado da conversão de graus Celsius em Fahrenheit
"""
return celsius * (9.0/5.0) + 32.0
celsius1 = float(input("Digite a temperatura em graus Celsius: "))
print(f"\nTemperatura em graus Fahrenheit: {converte_em_fahrenheit(celsius1)}°F")
|
e632ec6cea6fbec7fe61eff27d85067309591f0b | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios2/questao12.py | 717 | 4.1875 | 4 | """
12) Leia uma matriz de 3 x 3 elementos. Calcule e imprima a sua transposta.
"""
lista1 = []
for i in range(3):
lista2 = []
for j in range(3):
num = int(input("Digite um número: "))
lista2.append(num)
lista1.append(lista2)
print()
lista_transposta = []
# Imprimindo a matriz escrita pelo usuário e adicionando os valores na matriz transposta
for i in range(3):
lista = []
for j in range(3):
print(lista1[i][j], end=' ')
lista.append(lista1[j][i])
print()
lista_transposta.append(lista)
print(f"\nLista transposta: {lista_transposta}")
for i in range(3):
for j in range(3):
print(lista_transposta[i][j], end=' ')
print()
|
8dfeaa10644d625dacd4f011708a4827f7662068 | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao32.py | 313 | 3.9375 | 4 | """
32) Leia um número inteiro e imprima a soma do sucessor
de seu triplo com o antecessor e seu dobro.
"""
numero = int(input("Digite um número: "))
sucessor_triplo = (numero*3) + 1
antecessor_dobro = (numero*2) - 1
print(f"\n{sucessor_triplo} + {antecessor_dobro} = {(sucessor_triplo+antecessor_dobro)} ")
|
6394e529701233c81aa77a24bdd84f9b466c30c1 | RianMarlon/Python-Geek-University | /secao17_heranca_polimorfismo/exercicios1/questao14.py | 4,770 | 3.625 | 4 | """
14)Baseando-se no exercício 13 adicione o atributo ligada que terá a função
de indicar se a moto está ligada ou não. Este atributo deverá ser do tipo
boleano. O método imprimir deve ser modificado de forma a mostrar na tela
os vaores de todos os atributos.
"""
from secao17_heranca_polimorfismo.exercicios1.questao13 import Moto5
class Moto6(Moto5):
def __init__(self, ligada):
"""Construtor que recebe a informação referente a moto(se está ligada ou não),
chama a Classe Pai e verifica se o valor recebido é válido ou não"""
super().__init__()
try:
if type(ligada) == str:
if ligada.strip().title() == "False" or ligada.strip() == "0":
self.__ligada = False
elif ligada.strip().title() == "True" or ligada.strip() == "1":
self.__ligada = True
else:
raise ValueError
elif type(ligada) == int:
if ligada == 0:
self.__ligada = False
elif ligada == 1:
self.ligada = True
else:
raise ValueError
elif type(ligada) == bool:
self.__ligada = ligada
except ValueError:
print("\nValor inválido")
exit(1)
@property
def ligada(self):
"""Retorna o valor contido no atributo de instância 'ligada'"""
return self.__ligada
@ligada.setter
def ligada(self, novo_valor):
"""Recebe um valor que irá ser o novo valor do atributo de instância 'ligada'"""
try:
if type(novo_valor) == str:
if novo_valor.strip().title() == "False" or novo_valor.strip() == "0":
novo_valor = False
elif novo_valor.strip().title() == "True" or novo_valor.strip() == "1":
novo_valor = True
else:
raise ValueError
elif type(novo_valor) == int:
if novo_valor == 0:
novo_valor = False
elif novo_valor == 1:
novo_valor = True
else:
raise ValueError
elif type(novo_valor) == bool:
novo_valor = novo_valor
else:
raise ValueError
if self.__ligada != novo_valor:
if self.marcha == self.menor_marcha:
self.__ligada = bool(novo_valor)
else:
print("\nAVISO: A marcha não está no neutro(menor marcha)")
self.__ligada = bool(novo_valor)
else:
if bool(novo_valor):
print("\nA moto já está ligada")
else:
print("\nA moto já está desligada")
except ValueError:
print("\nValor inválido")
def marcha_abaixo(self):
"""Desce uma marcha, caso a moto esteja ligada e ainda tenha uma marcha abaixo da atual"""
if self.__ligada:
if self.marcha > self.menor_marcha:
self._Moto__marcha -= 1
else:
print("\nJá se encontra na menor marcha")
else:
print("\nMoto está desligada")
def marcha_acima(self):
"""Sobe uma marcha, caso a moto esteja ligada e ainda tenha uma marcha acima da atual"""
if self.__ligada:
if self.marcha < self.maior_marcha:
self._Moto__marcha += 1
else:
print("\nJá se encontra na maior marcha")
else:
print("\nMoto está desligada")
def imprimir(self):
"""Imprimi todos os valores de todos os atributos"""
print(f"\nMarca: {self.marca}")
print(f"Modelo: {self.modelo}")
print(f"Cor: {self.cor}")
print(f"Marcha atual: {self.marcha}")
print(f"Menor marcha: {self.menor_marcha}")
print(f"Maior marcha: {self.maior_marcha}")
print(f"Ligada? {'Sim' if self.__ligada else 'Não'}")
if __name__ == "__main__":
moto1 = Moto6("False")
moto1.marca = "yamaha"
moto1.imprimir()
moto1.modelo = "xj6"
moto1.imprimir()
moto1.cor = "branco"
moto1.imprimir()
moto1.maior_marcha = 6
moto1.menor_marcha = 1
moto1.imprimir()
moto1.marcha_acima()
moto1.marcha_acima()
moto1.ligada = "True"
moto1.imprimir()
moto1.marcha_acima()
moto1.marcha_acima()
moto1.marcha_abaixo()
moto1.marcha_acima()
moto1.imprimir()
moto1.ligada = False
moto1.imprimir()
moto1.ligada = True
moto1.imprimir()
moto1.ligada = True
|
817afa6ba0fa59ea7a20951dcbf2d0f05c923892 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios2/questao13.py | 969 | 3.984375 | 4 | """
13) Gere matriz 4 x 4 com valores no intervalo [1, 20]. Escreva um programa que transforme
a matriz gerada numa matriz triangular inferior, ou seja, atribuindo zero a todos os
elementos acima da diagonal principal. Imprima a matriz original e a matriz transformada.
"""
from random import randint
lista1 = []
for i in range(4):
lista2 = []
for j in range(4):
lista2.append(randint(1, 20))
lista1.append(lista2)
# Imprimindo a matriz gerada
for i in range(4):
for j in range(4):
print(lista1[i][j], end=' ')
print()
print()
cont = 0
for i in range(4):
for j in range(4):
if i != 0 and i == j:
# Pegando os valores que estão acima da linha onde se encontra a coluna da diagonal e adicionando 0
for k in range(1, i+1):
lista1[i-k][j] = 0
# Imprimindo a matriz tranformada
for i in range(4):
for j in range(4):
print(lista1[i][j], end=' ')
print()
|
d97e97cfae318749b02ac8d4931d0c88693086fc | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao40.py | 467 | 3.78125 | 4 | """
40) Uma empresa contrata um encanador a R$30,00 por dia.
Faça um programa que solicite o número de dias trabalhados pelo encanador e imprima
a quantida liquida que deverá ser paga. Sabendo-se que são descontandos 8% para imposto de renda.
"""
dias = int(input("Digite o número de dias trabalhados pelo encanador: "))
salario_total = 30.00 * dias
salario_total -= (salario_total * 0.08)
print("\nValor do salário total:\n"
"R$%.2f" % salario_total)
|
7d71a7a4966b7afad6a9925204e50a77aa378a00 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao7.py | 354 | 3.890625 | 4 | """
7) Faça um programa que leia 10 inteiros positivos, ignorando não positivos,
e imprima sua média
"""
media = 0
soma = 0
cont = 10
for i in range(1, 11):
num = int(input(f"Digite o {i}° valor: "))
if num < 0:
cont -= 1
else:
soma += num
if i >= 10:
media = soma / cont
print()
print(f"Média: {media}")
|
23db56ca0a223cc59e354555551c741d60291243 | RianMarlon/Python-Geek-University | /secao6_estrutura_repeticao/exercicios/questao5.py | 202 | 4.09375 | 4 | """
5) Faça um programa que peça ao usuário para digitar
10 valores e some-os.
"""
soma = 0
for i in range(10):
num = int(input(f"Digite o {i+1}° valor: "))
soma += num
print()
print(soma) |
3ac4d3fe40faded55b34fdb5d4ee7f4d96b46294 | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/exercicio/questao2.py | 746 | 4.15625 | 4 | """
2) Faça um programa que receba do usuário um arquivo texto e mostre na tela
quantas linhas esse arquivo possui
"""
nome_arquivo = str(input("Digite o caminho do arquivo ou o nome do mesmo "
"(caso o arquivo esteja no mesmo local do programa): "))
nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt"
try:
with open(nome_arquivo, "r", encoding='utf-8') as arquivo:
texto = arquivo.read()
quebra_de_linha = len(texto.splitlines())
print(f"\nO arquivo possui {quebra_de_linha + 1} linhas!")
except FileNotFoundError:
print("\nArquivo informado não encontrado!")
except OSError:
print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
|
71697a5618601f4d66deacf954b310fe8a252f6d | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao33.py | 253 | 3.890625 | 4 | """
33) Leia o tamanho do lado de um quadrado e imprima como resultado a sua área.
"""
lado_quadrado = float(input("Digite o tamanho do lado do quadrado: "))
print(f"\nA áresa do quadrado:\n{lado_quadrado} * {lado_quadrado} = {(lado_quadrado**2)}")
|
2e1a96d3743aee0e4fb824f70bf0549d399caf0a | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao5.py | 157 | 3.828125 | 4 | """
5) Leia um número real e imprima a quinta parte deste número.
"""
numero_real = float(input("Digite um número real: "))
print("%.5f" % numero_real)
|
05f3c2709b5ef395ec8a39d1160720d98592dfd2 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios2/questao14.py | 847 | 4.15625 | 4 | """
14) Faça um prorgrama para gerar automaticamente números entre 0 e 99 de uma
cartela de bingo. Sabendo que cada cartela deverá conter 5 linhas de 5
números, gere estes dados de modo a não ter números repetidos dentro das cartelas.
O programa deve exibir na tela a cartela gerada.
"""
from random import randint
lista1 = []
lista3 = []
while len(lista1) < 5:
lista2 = []
while len(lista2) < 5:
num = randint(0, 99)
# Se o número aleatório não existir na lista3, adicione o valor na lista3 e adicione o valor na matriz lista2
# Assim, o número não irá se repetir em nenhuma matriz
if num not in lista3:
lista3.append(num)
lista2.append(num)
lista1.append(lista2)
for i in range(5):
for j in range(5):
print(lista1[i][j], end=' ')
print()
|
90f25b0dd3310dbc4e7a2420cea812ec9c86d803 | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao2.py | 138 | 3.890625 | 4 | """
2) Faça um programa que leia um número e o imprima.
"""
numero_real = float(input("Digite um número real: "))
print(numero_real)
|
a13fc7f9f9938ea7e72f3f8bb7a4b4eb64d0ec6a | RianMarlon/Python-Geek-University | /secao4_variaveis_tipos_de_dados/exercicios/questao6.py | 385 | 4.09375 | 4 | """
6) Leia uma temperatura em gruas Celsius e apresente-a convertida
em graus Fahrenheit. A fórmula de conversão é: F = C*(9.0/5.0)+32,
sendo F a temperatura em Fahrenheit e C a temperatura em Celsius.
"""
celsius = float(input("Digite a temperatura em graus Celsius °C: "))
fahrenheit = celsius*(9.0/5.0)+32
print("A temperatura em graus Fahrenheit é %.2f°F" % fahrenheit)
|
d1f57a43c27c0cfed1a993c42a06ca921968aa10 | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/exercicio/questao6.py | 1,464 | 4.40625 | 4 | """
6) Faça um programa que receba do usuário um arquivo texto e mostre na tela quantas
vezes cada letra do alfabeto aparece dentro do arquivo.
"""
def qtd_letras(txt):
"""Recebe um texto e imprimi na tela cada letra do alfabeto e a quantidade
de vezes que a mesma aparece no texto. Caso não seja passado um texto, a função
imprimirá uma mensagem informando que o valor recebido por parâmetro não é um texto"""
txt = txt.lower()
letras = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print()
try:
for letra in letras:
print(f"A letra {letra} se repete {txt.count(letra)} vezes no texto")
except AttributeError:
print("O valor recebido por parâmetro não é um texto/string")
if __name__ == "__main__":
nome_arquivo = str(input("Digite o caminho do arquivo ou o seu nome "
"(caso o arquivo esteja no mesmo local que do arquivo): "))
nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt"
try:
with open(nome_arquivo, "r", encoding="utf-8") as arquivo:
texto = arquivo.read().lower()
qtd_letras(texto)
except FileNotFoundError:
print("\nArquivo informado não encontrado!")
except OSError:
print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
|
e6048ff85c0b82e43e31323adafe362f00a16ee6 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao34.py | 740 | 4.09375 | 4 | """
34) Faça um programa para ler 10 números DIFERENTES a serem armazenados
em um vetor. Os dados deverão ser armazenados no vetor na ordem que
forem sendo lidos, sendo que o caso o usuário digite um número
que já foi digitado anteriormente, o programa deverá pedir para ele
digitar outro número. Note que cada valor digitado pelo usuário deve
ser pesquisado no vetor, verificando se ele existe entre os números que
já foram fornecidos. Exibir na tela o vetor final que foi digitado.
"""
lista = []
while True:
if len(lista) >= 10:
break
num = int(input("Digite um número: "))
if num in lista:
print("Digite outro número")
else:
lista.append(num)
print(f"\nVetor final: {lista}")
|
91a1ae05f6ce3753e00b5b7e77f54bafee9c3baf | RianMarlon/Python-Geek-University | /secao13_leitura_escrita_de_arquivos/exercicio/questao14.py | 2,971 | 4.03125 | 4 | """
14) Dado um arquivo contendo um conjunto de nome e data nascimento (DD MM AAAA,
isto é, 3 inteiros em sequência), faça um programa que leia o nome do arquivo
e a data de hoje e construa outro arquivo contendo o nome e a idade de cada
pessoa do primeiro arquivo.
"""
from datetime import date
nome_arquivo = str(input("Digite o caminho do arquivo ou o seu nome "
"(caso o arquivo esteja no mesmo local do programa): "))
nome_arquivo = nome_arquivo if ".txt" in nome_arquivo else nome_arquivo + ".txt"
try:
with open(nome_arquivo, "r", encoding="utf-8") as arquivo:
informacoes = arquivo.read()
# O strip() irá remover coisas desnecessárias do inicio e fim do texto
# o splitlines() criará um vetor, onde cada elemento do vetor é uma linha do arquivo
informacoes = informacoes.strip().splitlines()
# Irá criar outro vetor dentro de cada elemento(uma matriz),
# separando a parte do nome e da data de nascimento
informacoes = [informacao.split(";") for informacao in informacoes]
# Um vetor para receber todos os nomes
nomes = [infor[0] for infor in informacoes]
# Criará uma matriz, onde o vetor de cada elemento separará o dia, mês e ano
datas = [infor[1].split(" ") for infor in informacoes]
# Colocando a data atual em uma variável
data_hoje = date.today()
ano_hoje = data_hoje.year
mes_hoje = data_hoje.month
dia_hoje = data_hoje.day
with open("arquivos/nome_idade.txt", "w", encoding="utf-8") as novo_arquivo:
for posicao in range(len(datas)):
# O ano atual subtraido pelo ano da data de nascimento
idade = ano_hoje - int(datas[posicao][2])
if idade > 0:
# Se o mês da data de nascimento for maior que o mês atual...
if int(datas[posicao][1]) > mes_hoje:
idade -= 1
# Se o mês da data de nascimento for igual o mês atual e o dia da data de nascimento
# for maior que o dia atual...
elif int(datas[posicao][1]) == mes_hoje and int(datas[posicao][0]) > dia_hoje:
idade -= 1
novo_arquivo.write(f"Nome: {nomes[posicao]};Idade: {idade}\n")
else:
novo_arquivo.write(f"Nome: {nomes[posicao]};Idade: 0\n")
print("\nInformações inseridas no arquivo com sucesso!")
except FileNotFoundError:
print("\nO arquivo informado não foi encontrado ou o programa não tem permissão para criar um diretório/pasta!")
except OSError:
print("\nO SO não aceita caracteres especiais em nomes de arquivo!")
except ValueError:
print("\nO modo que as informações se encontram no arquivo é inválido!")
except IndexError:
print("\nO modo que as informações se encontram no arquivo é inválido!")
|
cfbe486d8b5d6e1e3ecfbaf82f6b3d654bdd5a87 | H874589148/python-study | /game/number.py | 222 | 3.734375 | 4 | import random
number = random.randint(0, 9)
inp_number = input("请输入你猜的数字(0-9):")
if inp_number == number:
print ("恭喜猜对了")
else :
print ("抱歉猜错了,正确答案是%d"%number) |
457ebdae7f3e1b437f90a62b6b24d05c6d41c529 | H874589148/python-study | /12/12.2.10滚动条.py | 418 | 3.6875 | 4 | from tkinter import *
root = Tk()
root.title("Hawkeye")
# 设定一个列表组件
l = Listbox(root, height=6, width=15)
# 定义滚动条,并绑定一个回调
scroll = Scrollbar(root, command=l.yview)
l.configure(yscrollcommand=scroll.set)
l.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)
#for item in ['apple', 'orange', 'peach', 'banana', 'melon']:
for item in range(20):
l.insert(END, item)
root.mainloop() |
79fec5efe8deeaa2952ae460fc5bd5343dadbc3c | H874589148/python-study | /6.1.5.py | 183 | 4.0625 | 4 | word = "hello world"
print ("hello"==word[0:5])
print (word.startswith("hello"))
print (word.endswith("ld",6))
print (word.endswith("ld",6,10))
print (word.endswith("ld",6,len(word))) |
223e1a85577f4fba65430c34ba5cfa9e4b3aed8e | onl1steam/wide_nets | /1_Lab/text_processing.py | 1,196 | 3.78125 | 4 | class Divider:
def __init__(self, text, codeword_length):
self.codeword_length = codeword_length
self.data = ''
for letter in text:
letter_code = bin(ord(letter))[2:]
letter_code = (16 - len(letter_code)) * '0' + letter_code
self.data += letter_code
self.i_codeword = 0
self.n_codewords = len(self.data) // codeword_length
remainder = len(self.data) % codeword_length
if remainder != 0:
self.n_codewords += 1
self.data += (codeword_length - remainder) * '0'
def __iter__(self):
return self
def __next__(self):
i = self.i_codeword
if i < self.n_codewords:
self.i_codeword += 1
return self.data[i*self.codeword_length:(i+1)*self.codeword_length]
else:
raise StopIteration()
def merge(codewords):
data = ''
for codeword in codewords:
data += codeword
text = ''
i_letter = 0
letter_code = data[:16]
while '1' in letter_code:
text += chr(int(letter_code, base=2))
i_letter += 1
letter_code = data[16*i_letter:16*(i_letter+1)]
return text
|
b2f8f548e21cc9ae86a8df92fb02988c85cdadc3 | aishidajt9/AgentBasedModeling | /turtle_random.py | 584 | 3.75 | 4 | import turtle
import random
n_turtles = 10
wn = turtle.Screen()
kames = [turtle.Turtle() for i in range(n_turtles)]
colours=["red","blue","yellow","brown","black","purple","green"]
for i, t in enumerate(kames):
t.shape('turtle')
t.color(colours[i%7])
t.speed(0)
t.goto(random.randrange(-100, 100), random.randrange(-100, 100))
def random_walk(ts, steps):
for steps in range(steps):
for t in ts:
t.forward(random.randrange(0, 50))
t.right(random.randrange(0,180))
random_walk(kames, 100)
wn.exitonclick() |
642ca7c2f5133424cd5790f2994403f8b97a2419 | luiscarlossf/how-to-contribute | /code/python/f.py | 202 | 3.90625 | 4 | a = int(input('Digite a:'))
b = int(input('Digite b:'))
soma = a+b
sub = a - b
mult = a*b
div = a / b
print ('Soma = %d'%soma)
print ('Sub = %d'%sub)
print ('mult = %d'%mult)
print ('div = %d'%div)
|
ec33a45b662700a60463ef4d456f6abf44c79525 | SkylaBlue/SteamID-To-CommunityID | /CommID.py | 1,535 | 3.859375 | 4 | """
Source https://developer.valvesoftware.com/wiki/SteamID
Following that guide, we can convert a SteamID to it's community id.
"""
def SteamToComm():
SteamID = raw_input("Enter SteamID: ")
# Doesn't really need to be caps, but I prefer it
if not SteamID.startswith("STEAM_"):
print "Please use a valid steam id!"
splitID = SteamID.split(":")
Universe = int(splitID[1])
# User entered a SteamID with a universe greater than one, which is basically impossible
if Universe > 1:
print "Please use a valid steam id!"
LastDigits = int(splitID[2])*2
# User entered a SteamID with an id less than 1, which is impossible
if LastDigits < 1:
print "Please use a valid steam id!"
# Valve uses 0x0110000100000000 as the SteamID64 identifier
Algo = 76561197960265728
CommunityID = Algo + LastDigits + Universe
print "\nCommunity ID:", CommunityID
def CommToSteam():
CommID = long(raw_input("Enter community id: "))
Algo = 76561197960265728
Universe = CommID % 2
SteamID = (CommID - Algo - Universe) / 2
print "\nSteamID: STEAM_0:%s:%s" % (int(Universe), SteamID)
def main():
choise = raw_input("1: SteamID->CommunityID\n" \
"2: CommunityID->SteamID\n" \
"-> ")
if choise == '1':
SteamToComm()
elif choise == '2':
CommToSteam()
else:
print "Please enter 1 or 2!"
while True:
main()
raw_input()
|
a901c913928093b95984405dbaaac021c5116eb6 | Pramod-Shrinivas/Scripts-Cryptography | /001-CaeserCipher.py | 1,761 | 3.875 | 4 | #!/usr/bin/python
import sys
import argparse
def caesercipher(string,shift):
cipher=""
for x in string:
temp=""
if(ord(x)>64 and ord(x)<91):
temp=chr(ord(x) + shift)
if(ord(temp) > 90 ):
temp=chr(ord(temp) - 26)
elif(ord(x)>96 and ord(x)<123):
temp=chr(ord(x) + shift)
if(ord(temp) > 122 ):
temp=chr(ord(temp) - 26)
else:
temp=x
cipher+=temp
return cipher
def main(argv):
desc="""Print all possible shifts/rot combinations (only 0-25)"""
epilog="""Credits (C) Pramod.S """
parser = argparse.ArgumentParser(description=desc,epilog=epilog)
parser.add_argument("--f",help="Enter the file path",dest='filePath',required=True)
parser.add_argument("--r",help="[Optional] Shift/Rotation by",type=int,dest='shift',required=False)
temp=parser.parse_args()
filePath=temp.filePath
shift=temp.shift
inputFile = open(filePath,'r')
outputFile = open('output.txt','w')
if(shift is None):
for i in range(1,26):
inputFile.seek(0,0)
print("ROT {0}: {1}".format(i,caesercipher(inputFile.read().split('\n'),i)))
inputFile.seek(0,0)
outputFile.write("ROT {0}: {1}\n".format(i,caesercipher(inputFile.read().split('\n'),i)))
else:
if(shift>0 and shift <26):
print("ROT {0}: {1}".format(shift,caesercipher(inputFile.read().split('\n'),shift)))
inputFile.seek(0,0)
outputFile.write("ROT {0}: {1}\n".format(shift,caesercipher(inputFile.read().split('\n'),shift)))
inputFile.close()
outputFile.close()
if __name__ == "__main__":
main(sys.argv[1:])
|
cc6cb9da58a14303e1eee30a74ede323f2518473 | kdudhat/Data-staructure-Algorithm-python | /Greedy Algorithm/maximum_value_of_the_loot.py | 1,052 | 3.703125 | 4 | '''
The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
Input Format:
The first line of the input contains the number 𝑛 of items and the capacity 𝑊 of a knapsack. The next 𝑛 lines define the values and weights of the items.
The 𝑖-th line contains integers 𝑣𝑖 and 𝑤𝑖—the value and the weight of 𝑖-th item, respectively.
Input:
3 50
60 20
100 50
120 30
Output:
180.0000
'''
n,total_weight = map(int, input().split())
total_value = 0
l = list()
for i in range(n):
value,weight = map(int,input().split())
l.append([value,weight,value/weight])
def Sort(sub_li):
return(sorted(sub_li, key = lambda x: x[2], reverse=True))
l = Sort(l)
for i in l:
if total_weight == 0:
break
if total_weight<i[1]:
x = i[1]/total_weight
total_value+=i[0]/x
total_weight=0
else:
total_value+=i[0]
total_weight-=i[1]
print(total_value)
|
6abc3155da09e46d2c1436f4726b1668090dc0bf | Funnul/Codingbat | /Logic-2/make_bricks(review).py | 426 | 3.90625 | 4 | # def make_bricks(small, big, goal):
# s = small * 1
# b = big * 5
# if (b + s >= goal):
# return True
# else:
# return False
def make_bricks(small, big, goal):
# Distance bigs cover? Goal - lowest number of bigs needed * 5cm = Remaining distance
goal = goal - 5 * min(big, goal/5)
# Enough smalls to cover? Remaining distance - smalls = 0 or lower
return (goal - small) <= 0
|
f7257851b637af0cc802d81f66f4d91410f4d85e | Funnul/Codingbat | /Warmup-1/front_back.py | 257 | 3.90625 | 4 |
def front_back(str):
if len(str) <= 1:
return str
else:
return str[len(str)-1] + str[1:-1] + str[0]
return front_back
# len(str)-1 is last letter, 1:-1 is range from 2nd to 2nd last
# because 1:-1 range is non-inclusive of -1
|
401af4f11f964831e459b76e5002473400e8e6da | tomrozanski/Imdb-Web-Scraping | /MovieFileWriter.py | 392 | 3.921875 | 4 | import os
class MovieFileWriter(object):
def write_to_file(self, movies, path):
save_path = path
file_name = "movies_file.txt"
final_path = os.path.join(save_path, file_name)
text_file = open(final_path, "w")
for movie in movies:
text_file.write(str(movie))
print("The movie text file is in: "+path)
text_file.close()
|
05dbf2f6923071eccad18dc65d97a3e0baab3333 | schlangens/Python_Shopping_List | /shopping_list.py | 632 | 4.375 | 4 | # MAKE sure to run this as python3 - input function can cause issues - Read the comments
# make a list to hold onto our items
shopping_list = []
# print out instruction on how to use the app
print('What should we get at the store?')
print("Enter 'DONE' to stop adding items.")
while True:
# ask for new items
# if using python 2 change this to raw_input()
new_item = input("Item: ")
# be able to quit the app
if new_item == 'DONE':
break
# add new items to our list
shopping_list.append(new_item)
# print out the list
print("Here's your list:")
for item in shopping_list:
print(item)
|
6ecf406d735ba464e84ef6040c5222602a81e689 | alma-frankenstein/Rosalind | /all_substrings.py | 359 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#find each substring slice in the superstring
string = "" #insert string here
def everySubstring(string):
substrings = []
for i in range(len(string)):
for j in range(i, len(string)):
substrings.append(string[i:j+1])
return substrings
print(everySubstring(string))
|
ed5c9669052efef4d7003952c0a7f20437c5109d | alma-frankenstein/Rosalind | /RNA.py | 284 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Transcribing DNA to RNA
#Given: A DNA string t
#Return: The transcribed RNA string of t
.
filename = 'rosalind_rna.txt'
with open(filename) as file_object:
contents = file_object.read()
rna = contents.replace('T', 'U')
print(rna)
|
2a18aedf5b870c59e5d0fb45fc6a14878549f891 | alma-frankenstein/Rosalind | /SPLC.py | 720 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#RNA splicing
#Given: A DNA string s (of length at most 1 kbp) and a collection of substrings of s
#acting as introns. All strings are given in FASTA format.
#Return: A protein string resulting from transcribing and translating the exons of s
import PROT, fastaToDict
def main():
filename = 'rosalind_splc.txt'
dna = "" #manually delete sequence from fasta, paste it here
introns = fastaToDict.fastaToDict(filename)
for k, v in introns.items():
dna = dna.replace(v,"")
rna = dna.replace('T', 'U') #turn DNA to RNA
rna = list(rna)
protein = PROT.rnaToProtein(rna)
print(protein)
if __name__ == "__main__":
main()
|
6a8203f812ccc5b829b20e7698246d8c327ac3af | dudejadeep3/python | /Tutorial_Freecodecamp/11_conditionals.py | 530 | 4.34375 | 4 | # if statement
is_male = True
is_tall = False
if is_male and is_tall:
print("You are a tall male.")
elif is_male and not is_tall:
print("You are a short male")
elif not is_male and is_tall:
print("You are not a male but tall")
else:
print("You are not male and not tall")
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num3:
return num2
else:
return num3
print(max_num(4,1,10))
# we can compare strings also == is used for equal
|
dbfd05d60911bf8141c1bf910cad8229915e420a | dudejadeep3/python | /Tutorial_Freecodecamp/06_input.py | 467 | 4.25 | 4 | # Getting the input from the users
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! You are "+age)
# Building a basic calculator
num1 = input("Enter a number:")
num2 = input("Enter another number:")
result = float(num1) + float(num2); # we could use int() but it will remove decimal points
print(result);
# if we int() and pass number with decimal then we will get
# an error and program will stop.
# result = int(5.5) |
725178aa99c25c148bdf75ce5dcfb4ad20538c87 | MiyabiTane/myLeetCode_ | /34_m_Find_FirstAndLast_Position.py | 899 | 3.75 | 4 | def searchRange(nums,target):
left=0
right=len(nums)-1
while left<=right:
mid=(left+right)//2
print("mid={}".format(mid))
if target==nums[mid]:
ans_if=mid
rig=mid
lef=mid
while True:
if rig==len(nums)-1:
break
elif nums[rig+1]!=target:
print("right={}".format(rig))
break
rig+=1
while True:
if lef==0:
break
elif nums[lef-1]!=target:
print("left={}".format(lef))
break
lef-=1
return [lef,rig]
elif nums[left]<=target and target<=nums[mid]:
right=mid-1
else:
left=mid+1
return [-1,-1]
ans=searchRange([3,4,5,6,6,7,8],6)
print(ans)
|
08061f9e3c90eb634198e7e05c67ae2e976b0013 | MiyabiTane/myLeetCode_ | /14_Longest_Common_Prefix.py | 606 | 3.640625 | 4 | def longestCommonPrefix(strs):
result=""
i=0
while True:
try:
sets=set(string[i] for string in strs)
if len(sets)==1:
result+=sets.pop()
i+=1
else:
break
#>>> strs=["art","bar","cat"]
#>>> for i in range(3):
#... sets=set(string[i] for string in strs)
#... print(sets)
#...
#set(['a', 'c', 'b'])
#set(['a', 'r'])
#set(['r', 't'])
except Exception as e:
break
return result
|
a225d2158f480d255f072aa85938996f8d40afb0 | MiyabiTane/myLeetCode_ | /30-Day_Challenge/3_Maximum_Sunarray.py | 354 | 3.875 | 4 | def maxSubArray(nums):
max_num = nums[0]
max_pre = nums[0]
for i in range(1,len(nums)):
if nums[i] > max_pre+nums[i]:
max_pre= nums[i]
else:
max_pre += nums[i]
if max_pre > max_num:
max_num = max_pre
return max_num
ans = maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
print(ans)
|
4c32d3d46ef193f271344567c67357a09c04332c | MiyabiTane/myLeetCode_ | /May_LeetCoding_Challenge/26_Contiguous_Array.py | 553 | 3.78125 | 4 | def findMaxLength(nums):
#memo key:sum value:index
memo = {0:1}
sum = 0
max_len = 0
for i,num in enumerate(nums):
if num == 0:
sum -= 1
elif num == 1:
sum += 1
if sum in memo:
#同じ値になるということはその間にある0と1の数が等しいということ
leng = i - memo[sum]
if leng > max_len:
max_len = leng
else:
memo[sum] = i
return max_len
ans = findMaxLength([0, 1, 0])
print(ans)
|
70599342ebfa288044941ee9ff5afab7eb59ee3c | MiyabiTane/myLeetCode_ | /30-Day_Challenge/25_Jump_Game.py | 337 | 3.6875 | 4 | def canJump(nums):
#その位置から最後のマスにたどり着けるのがGoodマス
Good_left = len(nums) - 1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= Good_left:
Good_left = i
if Good_left == 0:
return True
return False
ans = canJump([3, 2, 1, 0, 4])
print(ans)
|
9805e9be91f3a6ee0c04367eb6ad0be6760d640a | MiyabiTane/myLeetCode_ | /43_m_Multiply_Strings.py | 601 | 3.984375 | 4 | def multiply(num1,num2):
dict={"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"0":0}
dict2={1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",0:"0"}
int1=0
for i in range(len(num1)):
int1+=dict.get(num1[i])*(10**(len(num1)-i-1))
int2=0
for i in range(len(num2)):
int2+=dict.get(num2[i])*(10**(len(num2)-i-1))
mul=int1*int2
ans=""
while True:
num=mul%10
#print(dict2.get(num))
ans=dict2.get(num)+ans
if mul<10:
break
mul=mul//10
return ans
answer=multiply("123","456")
print(answer) |
5113f69dae5eb3e61e55694e85f364bc68500ce3 | MiyabiTane/myLeetCode_ | /30-Day_Challenge/16_Valid_Parenthesis_String.py | 819 | 3.71875 | 4 | def checkValidString(s):
#'('と')'の数だけに注目すれば良い。*はあり得るパターンをメモすればいい。
low = 0; high =0
for sig in s:
if sig == '(':
low += 1; high += 1
elif sig == ')':
low -= 1; high -= 1
elif sig == '*':
low -= 1 #もし*が)だったら
high += 1 #もし*が(だったら
low = max(0, low) #low<0の時点でFalse
if high < 0: #)が一番左にきてしまった時
return False
#print(low, high)
#lowとhighの間に0がある、すなわち左右の()数が等しくなり得る時
if low == 0:
return True
return False
ans = checkValidString("(())((())()()(*)(*()(())())())()()((()())((()))(*")
print(ans)
|
e81499187da200be8bd4fe4fdf98da5c6a87dfce | MiyabiTane/myLeetCode_ | /168_Excel_Sheet.py | 413 | 3.5 | 4 | def convertToTitle(n):
dict={1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',7:'G',8:'H',9:'I',10:'J',11:'K',12:'L',13:'M',14:'N',15:'O',16:'P',17:'Q',18:'R',19:'S',20:'T',21:'U',22:'V',23:'W',24:'X',25:'Y',26:'Z'}
if n<=26:
return dict.get(n)
else:
div=(n-n%26)/26
rem=(n%26)
if rem==0:
rem=26
div-=1
return convertToTitle(div)+convertToTitle(rem)
|
385be12dd84a66a87146f86702a97e8e1c87cc70 | MiyabiTane/myLeetCode_ | /STEP/week3/homework1.py | 5,697 | 3.640625 | 4 | def readNumber(line, index):
number = 0
while index < len(line) and line[index].isdigit():
number = number * 10 + int(line[index])
index += 1
if index < len(line) and line[index] == '.':
index += 1
keta = 0.1
while index < len(line) and line[index].isdigit():
number += int(line[index]) * keta
keta /= 10
index += 1
token = {'type': 'NUMBER', 'number': number}
return token, index
def readPlus(line, index):
token = {'type': 'PLUS'}
return token, index + 1
def readMinus(line, index):
token = {'type': 'MINUS'}
return token, index + 1
def readMalti(line, index):
token = {'type' : 'MALTI'}
return token, index + 1
def readDevis(line, index):
token = {'type' : 'DEVIS'}
return token, index + 1
def tokenize(line):
#when input contains space, remove
line = line.replace(' ','')
# ALEXNOTE: good trick, remove all the spaces beforehand without changing the tokenizer.
# mind you that this is a trade-off: it requires more computation to do it this way,
# as replace() will traverse the entire string. Not wrong, just something to keep in mind
# - many times, it is worth it to spend more computing time to keep the program simple.
tokens = []
index = 0
while index < len(line):
if line[index].isdigit():
(token, index) = readNumber(line, index)
elif line[index] == '+':
(token, index) = readPlus(line, index)
elif line[index] == '-':
(token, index) = readMinus(line, index)
elif line[index] == '*':
(token, index) = readMalti(line, index)
elif line[index] == '/':
(token, index) = readDevis(line, index)
#when input is fractional numbers without a leading zero
elif line[index] == ".":
line = line[:index] + '0' + line[index:]
# ALEXNOTE: the statement above is another example of a program simplification which is
# relatively expensive: it is re-creating the entire input sting.
(token, index) = readNumber (line, index)
else:
print('Invalid character found: ' + line[index])
exit(1)
tokens.append(token)
#print(tokens)
return tokens
def firstEvaluate(tokens):
def checker(tokens, index):
if tokens[index - 1]['type'] != 'NUMBER' or tokens[index + 1]['type'] != 'NUMBER':
print('Invalid syntax')
exit(1)
tokens.insert(0, {'type': 'PLUS'}) # Insert a dummy '+' token
index = 0
while index < len(tokens):
if tokens[index]['type'] == 'MALTI':
checker(tokens, index)
new_number = tokens.pop(index - 1)['number'] * tokens.pop(index)['number']
tokens.insert(index - 1, {'type': 'NUMBER', 'number': new_number})
tokens.pop(index)
elif tokens[index]['type'] == 'DEVIS':
checker(tokens, index)
if tokens[index + 1]['number'] == 0:
print("cannot devide by 0")
exit(1)
new_number = tokens.pop(index - 1)['number'] / tokens.pop(index)['number']
tokens.insert(index - 1, {'type': 'NUMBER', 'number': new_number})
tokens.pop(index)
else:
index += 1
#print(tokens)
return tokens
def secondEvaluate(new_tokens):
answer = 0
index = 1
while index < len(new_tokens):
if new_tokens[index]['type'] == 'PLUS' or new_tokens[index]['type'] == 'MINUS':
if new_tokens[index+1]['type'] != 'NUMBER':
print("Invalid syntax")
exit(1)
if new_tokens[index]['type'] == 'NUMBER':
if new_tokens[index - 1]['type'] == 'PLUS':
answer += new_tokens[index]['number']
elif new_tokens[index - 1]['type'] == 'MINUS':
answer -= new_tokens[index]['number']
else:
print('Invalid syntax')
exit(1)
index += 1
return answer
def tokenToNumber(tokens):
new_tokens = firstEvaluate(tokens)
actualAnswer = secondEvaluate(new_tokens)
return actualAnswer
def test(line):
if len(line) == 0:
print("please input some numbers")
return None
tokens = tokenize(line)
actualAnswer = tokenToNumber(tokens)
# ALEXNOTE: I like this solution best. However: does it ever make sense to invoke firstEvaluate without secondEvaluate?
# Or does it make sense to call firstEvaluate twice in a row?
# Probably not... therefore, for modularity, it makes sense to add a wrapper function, whose only purpose is
# to tokenize, then call firstEvaluate() then call secondEvaluate()
expectedAnswer = eval(line)
if abs(actualAnswer - expectedAnswer) < 1e-8:
print("PASS! (%s = %f)" % (line, expectedAnswer))
else:
print("FAIL! (%s should be %f but was %f)" %
(line, expectedAnswer, actualAnswer))
# Add more tests to this function :)
def runTest():
print("==== Test started! ====")
test("")
test("1")
test("1+2")
test("12+3")
test("1.0+2")
test("1-3")
test("2.0-13")
test("3-14+4.0")
test("2*3")
test("4.2*9")
test("2*2*2")
test("3*5.9+2")
test("6.0-4*2")
test("8/9")
test("6/3.0/4")
test("2*3*4/5")
test("2*4.0/2.1+2.5*14")
test("4*5-7.0/3+2")
test("3+2+4.0*4-4/2.0")
# ALEXNOTE: how about invalid punctuation (++ or **) ?
# also, how about fractional numbers without a leading zero - such as .25 (are these accepted?)
test(".35+3.0")
test("9.0*.57+3/2")
test("4+3-.95/2*1.0")
test("3+2+ 4.0*4- 4/2.0")
test("++2-3")
#test("3//2*3")
#test("3/0")
print("==== Test finished! ====\n")
runTest()
while True:
print('> ', end="")
line = input()
tokens = tokenize(line)
# ALEXNOTE: did you mean to call tokenToNumber() below?
new_tokens = firstEvaluate(tokens)
answer = secondEvaluate(new_tokens)
print("answer = %f\n" % answer)
|
213b6e4ba9a40491931459853aa1f164433fce16 | MiyabiTane/myLeetCode_ | /Top_Interview_Questions/Strings/Valid_Palindrome.py | 631 | 3.703125 | 4 | class Solution(object):
def isPalindrome(self, s):
s = s.replace(' ', '')
s = s.lower()
# print(s)
left = 0
right = len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
# print(s[left], s[right])
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
s = "A man, a plan, a canal: Panama"
sol = Solution()
ans = sol.isPalindrome(s)
print(ans)
|
bec7538fee7edf7ec4eafbb53da65bca1f9c26f9 | MiyabiTane/myLeetCode_ | /58_Length_of_Last_Word.py | 240 | 3.578125 | 4 | def lengthOfLastWord(s):
ans=""
flag=0
for i in range(len(s)-1,-1,-1):
if s[i]==' ' and flag==1:
break
elif s[i]!=' ':
flag=1
ans+=s[i]
#print(ans)
return len(ans)
|
a81ea8abfcd9a5074f9336ecaf4e7e64ae0fa199 | MiyabiTane/myLeetCode_ | /169_Majority_Element_2.py | 203 | 3.671875 | 4 | def majorityElement(nums):
count=0
for num in nums:
if count==0:
candidate=num
count+=1 if num==candidate else -1
#print(candidate,count)
return candidate
|
2696213a2b83cb912d542f51bb4e5b3c7473edfe | MiyabiTane/myLeetCode_ | /30-Day_Challenge/29_Binary_Tree_Maximum_Path_Sum.py | 754 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxPathSum(self, root):
self.current_max = float("-inf")
def maxPathSumHelper(root):
if not root:
return 0
left = maxPathSumHelper(root.left)
right = maxPathSumHelper(root.right)
if left <= 0:
left = 0
if right <= 0:
right = 0
self.current_max = max(left+right+root.val, self.current_max)
return max(left, right) + root.val
maxPathSumHelper(root)
return self.current_max
|
4a18e8ee00d2959faa92b8a12d432debc9fff84f | MiyabiTane/myLeetCode_ | /30-Day_Challenge/15_Product_of_Array_Except_Self.py | 516 | 3.71875 | 4 | def productExceptSelf(nums):
left_product = [1]*len(nums)
right_product = [1]*len(nums)
for i in range(1,len(nums)):
pro = left_product[i-1]*nums[i-1]
left_product[i] = pro
#print(left_product)
for i in range(len(nums)-2,-1,-1):
pro = right_product[i+1]*nums[i+1]
right_product[i] = pro
#print(right_product)
for i in range(len(nums)):
left_product[i] *= right_product[i]
return left_product
ans = productExceptSelf([1, 2, 3, 4])
print(ans)
|
1e9dc1903c6ba31cc198eac3b8439975ae5b5f3a | MiyabiTane/myLeetCode_ | /May_LeetCoding_Challenge/6_Majority_Element.py | 204 | 3.65625 | 4 | import collections
def majorityElement(nums):
dict = collections.Counter(nums)
ans = [k for k, v in dict.items() if v > len(nums)//2][0]
return ans
ans = majorityElement([3,2,3])
print(ans)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.