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 |
|---|---|---|---|---|---|---|
e5a741e738040de2e2b62dd7515e2ae5afa31440 | lucas-cavalcanti-ads/projetos-fiap | /1ANO/PYTHON/ListaExercicios/Lista02/Ex03.py | 808 | 4.15625 | 4 | teclado = input("Digite o primeiro numero: ")
num1 = int(teclado)
teclado = input("Digite o segundo numero: ")
num2 = int(teclado)
soma = num1 + num2
somar = str(soma)
subtracao = num1 - num2
subtracaor = str(subtracao)
multiplicacao = num1 * num2
multiplicacaor = str(multiplicacao)
divisao = num1 / num2
divisaor = st... |
818d2ff7650a21dd1d3eca826e0c9862e448e007 | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-1/desafio-009.py | 1,304 | 3.640625 | 4 | cores = {'limpo': '\033[m',
'ciano': '\033[1;36m',
'roxo': '\033[1;35m',
'azul': '\033[1;34m'}
n = int(input('Coloque um número para ver sua tabuada: '))
n1 = n * 1
n2 = n * 2
n3 = n * 3
n4 = n * 4
n5 = n * 5
n6 = n * 6
n7 = n * 7
n8 = n * 8
n9 = n * 9
n10 = n * 10
print(f'{cores["azul"]}====... |
4ccbdf4786b3193c3184f8738b5da13112ee2856 | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-2/desafio-041.py | 393 | 3.953125 | 4 | import datetime
ano = int(input('Que ano o atleta nasceu?: '))
idade = datetime.date.today().year - ano
print(f'Quem nasceu em {ano} tem {idade} anos')
if 0 < idade <= 9:
print('Atleta MIRIM')
elif 9 < idade <= 14:
print('Atleta INFANTIL')
elif 14 < idade <= 19:
print('Atleta JUNIOR')
elif 19 < idade <= 25:... |
146df0a1eabd265184c94297aedd218347f754ce | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-2/desafio-056.py | 783 | 3.5625 | 4 | médiaidade = 0
maioridadehomem = 0
nomevelho = ''
mulheresmaisnovas = 0
for p in range(1, 5):
print(f'{"=" * 9}{p}ª Pessoa{"=" * 9}')
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [H/M]: ')).strip().upper()
médiaidade += idade
if p == 1 and sexo == 'H':... |
75578330aed370156506f96dbd89fce55a72287b | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-3/desafio-093.py | 1,000 | 3.84375 | 4 | # Declarando as variáveis.
jogador = dict()
gols = list()
# Adicionando os valores ao dicionário "jogador".
jogador['nome'] = str(input('Nome do jogador: ')).strip().title()
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou?: '))
# Pegando os gols de cada partida utilizando o FOR.
for g in range(0, parti... |
578d0f26d1f90ca422737d6201e56fe3de3d8adc | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-3/desafio-084.py | 1,027 | 3.765625 | 4 | dados = list()
pessoas = list()
maiornome = list()
menornome = list()
cont = maior = menor = -1
while True:
dados.append(str(input('Nome: ')).strip())
dados.append(float(input('Peso: ')))
if len(pessoas) == 0:
maior = menor = dados[1]
else:
if dados[1] > maior:
maior = dados[... |
34158e8e5e3089846814464a58d30a99a9963e5c | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-2/desafio-036.py | 559 | 4 | 4 | valordacasa = float(input('Qual é o valor da casa?: R$'))
salário = float(input('Qual o seu salário?: R$'))
anos = int(input('Por quantos anos você vai pagar a casa?: '))
print(f'Para pagar uma casa de R${valordacasa :.2f} em {anos} anos, a prestação mensal será de R${valordacasa / anos / 12 :.2f}')
if valordacasa / an... |
910adfeb6b500f702e90a782fbedb43fceaf939b | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-2/desafio-044.py | 1,037 | 3.875 | 4 | preço = float(input('Qual o preço do produto ou das compras?: '))
print('Escolha a forma de pagamento:')
print('''1- À vista com dinheiro/cheque (10% de desconto)
2- À vista no cartão (5% de desconto)
3- 2x no cartão (preço normal)
4- 3x ou mais no cartão (20% de juros)''')
escolha = int(input('Qual forma de pagamento ... |
382926b8adb929eb319e68152c815c25b60c1c88 | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-3/desafio-097.py | 380 | 3.703125 | 4 | # Criando uma função que digita uma mensagem no meio de duas linhas.
def escreva(msg):
# Fazendo com que a linha tenha um tamanho que se adapta a mensagem.
print('~' * (len(msg)+4))
print(f' {msg}')
print('~' * (len(msg)+4))
# Programa pricipal - Usando a função "escreva" na prática.
escreva('Gustavo... |
0bb3bd040ef8d9316111b4f82a9416b13e81ac75 | LeonardoARGR/Desafios-Python-Curso-em-Video | /Mundo-1/desafio-007.py | 357 | 3.609375 | 4 | cores = {'limpo': '\033[m',
'verde': '\033[1;32m',
'vermelho': '\033[1;31m'}
n1 = float(input('Primeira Nota: '))
n2 = float(input('Segunda Nota: '))
m = (n1+n2) / 2
if m < 5:
print('A sua nota foi {}{}{}'.format(cores['vermelho'], m, cores['limpo']))
else:
print('A sua nota foi {}{}{}'.format... |
cb47ef51e8c71a29c9f0d1345210b2242382be50 | naodell/Project-Euler | /Page 1/problem_34.py | 484 | 3.71875 | 4 | '''
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of
their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
'''
import math
number = 11
answer = 0
while(number < 2.6e6):
digits = str(number)
digitS... |
baec9cad1d5d24f74935ccd2d537b33c11ca7093 | naodell/Project-Euler | /Page 1/problem_38.py | 1,128 | 4.03125 | 4 | '''
Take the number 192 and multiply it by each of 1, 2, and 3:
192 x 1 = 192, 192 x 2 = 384, 192 x 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576. We will
call 192384576 the concatenated product of 192 and (1,2,3).
The same can be achieved by starting with 9 and multiplying by 1, 2, ... |
ec7dc5024c1fd2c5fd017120e3b8ceb45b0fe2c8 | naodell/Project-Euler | /Page 1/problem_44.py | 957 | 3.703125 | 4 | '''
Pentagonal numbers are generated by the formula, P_n=n(3n-1)/2. The first ten
pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their difference,
70 - 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P_j and P_k, for w... |
a050956731ea15251b18a627eb6be527430f8032 | naodell/Project-Euler | /Page 1/problem_16.py | 268 | 3.75 | 4 | '''
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
'''
bigNumber = pow(2, 1000)
bigString = str(bigNumber)
powSum = 0
for number in bigString:
powSum += int(number)
print bigNumber, powSum
|
5f9b05e919c0dda6fb13f10c86b418a135adf623 | naodell/Project-Euler | /Page 1/problem_22.py | 984 | 3.875 | 4 | '''
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.
For example... |
40a915b242ccf97509ff90279b0ec32af81946b6 | PierpaoloLucarelli/IR_door_alarm | /activity_monitor/MonitorFSM.py | 3,340 | 3.515625 | 4 | '''
Author : Pierpaolo Lucarelli
MonitorFSM class taht extends the FSM class.
this class ir sesponsible for handling the I/O of the machine
Give a certain type of input and the correct type of output will be send
'''
from FSM import *
class MonitorFSM(FSM):
startState = 'deactivated'
codeState = 0 #state of... |
86aeb48adfad7762a2ac64e0fe85f50ee7af91b7 | noahklein/daily-coding-problem | /088.py | 428 | 4.09375 | 4 | """
Implement division of two positive integers without using the division,
multiplication, or modulus operators. Return the quotient as an integer,
ignoring the remainder.
"""
def divides(a, b):
if b == 0:
raise ArithmeticError()
if a < b:
return 0
return 1 + divides(a - b, b)
assert(d... |
5427437c4317a369825b00c755eb1a2b81ae4de5 | 3leonora/fourier-lab | /exercise1.py | 1,622 | 3.59375 | 4 | '''
Exercise 1
Fouriertransform of function with a period of 2pi
Dependencies: numpy, matplotlib
Authors:
@Eleonora Svanberg
@Henrik Jörnling
'''
#hej
#Modules
import numpy as np
import matplotlib.pyplot as plt
def xarray(N: int) -> np.ndarray:
'''Array with x values'''
return np.linspace(0., 2.*np.pi, N, e... |
56580b82fb7ecef03712dfecdb2f1e72d0442cff | KraProgrammer/AdventOfCode2020 | /src/day23.py | 3,892 | 3.515625 | 4 | from aocd.models import Puzzle
class Node:
def __init__(self, data, prev_node, next_node):
self.data = data
self.prev_node = prev_node
self.next_node = next_node
class LinkedList:
def __init__(self):
self.index = {}
def append(self, prev, data) -> Node:
if prev i... |
529a0ae383f5e1650a35935e51e289f13dd8d1e5 | KraProgrammer/AdventOfCode2020 | /src/day21.py | 2,197 | 3.5 | 4 | from collections import defaultdict
from aocd.models import Puzzle
def solve_puzzle_one(input_array):
counter, ingredients, allergens, possible_allergens = get_data(input_array)
c = 0
for i in ingredients:
if not possible_allergens[i]:
c += counter[i]
print(c)
def get_data(inpu... |
7f2f690fa1b67d1c43566771e783c08d2eb57588 | jamathis77/Python-fundamentals | /conditionals.py | 2,444 | 4.28125 | 4 | # A conditional resolves to a boolean statement ( True or False)
left = True
right = False
# Equality Operators
left != right # left and right are not equivalent
left == right # left and right are equivalent
left is right # left and right are same identity
left is not right # Left and right are not same identit... |
ce124a17f9b0f62b3a8f2f457f28a0fdf6c0babb | evargas1/Algorthims | /Non_repeat_elements.py | 1,653 | 3.609375 | 4 | """
Linear time solution
Non repeat element
Take a string and return characters that never repeats if mutiple unique
then only return only the first
unique character
This algo is really helpful in
cyber sercuity!
"""
def non_repeating(s):
s = s.replace(' ', '').lower()
char_count = {}
# answer =... |
edf5f02ad075fcac802302e8f71bc62746d6d051 | jacob-brown/programming-notes-book | /programming_notes/_build/jupyter_execute/python_basic.py | 4,747 | 4.46875 | 4 | # Python: Basics
## Lists
Methods:
* `append()`
* `clear()`
* `copy()`
* `count()`
* `extend()`
* `index()`
* `insert()`
* `pop()`
* `remove()`
* `reverse()`
* `sort()`
demoList = ["apple", "banana", "orange", "kiwi"]
print(demoList)
Adding/Removing items
demoList.append('cherry')
print(demoList)
demoList.inse... |
6726f3ca4feff9c2fcf5d368be13470b2cc8d73f | makowiecka/Hangman | /door.py | 1,332 | 3.65625 | 4 | class DoorError(RuntimeError): #nowy błąd na podstawie istniejącego, doorerror dziedziczy po Runtimeerror i przyjmuje wszystkie jego własciwości
pass
class Door: # w klasach tworzymy w liczbach pojedyńczych
def __init__(self, name: str):
self.__name = name # ja wstawimy __ - nie mamy dostępu z zewnątrz... |
b2a57d3dfb42d63aaeda6039e0b957661872528c | makowiecka/Hangman | /words_from_file/words.py | 2,434 | 3.65625 | 4 | import os
from random import randint
from abstract_word import AbstractWord
class WordsFromFile(AbstractWord):
@staticmethod #nie będzie działała na żadnych własnosciach danego obiektu
def get_path(): #ścieżka
return os.path.abspath(os.path.dirname(__file__)) #biblioteka os, moduł - path, funkcja d... |
6d031a90814976c539f22823bffd72222b4625c9 | JianfengYao/C-practice | /algorithm/algorithm-python/src/number_theory/gcd.py | 274 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8
def gcd(a, b):
divisor = a
dividend = b
while dividend is not 0:
divisor, dividend = dividend, divisor % dividend
return divisor
def main():
print(gcd(12, 18))
if __name__ == "__main__":
main()
|
bb6a42640770f39615f60d5b368ace2836d2e545 | JianfengYao/C-practice | /algorithm/algorithm-python/src/lib/stack.py | 828 | 4 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8
import copy
class Stack(object):
"""
使用Python快速实现一个栈
"""
def __init__(self, *arg):
super(Stack, self).__init__()
self.__stack = list(copy.copy(arg))
self.__size = len(self.__stack)
def push(self, value):
self.__stack.appe... |
7c2fde5d7a2da2544cf8ee68fe6ed77177fbacfc | sjogleka/Intelligent_Systems | /IS_Project2/code.py | 15,712 | 3.8125 | 4 | from random import randrange
from copy import deepcopy
from random import choice
# A class to create queenstate and identify the best possible children based on number of queens attacking
class QueensState:
instance_counter = 0
def __init__(self, queen_positions=None, parent=None,f_cost=0,):
... |
4e5d2fddbb38e7f243c2302203c692e238740ee5 | xudaniel11/interview_preparation | /robot_unique_paths.py | 1,808 | 4.21875 | 4 | """
A robot is located at the top-left corner of an M X N grid. The robot can only move either down or
right at any point in time. The robot is trying to reach the bottom-right corner of the grid.
How many possible unique paths are there?
Input: M, N representing the number of rows and cols, respectively
Output: an in... |
b72c2595f1863a8a3a681657428dd4d6caceefb2 | xudaniel11/interview_preparation | /calculate_BT_height.py | 1,621 | 4.15625 | 4 | """
Calculate height of a binary tree.
"""
import unittest
def calculate_height(node):
if node == None:
return 0
left, right = 1, 1
if node.left:
left = 1 + calculate_height(node.left)
if node.right:
right = 1 + calculate_height(node.right)
return max(left, right)
class... |
3c419ab15020a8827a24044dfa180da9a7a5c47f | xudaniel11/interview_preparation | /array_of_array_products.py | 1,044 | 4.15625 | 4 | """
Given an array of integers arr, write a function that returns another array at the same length where the value at each index i is the product of all array values except arr[i].
Solve without using division and analyze the runtime and space complexity
Example: given the array [2, 7, 3, 4]
your function would retur... |
481fb0533a3f52fb1a2093472bbf07bcf8f1da0e | xudaniel11/interview_preparation | /city_destinations.py | 2,047 | 4.09375 | 4 | """
Given an input city, return the cities that can be reached.
Algorithm: iterate through the initial list in order to create the adjacency matrix.
Then, use DFS to figure out what cities can be connected to from the input one.
"""
import unittest
def city_destinations(cities, original_city):
# build adjacency li... |
be3e45acb992ac1db59427d3b411bdc2c8a3d84a | xudaniel11/interview_preparation | /Queue.py | 337 | 3.71875 | 4 | """
Queue DS
"""
class Queue():
def __init__(self):
self.q = []
def enqueue(self, item):
self.q.append(item)
def dequeue(self):
return self.q.pop(0)
def is_empty(self):
return len(self.q) == 0
def size(self):
return len(self.q)
def front(eslf):
... |
f26285e201db5aca5cf026b2e3377539ee23d1ab | xudaniel11/interview_preparation | /remove_duplicates_LL.py | 1,403 | 3.875 | 4 | """
Remove duplicates from an unsorted linked list in O(1) space.
"""
import Singly_LL as LL
import unittest
def remove_duplicates(ll):
if ll.get_size() == 0 or ll.get_size == 1:
return ll
prev = ll.head
curr = ll.head.next
while curr:
runner = ll.head
while runner != curr:
... |
8268e7d5e29f7ccb1616fa17c022ad060256c569 | xudaniel11/interview_preparation | /check_balanced_tree.py | 1,516 | 4.4375 | 4 | """
Implement a function to check if a tree is balanced. For the purposes of this question,
a balanced tree is defined to be a tree such that no two leaf nodes differ in distance
from the root by more than one.
Solution taken from CTCI: recursive algorithms calculate the maximum and minimum length
paths in the tree. C... |
5b460faff9b8266878e666793101b3ac11e9cc87 | xudaniel11/interview_preparation | /all_possible_subsets.py | 1,072 | 4.03125 | 4 | """
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Also, the subsets should be sorted in ascending ( lexicographic ) order.
The list is not necessarily sorted.
Example :
If S = [1,2,3],... |
6bfa59c214fd9b3794027905132da251f3775af6 | xudaniel11/interview_preparation | /stairs.py | 448 | 3.9375 | 4 | """
There are n stairs, a person standing at the bottom wants to reach the top.
The person can climb either 1, 2, or 3 stairs at a time. Count the number
of ways, the person can reach the top.
Base cases handle illegal cases.
"""
def stairs(n):
if n == 0:
return 1
elif n < 0:
return 0
els... |
0b95a6a31595b540c25dbb81cad8b99acd3af537 | xudaniel11/interview_preparation | /binaryMatrixCloseness_INCORRECT.py | 2,902 | 3.578125 | 4 | """
@author - Daniel Xu
Given a matrix M of number 1 and 0, for each cell in the matrix determine how far
the closest 1 is to the current cell. If the 1 is the current cell, then the distance is 0
because there is no "distance". If the 1 is next to the cell, the distance is 1.
Only consider cardinal directions (up, d... |
f35842ab5a7e78d864e28944a262c49f06bfde31 | BeatrizVasconcelos/Trabalho-Banco-de-Dados | /aux.py | 14,799 | 3.609375 | 4 | from getpass import getpass
from cripto import crip
# função que realiza login
def login(db):
while(True):
# lê email do usuário
print('Digite seu e-mail:')
email = input()
# executa query para buscar email digitado
q = "SELECT * FROM usuario WHERE email='{}';".format(emai... |
6c26473dd26a547e51266f8b0d54f6c9df060b36 | MatthewDobsonOnGitHub/Miscellaneous | /python_scripts/test_python_script.py | 1,962 | 3.5 | 4 | #!/usr/bin/env python
#
#
# Load in the necessary libraries; importing them as smaller strings for brevity.
import numpy as np
import matplotlib.pyplot as plt
import math
import pylab
# Now, we load in the transient data.
# Enter data file name inside brackets.
# This will store the data from the file as an array ca... |
c6852a0f14a112645380329be291055f21736919 | MatthewDobsonOnGitHub/Miscellaneous | /python_scripts/clipping_function.py | 2,388 | 3.65625 | 4 |
def clipping_function(input_dictionary, output_dictionary):
output_dictionary = {}
# We loop through all the days of measurements, and loop through all the measurements taken on each day (nested loops).
for key, value in input_dictionary.items():
# Define the number of points per day in the initial, unclippe... |
30ca063384563a9b904f680295e18ed3061593b5 | rodrigoctoledo/UnipPandemia | /Pademia1.py | 10,035 | 3.9375 | 4 | '''
Rodrigo de Camargo Toledo D26EB3-6 CCP13
Algoritmo Pandemia
Desenvolvedor: Rodrigo Toledo
Baseado no Enunciado do Professor Dirceu,
As Vezes é necessario interagir com o programa, apertando Enter para obter resultados ou inserindo informações
Após apertar, o enter, pode demorar um pouco, pois coloquei o elemento ... |
6d1b7c713ca3d76f905109aa6770b67d3b2da4a3 | Roooommmmelllll/Python-Codes | /randomNumList.py | 1,029 | 3.984375 | 4 | import random
def makeList():
numList = []
for i in range(50):
numList.append(random.randint(0,100))
return numList
def stats(numList):
total = 0
minimum = 100
maximum = 0
for i in range(50):
total+=numList[i]
if (numList[i] < minimum):
minimum = numList[i]
if (nu... |
d9aeb4ebe92db4d93fabc3c2362a1889605f1c35 | Roooommmmelllll/Python-Codes | /string_slicing.py | 176 | 3.78125 | 4 | #string slicing
def strSlice():
name = "Abraham Lincoln"
print (name)
#print (name[0])
#print (name[6:11])
#print (name[2::2])
print (name[-1::-1])
strSlice()
|
67f02f80af5d677d4752503c9947c994be1ad901 | Roooommmmelllll/Python-Codes | /conversion_table.py | 453 | 4.1875 | 4 | #print a conversion table from kilograms to pounds
#print every odd number from 1 - 199 in kilograms
#and convert. Kilograms to the left and pounds to the right
def conversionTable():
print("Kilograms Pounds")
#2.2 pound = 1kilograms
kilograms = 1
kilograms = float(kilograms)
while kilograms <= ... |
648905f5d1d15cccd1a9356204ad69db0f30ce31 | Roooommmmelllll/Python-Codes | /rightTriangleTest.py | 970 | 4.21875 | 4 | def getSides():
print("Please enter the three sides for a triagnle.\n" +
"Program will determine if it is a right triangle.")
sideA = int(input("Side A: "))
sideB = int(input("Side B: "))
sideC = int(input("Side C: "))
return sideA, sideB, sideC
def checkRight(sideA, sideB, sideC):
if sideA ... |
996e8730e24a1d8f763ea3f2f2fd1b7eebcfcd03 | Roooommmmelllll/Python-Codes | /Brute_Force.py | 1,814 | 3.625 | 4 | import itertools
import hashlib
def main():
#Original Data
name = "Jane Doe Smith"
bd = "02/13/1981"
ssn = "567-33-2013"
pn = "831.228.5671"
petName = "Kujo Friendly"
win7Pass = "ae2e1fa899105c28184c0d0d11be8241"
print("The Original Data")
print(name,"\n",bd,"\n",ssn,"\n",pn,"\n",petName,"\... |
cc19bcc1c8da5e3ab76d70a2c460820ddbc7e1ea | Roooommmmelllll/Python-Codes | /4 Points Distance CHecker.py | 1,225 | 4 | 4 | def woot():
print("Program will determine the " +
"fastest route between four " +
"points of travel.")
print("Assume that point A is already plotted")
pointsNum = 0
while pointsNum < 6:
pointsNum+=1
if pointsNum == 1:
pointAB = int(input("Please input the distance" +
... |
3d12d105de0090fc2711f13e08ad7172732402b9 | Roooommmmelllll/Python-Codes | /class_ifs.py | 2,183 | 3.953125 | 4 | def divide():
topnum = int(input("Please input a number for the numerator: "))
botnum = int(input("Please input a number for the denominator: "))
if(botnum == 0):
print("You cannot divide with zero!!")
answer = "undefined"
return
answer = topnum/botnum
print("The an... |
273d7533f1f2de41e71eb77e9d291101f461bb5f | Roooommmmelllll/Python-Codes | /bus_seats.py | 247 | 3.96875 | 4 | def rentbus():
people = int(input("How many people are going?: "))
extra = people - 34
if extra >= 0:
print(extra, "people need to drive.")
else:
extra *= -1
print("There are", extra, "spaces empty on the bus.")
|
d28babacc9ada1b6bd9b74f941fe6b6b6d0131cc | Roooommmmelllll/Python-Codes | /highscores.py | 774 | 4 | 4 | def highscore():
loop = True
while loop == True:
students = input("How many students are in the class?: ")
if students.isdigit() == True:
break
chr(2)
ord(a)
highscore1 = 0
highscore2 = 0
for i in range(0, students):
while loop == True:
newScore ... |
fb44a10c97370bd7f1c1214260c1469b1c2f91b9 | Roooommmmelllll/Python-Codes | /MathCAI.py | 7,608 | 4.28125 | 4 | # Computer Assisted Instruction. Practice Arithmetic.
# At least 6 functions.
# Use echo printing where apporpriate (printing with variables)
# Extensions
# F) Extend your program so that it has differnt grade levels.
# For example, the program will only give problems with numbers at the level.
# Grade 1 - Numbers 1 ... |
722687225a39c563b955c4a56c8270b3aaea647c | Roooommmmelllll/Python-Codes | /printSlow.py | 322 | 3.828125 | 4 | import time
def printSlow():
print("Please input a speed to print at")
print("0.5 is pretty fast, while 5 is very very slow.")
printSpeed = float(input())
newString = input("Input a long string: ")
for i in range(len(newString)):
print(newString[i], end="")
time.sleep(printSpeed)
printSlow(... |
5ba3a2d27ec8f58f97c54cc837c81f210362508a | Roooommmmelllll/Python-Codes | /largerNumber.py | 241 | 4.125 | 4 |
def largeNumbers():
value = 0
for i in range(7):
user = int(input("Please input seven numbers: "))
if user > value:
value = user
print("The largest number you entered was: " + str(value) + ".")
largeNumbers()
|
109899d74d6d0c48afe0052224a64a258ea793e3 | nishhub/EasyLevelPythonPrograms | /Sorting/Bubble Sort.py | 346 | 3.890625 | 4 | def bubble_sort(a_list):
swap = True
for i in range(len(a_list)-1, 0, -1):
for j in range(0, i):
if a_list[j] > a_list[j+1]:
a_list[j], a_list[j+1] = a_list[j+1], a_list[j]
swap = False
if swap:
return
a_list = [4, 2, 38, 10, 5]
bubble_... |
8af20acbd18a8e179396fff27dedfa4cddda7d3c | mayer-qian/Python_Crash_Course | /chapter4/numbers.py | 1,092 | 4.34375 | 4 | #使用函数range生成数字,从1开始到5结束,不包含5
for value in range(1, 5):
print(value)
print("=======================================")
#用range创建数字列表
numbers = list(range(1, 6))
print(numbers)
print("=======================================")
#定义步长
even_numbers = list(range(2, 11, 2))
print(even_numbers)
print("================... |
c8d52dbd74315b07d658790c57a73802414fdba2 | badre-Idrissi/tpPython | /application2.py | 244 | 3.6875 | 4 | nom = input("sasissez le nom : \n")
genre_val=input("saisir le genre :\n")
#genre= ("Monsieur" if genre_val=="1" else "Madame")
genre=("Monsieur", "Madame")[genre_val=="0"]
msg= "Bonjour {} {}"
print("Bonjour {} {}".format(genre,nom))
|
0c3b01eeef287780b3c0cc135e5a4fe06f640778 | christinalow/compsci-class | /projects/semester 1/#2-11-16-2017.py | 376 | 3.5 | 4 | import math
#a = p(1+(r/n))**nt
p = float(input("What is the amount you saved up?"))
r = (int(input("What is your current savings rate in percent?"))/100)
n = int(input("How often does your investment compound per year?"))
a = 2*p
x = (1 + (r/n))
y = a/p
#y will always be 2
t = ((math.log10(y))/ (n*(math.log10(x))))
p... |
da90287810410dc0e41db8a5b93f63f99214496e | christinalow/compsci-class | /practice/2017-12-18.py | 499 | 3.921875 | 4 | sum=0
for i in range(1000):
if i%4==0 or i%7==0:
sum= sum + i
print("The sum of all the multiples of 4 and 7 below 1000 is " + str(sum) +".")
#checks to if user input is a prime number:
import math
num = int(input("Enter an integer: "))
mid = int(math.sqrt(num))+1
count=0
for x in range(2,mid):
if num%x==0:
... |
7d4ef9a2f61bbab56b14b9c3b26cc300e2fa6f1f | lxndrvn/python-lightweight-erp-3rd-tw-overload | /common.py | 917 | 3.8125 | 4 | # implement commonly used functions here
import random
# generate and return a unique and random string
# other expectation:
# - at least 2 special char()expect: ';'), 2 number, 2 l and 2 u case letter
# - it must be unique in the list
#
# @table: list of list
# @generated: string - generated random string (unique i... |
27a145eb25b3a446ef753448253916a71a4c44a9 | WarriorsWCH/python-lesson | /字典/dict.py | 699 | 4 | 4 | info = {'name':'li', 'id':100, 'sex':'f', 'address':'english'}
# 修改元素
info['id'] = 50
print(info)
# 添加新的元素
info['age'] = 23
print(info)
# del删除指定的元素
del info['sex']
print(info)
# clear清空整个字典
info.clear()
print(info)
info = {'name':'li', 'id':100, 'sex':'f', 'address':'english'}
# 键值对的个数
print(len(info))
# 返回一个包含... |
5ffbd62fd3238c5c2bdddf9b3f24ffdc7262bf01 | dmyerscough/demo | /test_main.py | 407 | 3.53125 | 4 | #!/usr/bin/env python
import unittest
from main import fib
class TestFib(unittest.TestCase):
def test_fib(self):
"""
Test fibonacci
"""
fibonacci = []
s = fib()
for _ in range(0, 11):
fibonacci.append(next(s))
self.assertEqual(fibonacci, [0... |
9acef6fa13ba60dd674dfea65c1674d4dd939c94 | thammaneni/Python | /Practice/TimedeltaExcercise.py | 324 | 3.84375 | 4 | from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
now = datetime.now()
print ("Today is "+ str(now))
print ("Time after 365 days :"+str(now + timedelta(days=365)))
print ("Date after 6 weeks, 4 days,20hours : ", str(now + timedelta(weeks=6,days=4,hours=2... |
79a6d94edab18821979a117ba4c226544aef0882 | thammaneni/Python | /Practice/DateTimeFormat.py | 443 | 4.0625 | 4 | from datetime import datetime
t = datetime.now()
print (t.strftime("The current year is : %Y"))
print (t.strftime("The current date is : %d"))
print (t.strftime("The current month is : %B"))
print (t.strftime("The current weekday is : %A"))
print (t.strftime("The Local Date and Time is : %c"))
print (t.strftime("The ... |
b81b5ccc53216e4485737df5a37121c85939eb33 | thammaneni/Python | /PythonPracticeEx/EvenListCreationSingleSTMT.py | 450 | 3.859375 | 4 | # import random
# randomNumber = random.randint(0,5)
# print (randomNumber)
#=========================================================
list1 = [30,32,46,12,13,14,15,16,17,18,19,20]
subList = [ i for i in list1 if i % 2 == 0]
subList.sort()
print (subList)
#========================================================
# a =... |
c424feca5aea8d199dfc86454391ab6266123ea0 | KinPeter/Udemy-and-other-courses | /Python-mega-course-by-Ardit-Sulce/bokeh_visualization/basic_graph.py | 796 | 3.78125 | 4 | # making a basic bokeh line graph
from bokeh.plotting import figure
from bokeh.io import output_file, show
import pandas
# ---- from python lists
# prepare some data
x = [1,2,3,4,5]
y = [6,7,8,9,10] # need to be the same length
# prepare the output file
output_file('line.html')
# create a figure object
f1 = figure... |
a6a16620fe79273b2d803874fdfca403a58cac4a | KinPeter/Udemy-and-other-courses | /Python-mega-course-by-Ardit-Sulce/pandas_jupyter/supermarkets/import_read_and_slice_dataframes.py | 1,874 | 3.84375 | 4 | import os
os.listdir()
import pandas
# import csv file
df1 = pandas.read_csv("supermarkets.csv") # header = None : will not treat first row as header
print(df1.set_index("ID")) # will treat ID column as index but only for output, not saving it
print(df1.shape) # how many rows and colums we have?
# import json file
... |
9700cb032358926683c69bfd64b0f904d2f0f757 | KinPeter/Udemy-and-other-courses | /Python-by-in28minutes/02-OOP-project/book-reviews.py | 709 | 3.59375 | 4 | class Book:
def __init__(self, id, name, author):
self.id = id
self.name = name
self.author = author
self.review = []
def __repr__(self):
return repr((self.id, self.name, self.author, self.review))
def add_review(self, review):
self.review.append(review)
c... |
6ddcb742d401c9179a8d0c36be4c9729950f51bd | KinPeter/Udemy-and-other-courses | /Python-mega-course-by-Ardit-Sulce/bokeh_visualization/weather_data.py | 610 | 3.625 | 4 | import pandas
from bokeh.plotting import figure
from bokeh.io import output_file, show
p = figure(plot_width=800, plot_height=600, tools='pan')
df = pandas.read_excel('http://pythonhow.com/data/verlegenhuken.xlsx')
x = df['Temperature'] / 10
y = df['Pressure'] / 10
p.title.text='Temperature and Air Pressure'
p.title... |
d8d913f624f5afef56252ae6a768bc688241708d | anti401/python1 | /python1-lesson1/easy-3.py | 535 | 3.96875 | 4 | # coding : utf-8
# Задача-3: Запросите у пользователя его возраст.
# Если ему есть 18 лет, выведите: "Доступ разрешен",
# иначе "Извините, пользование данным ресурсом только с 18 лет"
age = int(input('Сколько вам лет? - '))
if age >= 18:
print('Доступ разрешен')
else:
print('Извините, пользование данным ресу... |
d9657338aa5ce5c4be2b5f189f5d6ea7b3bae1a6 | anti401/python1 | /python1-lesson1/easy-2.py | 555 | 4.21875 | 4 | # coding : utf-8
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
a = input('A = ')
b = input('B = ')
print('Вы ввели A = ' + str(a) + ' и B = ' + str(b))
# перестановка значений через временную переменную
t = a
a = b
b =... |
eb18ec7075c744764ea2d06be8bb29785f76f8da | anti401/python1 | /python1-lesson3/normal-4.py | 1,003 | 4.09375 | 4 | # coding : utf-8
# Задача-4:
# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).
# Определить, будут ли они вершинами параллелограмма.
def middle(A, B):
# середина отрезка
return (A[0] + B[0]) / 2, (A[1] + B[1]) / 2
def equals(A, B):
# совпадение точек
return A[0] == B[0] and A[1] ... |
84766bbb2176c3375eb0717a0566c46bdcbfff42 | anti401/python1 | /python1-lesson2/normal-1.py | 865 | 3.640625 | 4 | # coding : utf-8
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 2... |
9ec5a1b69aeddeef690353a6b10b1f7e8604fe23 | miseop25/CS_Basic | /Algorithm/Sorting/QuickSort.py | 1,014 | 3.96875 | 4 | class Sort :
def __init__(self, array):
self.array = array
def quickSort(self, st, ed) :
if st >= ed :
return
pivot = st
small = st + 1
big = ed
temp = 0
while small <= big :
while small <= ed and self.array[small] <= ... |
4ef007bae17e06e2f2f81f160d2d07e8e029375f | kahnadam/learningOOP | /Lesson_2_rename.py | 688 | 4.3125 | 4 | # rename files with Python
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank")
#find the current working directory
saved_path = os.getcwd()
print("Current Working Directory is "+saved_path)
#change directory to the one with t... |
43a152688669d42bbfe9472235b37505bd315265 | jlopez0591/python-automate | /strings/table_printer.py | 814 | 4 | 4 | #table_printer.py
#prints a table of lists with the same amount of elements
#Function to print the table
def printTable(tableData):
rowLength = 0
colWidths = [0] * len(tableData)
for i, column in enumerate(tableData):
if(rowLength<len(column)):
rowLength = len(column)
... |
ce4909318398deed3194ca364684bbb07305892f | MarcusVinix/Cursos | /curso-de-python/exemplos/enumerate.py | 411 | 4 | 4 | numeros = [30, 28, 43, 54, -1, -4, -6, -7, 8, 7, 9,]
print(numeros)
i = 0
for num in numeros:
print("FOR sem enumerate: [%d] --> %d" % (i, num))
#print("FOR sem enumerate: [", i, "] --> ", num)
i += 1
i = 0
while i < len(numeros):
print("While sem enumerate: [%d] --> [%d]" % (i, numeros[i]))
i += 1... |
291a113d8bcc954b18d084b0d6a64340d5c88958 | MarcusVinix/Cursos | /curso-de-python/modulos/modulo_type.py | 738 | 3.65625 | 4 | import types
def mostraTipo(dado):
tipo = type(dado)
if tipo == str:
return ("String")
elif tipo == int:
return ("inteiro")
elif tipo == list:
return ("Lista")
elif tipo == dict:
return ("Dicionario")
elif tipo == float:
return ("Numero decimal")
elif ... |
35b4f63c77d843ae5f23d2e1455fcc8cf2a184f6 | MarcusVinix/Cursos | /curso-de-python/exercicios/contagem_cedulas.py | 761 | 3.75 | 4 | valor = float(input("Digite o valor: "))
cedulas = 0
valorCedulaAtual = 100
valorASerEntregue = valor
while True:
if valorCedulaAtual <= valorASerEntregue:
cedulas += 1
valorASerEntregue -=valorCedulaAtual
else:
if cedulas > 0:
print("%d cedula(s) de R$ %5.2f" % (cedulas, val... |
727df69164898002020bade490e3ac13d9b4c4b0 | MarcusVinix/Cursos | /curso-de-python/funcoes_def/criando_funcoes_fatorial.py | 485 | 4.0625 | 4 | #fatorial de 3: 3 * 2 * 1 = 6
#fatorial de 4: 4 * 3 * 2 * 1 = 24
#fatorial de 5: 5 * 4 * 3 * 2 * 1 = 120
def fatorial(numero):
f = 1
while numero > 1:
f *= numero
numero -= 1
return f
print(fatorial(3))
print(fatorial(4))
print(fatorial(5))
print(fatorial(6))
def fatorial1(numero):
f ... |
073248546d1afb1cd215ae07e8c69a3f5c5c9373 | MarcusVinix/Cursos | /curso-de-python/exemplos/string_len.py | 130 | 3.59375 | 4 | nome = "Marcus Vinicius"
print("Nome: ", nome)
print("Tamanho: ", len(nome))
tamanho = len(nome)
print("Tamanho: ", tamanho)
print(nome[5]) |
596f04b0adf35ebf8679d29bcab401868eb5eecb | MarcusVinix/Cursos | /curso-de-python/funcoes_def/criando_funcoes_pesquisa.py | 829 | 3.6875 | 4 | def pesquisar(lista, codigo):
for i, codigos in enumerate(lista):
if codigos == codigo:
return ("Codigo %d encontrado no indice %d" % (codigo, i))
return ("O codigo %d não foi localizado" % codigo)
listaProdutos = [4, 8, 2, 67, 5, 12]
print(pesquisar(listaProdutos, 8))
print(pesquisar(listaP... |
966c55fb0d234a61e5b66999b41be525a979d8c9 | MarcusVinix/Cursos | /curso-de-python/funcoes_def/criando_as_proprias_funcoes.py | 1,062 | 4.34375 | 4 | print("Sem usar funções, a soma é: ", (5+6))
def soma(num1, num2):
print("Usando funções (DEF), a soma é: ", (num1+num2))
def subtracao(num1, num2):
print("Usando funções (DEF), a subtração é: ", (num1 - num2))
def divisao(num1, num2):
print("Usando funções (DEF), a divisão é: ", (num1 / num2))
def mult... |
22472b8911a31661edf487d34bcee15711c747de | MarcusVinix/Cursos | /curso-de-python/classes/classes_conta_banco.py | 700 | 3.703125 | 4 | class ContaBanco:
def __init__(self, cliente, numeroConta, saldo=0):
self.saldo = saldo
self.cliente = cliente
self.numeroConta = numeroConta
def deposito(self, valor):
self.saldo += valor
print("Foi depositado R$%d em sua conta" % valor)
def saque(self, valor):
... |
ff7f7dcb405a313dedf08409f2714e36079b889c | MarcusVinix/Cursos | /curso-de-python/exemplos/tipo_de_dados.py | 397 | 3.5625 | 4 | #int
inteiro = 8
print(type(inteiro))
#float
numero = 9.7
print(type(numero))
#bolean
ativo = True
print(type(ativo))
#string
nome = "Marcus Vinicius"
print(type(nome))
#list
lista = ["Marcus", "Goku", "Naruto", "Natsu"]
print(type(lista))
#dict
familia = {}
familia[0, 0] = "Marcus"
familia[0, 1] = "Goku"
familia... |
abe978d9498b3edcb311552d4c797e615dbdbc79 | yqstar/MachineLearning | /TangYudi_MachineLearningCourse/MachineLearning/SVM/SVM_Facial_Recognition.py | 2,685 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : svm_face_recognition.py
# @Author: Shulin Liu
# @Date : 2019/3/8
# @Desc :
"""
As an example of support vector machines in action,
let's take a look at the facial recognition problem.
We will use the Labeled Faces in the Wild dataset,
which consists of several ... |
1103177ad273c3f1ac526fd1ad555b6cffe52279 | pseandersson/lsystem | /tests/test_lmath.py | 6,402 | 3.5625 | 4 | """
Tests for expressions and calculate
"""
import unittest
from random import choice, uniform
from lsystem.lmath import calculate, Expression, Operator
class TestExpression(unittest.TestCase):
def test_add(self):
"""Test a simple expression"""
expr = Expression('a+1')
self.assertEqual(exp... |
822ea9a3fb40c7e580cb25cb7b04f7418897ef28 | fessupboy/python_bootcamp_3 | /Tuples/Tuples.py | 219 | 3.765625 | 4 | t = (1,2,3)
mylist = [1,2,3]
print(type(t))
t = ('one',2)
print(t[0])
print(t[-1])
t = ('a','a','b')
print(t.count('a'))
print(t.index('a'))
print(t.index('b'))
mylist[0] ='NEW'
print(mylist)
t[0] = 'NEW'
print(t)
|
7118bf76fbb295f78247342b3b341f25d2d0a5c0 | adikadu/DSA | /implementStack(LL).py | 1,181 | 4.21875 | 4 | class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def node(self, value):
return {
"value": value,
"next": None
}
def peek(self):
if not self.length: return "Stack is empty!!!"
return self.top["value"]
def push(self, value):
node = self.node(value)
node["nex... |
4aaa2473dfc612231522c02ccd11dd26dbfceb0c | adikadu/DSA | /reverseString.py | 437 | 3.859375 | 4 | import re
# def reverseString(a):
# i=0
# j=len(a)-1
# a=list(a)
# while(True):
# if i>=j : return "".join(map(str, a)) # Converts list to string.
# k=a[i]
# a[i]=a[j]
# a[j]=k
# i+=1
# j-=1
# print(reverseString(input()))
def reverseString(a):
if len(re.findall(r"\S+", a)) == 0: #check if string con... |
2def6eec36986f0266030ced224a42ef3b127396 | adikadu/DSA | /factorial.py | 197 | 3.75 | 4 | def Rfact(n):
if n == 0 or n==1 : return 1
return n*Rfact(n-1)
def Ifact(n):
if n==0: return 1
x = 1
for i in range(2, n+1):
x *= i
return x
n=int(input())
print(Rfact(n))
print(Ifact(n)) |
1c9b8627cbcd812574bb52edbbfbc1bf9af86455 | Juand0145/AirBnB_clone | /models/engine/file_storage.py | 2,826 | 3.859375 | 4 | #!/usr/Bin/python3
'''Is a class FileStorage that serializes instances
to a JSON file and deserializes JSON file to instances:'''
import json
class FileStorage:
'''Is a class FileStorage that serializes instances
to a JSON file and deserializes JSON file to instances:'''
__file_path = "file.json"
__ob... |
95a649309ce0c95b56618400bce8eedb1bc7593d | Alex-Dumitru/python | /APPS/web_scraping/scrape_app.py | 2,852 | 3.59375 | 4 | """
scrape a website, gather data, and export it to csv
target page: century21.com
cached page, for practice: pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/
"""
import requests
from bs4 import BeautifulSoup as BS
web_page = requests.get('http://pythonhow.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/'... |
c99ca779476eac58b05e117c1825ba4189922f96 | Alex-Dumitru/python | /APPS/webmap_app/map1.py | 4,458 | 4.0625 | 4 | ''''
ibrary needed folium
pip install folium
the base layer of the map comes from openstreetmaps
'''
import folium
import pandas
def color_prod(elev):
if elev < 1500:
return 'green'
elif 1500 <= elev < 3000:
return 'orange'
else:
return 'red'
map = folium.Map(location=[80,-100])... |
cb0847a0abcf8a256c51c110ce61ea8eb6743f56 | Alex-Dumitru/python | /APPS/gui_and_db/kg_conv.py | 1,052 | 4.0625 | 4 | import tkinter as tk
# create the window object
window = tk.Tk()
# define the function
def kg_conv():
grams = float(e1_value.get()) * 1000 # convert kg to grams
pounds = float(e1_value.get()) * 2.20462 # convert kg to pounds
ounces = float(e1_value.get()) * 35.274 # convert kg to ounces
# insert... |
8d576d97f8aa4c97e8552e974bcedab81f504f3b | indigowhale33/COMS-4995 | /task3/task3.py | 842 | 3.578125 | 4 | from __future__ import print_function, division
import numpy as np
def MSD(nparr, ax=0):
"""
Calculate mean and standard deviation of numpy array by axis
Parameters
----------
- **Parameters**::
nparr : array_like
Array containing numbers
ax : int, optional (default=0)
Axis along which means and stand... |
09fe6ea10b609f2ee63a8f089f44f404b57be93b | mkumar-gt/t1 | /t4i.py | 464 | 3.859375 | 4 | Num_of_Numbers = 5
num_list = []
def main():
for i in range(Num_of_Numbers):
userInput = int(input("please enter number: "))
num_list.append(userInput)
info()
def find_lowest(anything):
lowestNumber = min(anything)
return lowestNumber
def totalN(anything):
total = 0
for i in anything:
total += i
r... |
70ce7118d3b24c724eb22a295dc82dae9770e511 | Dinesh-Sivanandam/HackerRank-Solutions | /sWAP_cASE.py | 459 | 4.03125 | 4 | def swap_case(S):
import string
lower = string.ascii_lowercase
upper = string.ascii_uppercase
T = []
for i in range(len(S)):
if S[i] in lower:
T.append(S[i].upper())
elif S[i] in upper:
T.append(S[i].lower())
else:
... |
e32e0bfa71eb66314bf38711126c8d5bf6662360 | phyllis-jia/note-for-python | /generator.py | 341 | 3.546875 | 4 | ##normal
def squares(N):
res=[]
for i in range(N):
res.append(i*i)
return res
for item in squares(9):
print(item)
##generator
def gensquares(N):
for i in range(N):
yield i**2
for item in gensquares(9):
print(item)
##generator has less code than normal way. Lazy evaluation makes... |
31b8704fbe6fef8de2c1d07e0d963ff053de66d4 | chapman-cs510-2017f/cw-05-seongandkynan | /cplane.py | 5,555 | 3.84375 | 4 | #!/usr/bin/env python3
import abscplane
""" The module includes a new class ListComplexPlane that subclasses the abstract base class AbsComplexPlane which is imported from the abscplane.py module.
"""
class ListComplexPlane(abscplane.AbsComplexPlane):
""" This class implements the complex plane with given attri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.