blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
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 f... |
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... |
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:... |
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 b... |
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))
cl... |
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)
pri... |
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 the... |
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_... |
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 ... |
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
... |
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 an... |
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_... |
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.ze... |
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 ... |
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.searc... |
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 i... |
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):
d... |
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("Divi... |
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... |
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... |
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... |
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):
... |
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 = flo... |
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 pre... |
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 jarda... |
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_... |
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... |
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
... |
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 ... |
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.1... |
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 quad... |
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íve... |
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 ... |
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:
... |
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), ... |
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: ")... |
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 ... |
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 ... |
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: "))
... |
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... |
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 Pa... |
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:
... |
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 ... |
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 ... |
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):
polindro... |
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... |
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 escrit... |
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.questao1... |
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 ... |
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: ")... |
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
prin... |
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 n... |
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
lis... |
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(... |
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 te... |
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 dig... |
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(inp... |
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 it... |
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
... |
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(-1... |
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 us... |
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):
... |
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 contai... |
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... |
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))
... |
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
... |
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
... |
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
de... |
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)... |
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 remov... |
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:
... |
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... |
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... |
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[s... |
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+=... |
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 #もし*が(だったら
lo... |
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:
... |
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]) *... |
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 no... |
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):
... |
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]
righ... |
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.