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 |
|---|---|---|---|---|---|---|
47b6bd082ed6d3ffe68451ff1eabdad04ede7020 | guam68/class_iguana | /Code/nathan/pythawn/lab_25_atm.py | 1,471 | 4.03125 | 4 | def check_balance(account):
return account
def check_interest(account, interest):
return account * interest
def deposit(account, amount):
return account + amount
def withdrawal(account, amount, history):
if account - amount < 0:
print('sorry you don\'t have that much money')
histor... |
5348a58a039c460277ad8c2fd7d6c58d575f0768 | guam68/class_iguana | /Code/Scott/Python/Lab_15_number_to_phrase.py | 2,272 | 4.0625 | 4 | #Lab_15_number_to_phrase.py
#version 1 = 1 - 99
# Convert a given number into its english representation. For example: 67 becomes 'sixty-seven'. Handle numbers from 0-99.
#
# Hint: you can use modulus to extract the ones and tens digit.
#
# x = 67
# tens_digit = x//10
# ones_digit = x%10
# Hint 2: use the digit as an i... |
643a141a96f0e4eeed285cae8e3f92271b1cb169 | guam68/class_iguana | /Code/Matthew/python/practice.py | 3,642 | 3.984375 | 4 |
# how to validate user input
# direction = input('what direction do you want to move in? ').lower()
# if direction in ['left', 'l', 'west', 'w']:
# # move left
# elif direction in ['right', 'r', 'east', 'e']:
# # move right
# else:
# print('command not recognized')
# def get_number(message):
# ... |
e1b9d92f766b4753c3fe834c790c7af0f792edf5 | BabyCakes13/Simple-Multilayer-Perceptron | /simple_mlp/network.py | 5,490 | 3.640625 | 4 | """Module which implements the neural network."""
from simple_mlp import layer as lay
class Network:
"""Class which holds the neural network structure and its functions."""
def __init__(self, weights,
activation_functions,
activation_functions_derivatives):
"""
... |
893cbc68e4095e7508625e6c423aad0e16ed2e1e | richpeaua/FB | /hackerrank/jumpingOnClouds/play.py | 433 | 3.65625 | 4 | def jumpingOnClouds(c):
jump = index = 0
while index < len(c) - 1:
if index + 2 > len(c) -1 or c[index + 2] == 1:
index += 1
else:
index += 2
jump += 1
return jump
count = [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0,... |
d3ba05563c7610b321e431928ced8b9b613ce4fd | richpeaua/FB | /hackerrank/repeatedString/play.py | 304 | 3.5 | 4 | def generator(s, n):
return (n // len(s)) * s.count('a') + s[:n % len(s)].count('a')
# s = 'abc', a_count_in_s = 1, length_s = 3, n = (10 // 3) * a_count_in_s + a_count_in_s[:n % length]
# 'abcabcabcabca'
# if s = abc then a_count in s = 1
string = 'abc'
num = 10
print(generator(string, num))
|
2ebb3eddb4dedf555ad47fccf0886fef3fec92ec | aeroswitch/GeekBrains | /1_Python_basics/2_Embedded_types/Task2.py | 1,931 | 4.09375 | 4 | '''
2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами
0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка
элементов необходимо использовать функцию input().
'''
user_list = []
while True:
new_ele... |
b756186fbf896315ba4d107f6aa49f1e5da18058 | aeroswitch/GeekBrains | /1_Python_basics/2_Embedded_types/Task3.py | 3,208 | 4.5 | 4 | '''
3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц
(зима, весна, лето, осень). Напишите решения через list и через dict.
'''
month = int(input('Введите месяц в виде целого числа от 1 до 12: '))
winter = [12, 1, 2]
spring = [3, 4, 5]
summer = [6, 7, 8]
autumn... |
d04a6a59d53ba2a8f1e969c17a945f5afaf589b9 | aeroswitch/GeekBrains | /1_Python_basics/6_OOP_Basics/Task2.py | 2,401 | 4.375 | 4 | """
2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных
атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета
массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать форм... |
1771b6941e7f6d0e1722bd4ff57ae826f720da08 | aeroswitch/GeekBrains | /1_Python_basics/3_Functions/Task6.py | 3,388 | 3.6875 | 4 | exec """
6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово
состоит из латинских бу... |
791832ac4be5e5aea1049360ad832411becc7175 | aeroswitch/GeekBrains | /1_Python_basics/3_Functions/Task1.py | 1,217 | 4.4375 | 4 | """
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у
пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def division(var_1, var_2):
"""Принимает два числа и возвращает результат их деления"""
try:
return var_1 / var_2
... |
f48aef08a8ce88dfe4a58fdd5af5ea6ab3a2e474 | lind1022/Coursera | /Advanced machine learning - Kaggle/Assignments/wk1_pandas_basics.py | 3,012 | 3.703125 | 4 | import matplotlib.pyplot as plt
import seaborn; seaborn.set()
import os
import pandas as pd
import numpy as np
import PyQt5
%matplotlib qt
# os.chdir("C:/Lin/Data science/Py training/Python DS handbook")
DATA_FOLDER = 'C:/Users/lind/Coursera/Advanced machine learning - Kaggle/Final project'
trans = pd.read_csv(os.pa... |
6e0a5db83c6c2ae95587a8604ea2ad1d772519c2 | thwhisler/eulerproblems | /euler7.py | 398 | 3.6875 | 4 | def isPrime(x):
if (x < 2):
return False
if (x == 2):
return True
factor = 2
while (factor <= (x**.5)):
if (x % factor == 0):
return False
factor +=1
return True
def euler7(x):
counter = 1
prime = 3
while (counter < x):
if (isPrime(prim... |
e14336904f44d692404780e855400b8b01e3814b | thwhisler/eulerproblems | /euler1.py | 140 | 3.734375 | 4 | def euler1():
sum = 0
for x in range(1,1000):
if (x % 3 == 0) or (x % 5 == 0):
sum += x
print(sum)
|
6c11429f5950e6b673955ddc20d3d96cc15c54ee | osx447/small_projects | /the_first_project_after_editing_by_osx447.py | 1,409 | 3.953125 | 4 | #it is my last project put after editing
#and adding factions and making it more simple
#---------------------------------------------
import time
name = input("what's your name : ")
while True:
try:
age = int(input(f"please, enter your age {name} : "))
break
except:
print("enter your age in numbers please")
... |
910bad76c5aa4a8ad0f520e4c3cf0e5a9cd6495e | Josh-Ay/breakout-game | /block.py | 335 | 3.828125 | 4 | from turtle import Turtle
from random import choice
COLORS = ["red", "yellow", "green", "purple", "orange"]
class Block(Turtle):
def __init__(self, x, y):
super().__init__()
self.penup()
self.shape("square")
self.shapesize(stretch_len=3)
self.color(choice(COLORS))
s... |
8362eeed7d5aea58d5589009bafd0d2cbf9a809a | jmprovencher/Treasure-Picker-Robot | /glo/BlackPearl/robot/alignement/AlignementStation.py | 1,626 | 3.5625 | 4 | import math
class AlignementStation():
def __init__(self):
self.terminer = False
self.ajustements = []
def calculerAjustement(self, distance_x, distance_y):
ajustements_x = self.ajusterPositionLaterale_CM(distance_x)
if (ajustements_x[1] >= 1):
self.ajustements.app... |
b7816fc8efb71a1535030bc5c2a0dc583c29116c | yvette-luong/first-repo | /data-types.py | 668 | 4.1875 | 4 | """
Boolean = True or False
String = "Yvette"
Undefined = A value that is not defined
Integer = 132432
Camel Case = lower case first word and then capitalize each following word:
example: helloWorld
"""
"1231314"
Yvette = 123
Yvette
def helloYvette(): # this is a function, which is indicated by brackets
pr... |
0a89b15974d3abe10cd78ac306e3e493c89ebd9b | Gabriel-RdS/Python-orientado-a-Objetos-CAP-2 | /pythonOO2/programa.py | 864 | 3.921875 | 4 | from abc import ABCMeta, abstractmethod
class Programa(metaclass=ABCMeta):
def __init__(self, nome, ano):
self._nome = nome.title()
self._ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_likes(self, numero_de_likes=1):
self._like... |
65eb98fcdfecaa8f2e1c049d500737ccb5fbcc6c | Jmoore1127/aoc2018 | /day2/challenge2.py | 535 | 3.59375 | 4 | #!/usr/local/opt/pyenv/shims/python
def solve():
with open("input.txt", "r") as f:
lines = f.readlines()
for i in range(0, len(lines)):
currentLine = lines[i]
for j in range(i+1, len(lines)):
difference = 0
commonLetters = []
comparedLine = lines[j]
for k in range(0, len(currentLine)):
i... |
bd765b64c5d037c9ac4b9d0ef69e5af50b8e8a4a | andriyevski/study | /if.py | 400 | 3.8125 | 4 | number = 23
guess = int(input('Введите целове число: '))
if guess == number:
print('Поздровляю вы угадали,',number)
print('хотя и не выиграли никакого приза')
elif guess < number:
print('Нет, число немного больше...')
else:
print('Нет, число немного меньше')
print('END GAME') |
fc3c48d5744a6d16caa58be9d770dc2466954912 | Clay190/Unit-1 | /warmup2.py | 150 | 3.6875 | 4 | #Clay Kynor
#9/7/17
#warmup2.py name to lucky number
from random import randint
input("Enter your name ")
print("Your lucky number is", randint (1,10))
|
892d17b39aaece34cb39adfe8ff88cb08d9a74f8 | platinio/phyton-algorithms | /phyton-algorithms/different_summands.py | 450 | 3.5625 | 4 | # Uses python3
import sys
def optimal_summands(n):
if(n == 1 ):
return [1];
summands = []
counter = n;
for j in range( 1 , n):
if( (counter - j) >= j + 1):
summands.append(j);
counter -= j;
else:
summands.append(counter);
... |
2348706186ce602625c247c5e5f22eb7a977cb38 | dineshkumar12004/posture-corrector | /posture.py | 4,817 | 3.796875 | 4 | # slouch_detector/posture.py
"""
Tracks current key_point coordinates and uses these to check for
various improper postures.
Stores a scale factor, which is used to reduce or increase the distances
that are used to calculate distance between key_points to determine if
improper posture is detected.
Posture is measured ... |
9e7f0fe66a66cfe2f730cea55c8f987942352a0d | NikOneZ1/ExchangePulseTGBot | /database.py | 820 | 3.734375 | 4 | import sqlite3
class DB:
def __init__(self, db_file):
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
with self.conn:
self.cursor.execute(""" CREATE TABLE IF NOT EXISTS rates (
ID integer PRIMARY KEY,
... |
c3fe5511b9c02cbfb077995e56266692b3cc7364 | dmswl0311/Algorithm | /DFS,BFS/queue.py | 183 | 3.625 | 4 | from collections import deque
queue = deque()
queue.append(2)
queue.append(1)
queue.append(6)
queue.popleft() # 그냥 pop하면 안됨
print(queue)
print(list(queue))
|
d15f1f2b2da80a4148ad2756c019f8382e3a938d | jnthmota/ParadigmasProg | /Exercicio7/Ex4.py | 328 | 3.859375 | 4 | # Defina a função prodnlista que recebe como argumento uma lista de inteiros e
# devolve o produto dos seus elementos.
# Ex: prodnlista([1,2,3,4,5,6]) = 720
prodnlista = lambda list: list[len(list) -1] * prodnlista(list[:-1]) if len(list) > 0 else 1
assert (prodnlista([1,2,3,4,5,6]) == 720)
print(prodnlista([1,2,3,4,... |
d29ac9e0b6d28f1cfef9da5b4abf2ede749738bb | jnthmota/ParadigmasProg | /Exercicio5/Exemplo.py | 400 | 3.984375 | 4 | class Pessoa:
contador = 0
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
Pessoa.contador += 1
p1 = Pessoa ("Ana",22)
p2 = Pessoa ("Jose",34)
print(Pessoa.contador)
p1 = Pessoa ("Ana",22)
print(Pessoa.contador)
p2 = Pessoa ("Jose",34)
print(f'p1: {p1.nome},{p1.id... |
414d428bd2f319793a148e83f67966c44f808f8e | jnthmota/ParadigmasProg | /Exercicio8/Com@Funcoes/Ex3.py | 327 | 3.71875 | 4 | # Escreva uma função que exibe uma lista recebida como parâmetro. Ela deve,
# contudo, ordenar a lista antes. A ordenação deve ser feita por meio de um
# decorator.
def ordena(f):
def decorator(lista):
return f(sorted(lista))
return decorator
@ordena
def funcao(lista):
print(lista)
print(funcao([7,3,6,2,0,1,4,5]... |
e07210eb2fd8dd0bee95579b6bf0f4e4f5a8b5c4 | jnthmota/ParadigmasProg | /Exercicio7/Ex8.py | 413 | 4.0625 | 4 | # Defina a função junta que recebe como argumentos duas listas de números
# inteiros o1 e o2 e devolve a concatenação de o1 com o2 .
# Ex: junta([1,2,3],[4,5,6]) = [1, 2, 3, 4, 5, 6]
# Ex: junta([],[4,5,6]) = [4, 5, 6]
# Ex: junta([1,2,3],[]) = [1, 2, 3]
junta = lambda x, y: x + y if len(x) > 0 and len(y) > 0 else []
... |
8bce9914c337f41cd789eaaa8f984d26c24110c3 | jnthmota/ParadigmasProg | /Exercicio8/Com@Classes/Ex1.py | 506 | 3.796875 | 4 | # Escreva uma função que calcula a soma dos n primeiros números naturais, dado
# que n é recebido como parâmetro. Escreva um decorator que garanta que o valor
# recebido é natural (maior ou igual a 1).
class Validar:
def __init__(self,f):
self.f = f
def __call__(self,n):
if (n>=1):
return self.f(n)
else:
... |
4f3b7f5a2114e451ea26d078798405827063f9ba | jnthmota/ParadigmasProg | /Exercicio6/Ex2.py | 430 | 4.28125 | 4 | # 2 Defna a função div que recebe como argumentos dois números naturais m
# e n e devolve o resultado da divisão inteira de m por n. Neste exercício você não
# pode recorrer às operações aritmétcas de multplicação, divisão e resto da divisão
# inteira.
# Ex: div(7,2) = 3
def div( dividendo, divisor ):
return 0 if ... |
6327d00e12ed15dc29efaf5f6b9e08acc3699611 | davakir/geekbrains-python | /lesson-7/Maxtrix.py | 1,842 | 3.625 | 4 | class Matrix:
def __init__(self, data: iter):
self.data = data
def __str__(self):
return '\n'.join(' '.join([str(elem) for elem in row]) for row in self.data)
def __getitem__(self, item):
return self.data[item]
def __len__(self):
return len(self.data)
def __add__(... |
3c6d0774f7dd6da59fa5b32f3e37e389fe93f248 | davakir/geekbrains-python | /lesson-4/fifth.py | 648 | 4.28125 | 4 | """
Реализовать формирование списка, используя функцию range() и возможности генератора.
В список должны войти четные числа от 100 до 1000 (включая границы).
Необходимо получить результат вычисления произведения всех элементов списка
"""
from functools import reduce
def multiplication(multiplier_1, multiplier_2):
... |
5d726403aa52295dd2d32f3e6c2345dda7ef1bbc | davakir/geekbrains-python | /lesson-6/Employee.py | 1,277 | 4.25 | 4 | """
Employee больше подходит для сущности "сотрудник"
"""
class Employee:
_income = {}
def __init__(self, name, surname, position):
self.name = name
self.surname = surname
self.position = position
def set_income(self, salary, bonus):
self._income = {'salary': salary, 'bonus... |
815d9259fcb2ed18b82ac3fbf0c4120a892561ec | davakir/geekbrains-python | /lesson-5/fourth.py | 678 | 3.515625 | 4 | numbers_with_titles = {
"zero": "ноль",
"one": "один",
"two": "два",
"three": "три",
"four": "четыре",
"five": "пять",
"six": "шесть",
"seven": "семь",
"eight": "восемь",
"nine": "девять",
"ten": "десять"
}
with open('files/strings.txt') as file_obj:
with open('files/str... |
e7148c8e41c90f68adbf7012b78a368a9c5063b0 | rutuja0897/OPPsPrinciples | /Inheritance.py | 168 | 3.578125 | 4 | class A:
a,b=10,20
class B(A):
i,j=100,200
def m1(self,x,y):
print(x+y)
print(self.i+self.j)
print(self.a+self.b)
b=B()
b.m1(1,2)
|
59571806f485c4d80caeebe9b89dda05ee291217 | rutuja0897/OPPsPrinciples | /Abstraction3.py | 458 | 3.921875 | 4 | from abc import ABC,abstractmethod
class DefenceForce(ABC):
def Gun(self):
print("AK47")
@abstractmethod
def Area(self):
pass
class Army(DefenceForce):
def Area(self):
print("Land")
class Airforce(DefenceForce):
def Area(self):
print("Sky")
class Navy(DefenceFo... |
476a8fff7bf98ca3b391c3fc9bdda90451904e74 | AumPauskar/Timer | /timer.py | 2,243 | 3.78125 | 4 | # importing all the modules
import timeconversion
from tkinter import *
import json
with open('config.json', 'r') as config:
data = json.load(config)
hours = int(data['hours']); minutes = int(data['minutes']); seconds = int(data['seconds'])
# defining the starting minutes and seconds
# using a json format-->config.... |
bdd392e2d3c0d48cf42e54795cd64e34c918e80c | nickhs/greplin-challenge | /level2b.py | 309 | 3.75 | 4 | import level2
def answer(num):
total = 0
divider = 1
addnums = []
while divider < num:
if num % divider == 0:
if level2.is_prime(divider):
total = total + divider
addnums.append(divider)
divider = divider+1
return total-1
|
f2ebeabae3435b19e6ee211cc9c571947c6d7245 | beginner-at-coding/projectswithpython | /RockPaperScissors.py | 1,487 | 4.03125 | 4 | from random import randint #do not use colons, paranthesis or any arguments
#Creating the list for python operators
t=["Rock", "Paper", "Scissors", "Exit!"]
#assigning a random play for the computer.
computer=t[randint(0,2)]
#Setting the player value to false
player=False
while player==False:
#Set ... |
ce8da5c3e2f6d7fa896ad779fc28d3c578dea1c2 | RanXuhui/Baishiqiuke | /caogao.py | 86 | 3.59375 | 4 | lst = {}
lst["1"] = "a"
lst["2"] = "b"
for key in lst.keys():
print(key, lst[key]) |
201e7943c3afbac387c2991663e108e93d21869e | Nishuskamal000/git-test | /Assignment_15_07_2021_OOPS/Q2.py | 206 | 3.90625 | 4 | x = int(input("Enter the first number : "))
y = int(input("Enter the second number : "))
y = x + y;
print("Swapping done")
x = y - x;
print("First number is :", x)
y = y - x;
print("second number is : ", y) |
914c14038f3bfc5414f00fdc9f04c76d59b7f39b | well147258well/pythonHW | /week4_classtest.py | 229 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def isPrime(N):
sum=0
for y in range(1,N+1):
if N%y==0:
sum=sum+1
if sum==2:
return 1
else:
return 0
num=0
for x in range(2,1001):
if isPrime(x)==1:
num=num+x
print num |
bdacca53425d1583911e2c05226d869d08d0d3e5 | gmarciani/pymple | /dstruct/queue.py | 3,466 | 3.625 | 4 | #Interface Import
from model.base.basequeue import basequeue
#Support Data-Structures Imports
from model.linkedlist import SimpleLinkedList as LinkedList
from collections import deque
class QueueLinkedList(LinkedList, basequeue):
def enqueue(self, element):
"""
Enqueues the element at ... |
05f5639b549a5452c42114a18fede41339927338 | gmarciani/pymple | /dstruct/base/baselinkedlist.py | 3,807 | 3.75 | 4 | class baselinkedlist:
"""
Linked-List interface.
is_empty()
add_as_first(element)
add_as_last(element)
get_first()
get_last()
get_first_record()
get_last_record()
pop_first()
pop_last()
delete_record(record)
"""
def is_empty(self)... |
2bb656fcaa3dfad9be36dbcce861283d096ec2d6 | agathaappb/project_python | /odd.py | 1,705 | 3.984375 | 4 | from datetime import datetime
import time
import random
odds = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59 ]
for x in range(5):
right_this_minute = datetime.today().minute
# Isso é um comentário
if right_this_minute in odds:
... |
eddd68d30e9e5d68f0d10528f4b30994176ac410 | dannycrief/full-stack-web-dev-couse | /Web/B/2/2.11/counter.py | 478 | 3.703125 | 4 | import collections
import random
c = collections.Counter()
print(c['key'])
print(c["k"])
c[32] += 1
print(c)
# the new one
print("")
c = collections.Counter()
for x in range(10):
c[x] = random.randint(1, 100)
print(c.most_common(3))
print(c)
for key, value in c.most_common(3):
print("{} - {}".format(key, val... |
abc5348a60aa3b3acdfee32ef6f83f98fff5bbcb | dannycrief/full-stack-web-dev-couse | /Web/B/2/2.5/2.5.py | 344 | 3.5 | 4 | FILENAME = 'input.txt'
reader = open(FILENAME)
lines = reader.readlines()
reader.close()
writer = open('output.txt', 'w')
lines_counter = 0
for line in lines:
stripped_line = line.strip()
if stripped_line:
writer.write(stripped_line)
writer.write('\n')
lines_counter += 1
writer.close... |
ebb824b95aa3be4d4e65166487a12d6d3fdc320a | dannycrief/full-stack-web-dev-couse | /Web/B/2/2.8/knowmynum.py | 507 | 3.921875 | 4 | import random
"""
secret = random.randint(1, 100)
for attempt in range(10, 0, -1):
guess = input('Will you know my num? You have {} tries\n'.format(attempt))
guess_number = int(guess)
if guess_number == secret:
print("Yeah, right")
break
elif guess_number < secret:
print("My num... |
d41da39f9f398e987c6262afc0b7ffeae2bd5682 | dannycrief/full-stack-web-dev-couse | /Web/B/1/1.11/tast1-11.py | 184 | 3.75 | 4 | names_len = {}
people = ["Bob", "Liza", "Anna", "Fanny", "Violet"]
for person in people:
names_len[person] = len(person)
keys_ = list(names_len.keys())
keys_.sort()
print(keys_)
|
d2ff262bcb0d167b311f72d61ebd6a32cc1d5afd | johnsmeeth/basicPython | /dataStructure.py | 220 | 3.703125 | 4 | __author__ = 'thanhnguyen'
## list: this data structure like array on some language such as c/c++, javascript...
cars = ["BMW", "Audi", 'Mercedes', 88, 99, 'Bentley'] # Create a new list
print cars[0:2]
print cars[:-1]
|
8fd555824b5b0e1cad7bfc1b1749181517cab9d6 | 3chamchi/likelion-seoul-6th | /week2/02_control.py | 902 | 3.875 | 4 | ### 제어문
### if
#if - 1
print('if - 1')
animal = '사자'
if animal == '사자':
print('사자입니다.')
#if - 2
print('if - 2')
age = 21
if age < 20:
print('청소년입니다.')
else:
print('성인입니다.')
#if - 3
print('if - 3')
score = 99
if score < 60:
print('E 학점')
elif score < 70:
print('D 학점')
elif score < 80:
print('C ... |
9d4a7f7dc503c136019b11c0186fdb5c887d5980 | 3chamchi/likelion-seoul-6th | /week3/04_class.py | 2,047 | 4.0625 | 4 | class Person(object):
def __init__(self, name, age, money):
# print('Person.__init__()')
self.name = name
self.age = age
self.money = money
def hello(self):
""" 인사 """
pass
def how_much(self):
""" 금액 출력 """
pass
class Korean(Person):
de... |
1e16678a1f6aea8c6fb96fe6abf9d2ac8b9914bd | drio/euler | /p28/euler-p28.py | 2,121 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: set ts=4 noet ft=python:
#
'''
// Problem 28
//
// Published on Friday, 11th October 2002, 06:00 pm; Solved by 59507
//
// Starting with the number 1 and moving to the right in a clockwise
// direction a 5 by 5 spiral is formed as follows:
//
// 21 22 ... |
31ece7416f5a77c13294ff458be63d90154f095b | drio/euler | /p34/euler-p34.py | 924 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: set ts=4 noet ft=python:
#
'''
// Problem 34
//
// Published on Friday, 3rd January 2003, 06:00 pm; Solved by 50376
//
// 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 fa... |
53ac16f17c18495f29d560fe42abfa0e176cff48 | youcefm/schelling-dynamic-segregation | /spatialmodel/spatial_configuration.py | 3,595 | 3.625 | 4 | import math
import random
from agent.agent import Agent
from house.house import House
from utils.pygame_utils import *
class SpatialConfiguration(object):
"""
Populates a city with houses and agents, following a specific design.
The current designs are line, Circle and Grid.
"""
def __ini... |
1f291ae733d7be79463b3da35ee3300bbebaa694 | gdevina1/MIS3640-Repository | /Session 6/Session6InClass.py | 563 | 4.0625 | 4 | print("Session 6 - Conditionals")
age = input ("What is your age?")
age= int(age)
#Chained Conditionals
if age >= 18:
print("Your age is {}".format(age))
print("Adult")
elif age >=6:
print("Your age is {}".format(age))
print("Teenage")
else:
print("cudi the kid")
age = 20
if age >= 6:
pri... |
38c2d3b384685c96d7806db8ced3306426e058cf | gdevina1/MIS3640-Repository | /Assignments/Assignment1/nim.py | 5,459 | 4.4375 | 4 | '''
The game of Nim. This is a well-known game with a number of variants. The following variant has an interesting
winning strategy. Two players alternately take marbles from a pile. In each move, a player chooses
how many marbles to take. The player must take at least one but at most half of the marbles. Then the othe... |
18848633171c8a68b2a3b7a1810c2b67df71152f | gdevina1/MIS3640-Repository | /Session 8/Session8Exercise4.py | 762 | 3.875 | 4 | #exercise 4
#1
def price(word):
p = 0
for letter in word:
p += ord(letter)-96
return p
print('bananas', ' $',price('bananas'))
print('rice', ' $',price('rice'))
print('paprika', ' $',price('paprika'))
print('potato chips', ' $',price('potato chips'))
print('----------------... |
7c263f8cb4c3eedce2b1cd3d678e90b57613bab6 | gdevina1/MIS3640-Repository | /Session 5/Session5InClass.py | 1,699 | 4.1875 | 4 | print("Session 5 - Functions II")
import turtle
bear = turtle.Turtle()
print(bear)
#for i in range(4): #the range has to be an integer
# bear.fd(100)
# bear.lt(90)
#for i in range(4):
# print(i)
#
#turtle.mainloop()
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
#sq... |
0df2b1f04fcdf47078b4e82020dada407302d72d | gdevina1/MIS3640-Repository | /Session 4/Session4function_demo.py | 896 | 3.65625 | 4 | def print_lyrics():
print("Hey Jude. Don't make it bad.")
print("Take a sad song and make it better.")
print_lyrics()
print(type(print_lyrics))
def repeat_lyrics():
print_lyrics()
print('Na - na - na - na - na, na - na - na - na')
print_lyrics()
# repeat_lyrics()
def print_twice(name):
print(n... |
25f0b3021eaac3d35e9a499897a2e91788285b42 | gdevina1/MIS3640-Repository | /Session 9/Session9Exercise2.py | 729 | 3.796875 | 4 | fin = open('words.txt')
# def is_abecedarian(word):
# previous = word[0]
# for c in word:
# if c < previous:
# return False
# previous = c
# return True
# print(is_abecedarian("bit"))
# print(is_abecedarian("cat"))
#--------REWRITE USING RECURSION-----------#
# def is_abeced... |
ea0c151e692d6c91fc772c671c21cb1a111d0b47 | ChoiSangjo/python_study | /2_jump_basic/python_class.py | 1,943 | 3.859375 | 4 | class Calculator: #클래스(과자 틀)
def __init__(self):
self.result = 0
def add(self, num):
self.result += num
return self.result
def sub(self, num):
self.result -= num
return self.result
cal1 = Calculator() #객체(과자) / Calculator의 인스턴스
cal2 = Calculator()
cal3 = Calculator... |
9ee3603ef7ccb979facafcaa3b10397248bf0dc2 | wuli2496/OJ | /UVa/1418 WonderTeam/WonderTeam.py | 1,202 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 08:48:03 2019
@author: wl
"""
from abc import ABCMeta, abstractmethod
import sys
class AlgoPolicy(metaclass=ABCMeta):
def __init__(self):
pass
def execute(self):
return self.process()
@abstractmethod
def... |
f2e74780277b6ac8198b3f35612b7da0c231acf7 | total4ever/fp_7-9_p1 | /ui/console.py | 4,949 | 3.6875 | 4 | class Console():
def __init__(self, ctrlStudent, ctrlDisc, ctrlGrades):
self.__ctrlStudent = ctrlStudent
self.__ctrlDisc = ctrlDisc
self.__ctrlGrades = ctrlGrades
def __meniu(self):
print("1 - Adauga student")
print("2 - Afisare studenti")
print("3 - Adauga disc... |
d38f24f724d4891208e808fd6244a606603303b0 | pedrodiogo219/competitiveProgramming | /minimaratonas/testes/d.py | 93 | 3.546875 | 4 | x = int(input())
k = x
k+=x
print(k)
k+=x
print(k)
k+=x
print(k)
k+=x
print(k)
k+=x
print(k)
|
f5e18483e974324b2b8b1d6bfe56ba84fa9e4ea7 | casprice/dice-games | /Python/dicegame.py | 637 | 3.953125 | 4 | import random
total = 0
while True:
print('\nWelcome to the Dice Game!\n')
num = int(input('Enter how many dice you want to roll: '))
for x in range(num):
rand = random.randint(1, 6)
total += rand
print('Die #' + str(x + 1) + ': ' + str(rand))
print('\nTotal = ' + str(total))... |
2e7839e32546b9cf8a790c16b71c24986d8f12cb | stevenhughes08/CIT120 | /work/python/unit7/SuperMarket.py | 1,337 | 4.28125 | 4 | # SuperMarket.py - This program creates a report that lists weekly hours worked
# by employees of a supermarket. The report lists total hours for
# each day of one week.
# Input: Interactive
# Output: Report.
# Declare variables.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done" # Named cons... |
0993203dafbda4d758dcc82f90ea06750fc4bb69 | AlirieGray/CS-3-Core-Data-Structures | /source/stack.py | 4,672 | 4.28125 | 4 | #!python
from linkedlist import LinkedList
from linkedlist import Node
class LinkedStack(object):
def __init__(self, iterable=None):
"""Initialize this stack and push the given items, if any."""
# Initialize a new linked list to store the items
self.list = LinkedList()
if iterable... |
f25313f5260876e54141d6ee9a82cc2117d77521 | FelixTang-only/learn_py | /day9.py | 1,807 | 4.125 | 4 | # 函数的参数详细解读
# 位置参数
# def power(x):
# return x * x
# power(4)
# power(x, n)
# def power(x, n):
# s = 1
# while n > 0:
# n = n - 1
# s = s * x
# return s
# print(power(5, 2))
# 默认参数
# power(5)
# def power(x, n = 2):
# s = 1
# while n > 0:
# n = n - 1
# s = s * x
# ... |
9acfbda7cc64e054cffd4e230b3a68f7aff2fda4 | shobhitasthana/Data401Project3 | /NeuralNetwork.py | 8,009 | 3.734375 | 4 | import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
class NeuralNetwork:
"""
Layers: an Integer value representing the total number of hidden layers in the network (input and output layers are extra)
Nodes: an integer array of size [0,..,Layers+1] containing the dimensio... |
a599048e686e251f5b6cfbd98627642ac30ecc10 | ryan-semmler/currency_converter | /currency_converter.py | 697 | 3.5 | 4 | from currency import *
class CurrencyConverter:
def __init__(self, cur_object, new_code):
self.currency = cur_object
self.code = new_code
self.rates = {'USD': 1.0, 'EUR': 0.74, 'JPY': 120}
def convert(self, cur_object, new_code):
if new_code in '$¥€' or new_code in ['USD', 'J... |
a313b4da7cd99a1bf78a9b3e8d9ee8b220d101ae | fsieversr/MCOC-Nivelacion | /21082019/000609.py | 480 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 16:27:56 2019
@author: panch
"""
#Listas
#definicion de lista con nombre "b"
b = ["banana", "apple", "microsoft"]
#cambio de orden entre banana y microsoft
temp = b[0] #creamos una variable auxiliar para guardar "banana"
b[0] = b[2] #cambiamos banana por microsoft
b[... |
ee557798a18d343708e3b9b55b3304ddff52c04e | brigusta0295/mycode | /iflogicchal/coffeeratiocal.py | 746 | 4.0625 | 4 | #!/usr/bin/env python3
'''
Coffee calculator simulation based on the type of
brewing technique.
'''
print("Welcome to the brewing ratio calculator!")
print("Please indicate the brewing method. Chemex, Aeropress, or French Press")
while True:
answer = input("Brewing Method? >").title()
if answer == "Chemex":
... |
c9171441fc15fc9f22c8af5fa24124fbc2920814 | niushufeng/Python_202006 | /代码/图片颜色渐进标注.py | 652 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np # 多维数组和矩阵函数,用来产生数据
# image data
a = np.array([0.314,0.365,0.424,
0.365,0.440,0.525,
0.424,0.525,0.652]).reshape(3,3) #reshape以三行三列的数组形式显示
"""
interpolation 的网站
http://matplotlib.org/examples/images_comtours_and_fields/interpolation_methods.... |
f7b81958260ca8b34fd3c5ce9e839de104367b5e | niushufeng/Python_202006 | /算法代码/0-100之间的算法/偶数求和.py | 476 | 3.71875 | 4 | # 计算0-100之间所有偶数的累计求和结果
# 0. 定义最终变量的结果
result = 0
# 1.定义一个整数变量记录循环的次数
i = 0 # 计算机计数从0开始
# 2. 开始循环
while i <= 100:
# 判断变量i中的数值是否是一个偶数
# i % 2 == 0
if i % 2 == 0:
print(i) # 加一个Tab
result += i # Tab加一个缩进,属于if 的条件判断
# 处理技术器
i += 1
print("result = %d" % result)
|
9cbf552b5a7e814272f5c37ebde6d7caa2594d96 | niushufeng/Python_202006 | /代码/次坐标轴.py | 337 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np # 多维数组矩阵
x = np.arange(0,10,0.1)
y1 = 0.05*x**2
y2 = -1 *y1
fig,ax1 = plt.subplots()
ax2 = ax1.twinx() # 以x为镜面
ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'b--')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1',color = 'g')
ax2.set_ylabel('Y2',color = 'purple')
plt.show()
|
a04a9d65e19c9b71be38dc80eb1caf4d2f30231f | niushufeng/Python_202006 | /算法代码/面向对象/异常/主动抛出异常_输入密码.py | 609 | 3.890625 | 4 | # 需求
def input_password():
# 1.定义 input_password 函数,提示用户输入密码
pwd = input("请输入密码:")
# 2.如果用户输入长度<8,抛出异常
if len(pwd) >= 8:
return pwd
# 3.如果用户输入长度>8,返回输入的密码
print("主动抛出异常")a
# 1>创建异常对象 - 可以使用错误信息字符串作为参数
ex = Exception("密码长度不够") # 元组的错误信息
# 2>主动抛出异常
raise ex
# 提示用户输入密... |
3af30205b7b89f26e1a63b364985d8a7556d9466 | niushufeng/Python_202006 | /算法代码/面向对象/私有属性/伪私有属性和方法.py | 641 | 3.796875 | 4 | class Women:
def __init__(self,name):
self.name = name
self.__age = 18 # aga前面加“__”就是指的私有属性;对名称进行了特殊处理,使外界无法访问
def __secret(self): # 加“__”指的就是私有方法
# 在对象的方法内部是可以访问私有属性的
print("%s 年龄是 %d" % (self.name,self.__age))
# 创建一个对象
xiaofang = Women("小芳")
# 私有属性,在外部不能够被直接访问
print(xiao... |
720a17f78d0a652e5f0aaf02b2f6273e1bd97fac | niushufeng/Python_202006 | /算法代码/0-100之间的算法/所有数据求和.py | 384 | 3.90625 | 4 | # 计算0-100之间所有数字的累计求和结果
# 0. 定义最终变量的结果
result = 0
# 1.定义一个整数变量记录循环的次数
i = 0 # 计算机计数从0开始
# 2. 开始循环
while i <= 100:
print(i)
# 每一次循环都让result这个变量和i这个计数器相加
result += i
# 处理技术器
i += 1
print("result = %d" % result)
|
001876e4a8bdf71f4cc1c05fa4698262827de4d5 | danangsw/python-learning-path | /sources/6_basic_string_operations/1_string_operations.py | 828 | 4 | 4 | astring = "Hello world!"
astring = 'hello world!'
print("a single quote is here ' '")
print(len(astring))
print(astring +" .capitalize() => "+astring.capitalize())
print(astring + " .index('wor') => %d " % astring.index('wor'))
print(astring + " .count('l') => %d " % astring.count('l'))
astring = 'abcdefghijklmnop'
p... |
a3d6d0d7062c1452341c59741ea67aada4dc9ed8 | danangsw/python-learning-path | /sources/8_loops/4_else_loop.py | 640 | 4.3125 | 4 | # Python supports `else` with a loops.
# When the loop condition of `for` or `while` statement fails then code part in `else` is executed.
# If `break` statement is executed then `else` block will be skipped.
# Even any `continue` statement within a loops, the `else` block will be executed.
count = 0
while count < 5:... |
46a5afc1832bc61b10a7da14dc26b7219dbb674b | danangsw/python-learning-path | /sources/8_loops/2_while_loop.py | 137 | 3.828125 | 4 | # While loops repeat as long as a certain boolean condition is met.
count = 0
while count < 5:
print(count)
count += 1
pass |
2e4761e091c6838cfdedbd8bdd48c727a606afd5 | hjhorsting/Bootrain2 | /PythonBasics.py | 549 | 4.4375 | 4 | # 1. Write a code that outputs your name and surname in one line.
print("Harald Horsting")
# or:
print("Harald", "Horsting")
# 2. Write a 1-line code that outputs your name and surname in two separate lines by using
# a single print() call.
print("Harald \n Horsting")
# 3. Use print() function that returns the fol... |
ace6644ed48956e133f276d3d7a834cdecab97cc | alexanderbukreev/python | /lesson1/dz1.py | 212 | 3.546875 | 4 | name = input("Введите ваше имя: ")
age = int(input("Введите ваш возраст: "))
addon = 20
print(f"{name}, Ваш возраст через {addon} лет будет {age + addon}")
|
1850f0d875857d5481322d8d7efaf4d7e8a602e6 | cheddy1/random-projects | /learningPY/terminalVelocity.py | 2,358 | 4.03125 | 4 | import math
def getVelocity(m,c,s):
global g
global p
g = 9.8 #Gravity
p = 1.225 #Air Density
m = m/1000 #Grams to kg
velocity = math.sqrt((2*m*g)/(p*c*s)) #Terminal Velocity Formula
printEverything(velocity,m,c,s)
def askUser():
again = 'y'
while again == 'y':
global ob... |
86b50d18bf82acbf185dafae20a046b194e5f1e5 | rvsp/Python3-reference | /2_variables-types.py | 563 | 3.6875 | 4 | '''
Owner: Venkatasubramanian
Topic: Variables and different types
'''
'''
int, float, string, list, tuple, set, dict, etc.
'''
int_type = 100 # An integer assignment
float_type = 10.6 # A floating point
string = "Hello world" # A string
print(int_type, type(int_type))
print(float_... |
20177ae27ca63089ae3f77ca5ba08223690003c0 | rvsp/Python3-reference | /Advanced/py-array-module.py | 1,106 | 3.71875 | 4 | '''
Owner: Venkatasubramanian
Topic: Python array module
'''
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
a1 = arr.array('i', [2, 4, 6, 8])
print("First element:", a1[0])
print("Second element:", a1[1])
print("Last element:", a1[-1])
# slice in array
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
n... |
1c6606dea1b52c9f83eac662a06e758295945a9e | baflQA/hyperskill | /Simple Currency Converter/Simple Currency Converter/task/tests.py | 7,539 | 3.5 | 4 | from hstest import StageTest, CheckResult, dynamic_test, TestedProgram
class CurrencyConverter(StageTest):
test_amounts = ["1", "3", "18", "50", "115"]
usd = 1.0
jpy = 113.50
eur = 0.89
rub = 74.36
gbp = 0.75
currencies = {"JPY": jpy, "EUR": eur, "RUB": rub, "GBP": gbp, "USD": usd}
kno... |
0129054fc9cac41a867350212d2d11c4ac157f9f | Wanderson96/ATIVIDADE-COMPLETA | /LETRAS A B C D E.py | 1,229 | 4.15625 | 4 | dia = int(input("escreva o dia: "))
mes = int(input("escreva o mês: "))
ano = int(input("escreva o ano: "))
print("DATA: ",dia,'/',mes,'/',ano)
A = int(input("escreva a variavel A: "))
B = int(input("escreva a variavel B: "))
C = int(input("escreva a variável C: "))
print("MEDIA DAS VARIÁVEIS: ",(A+B+C)/3)
X = in... |
2c099c78fb2eff10a340d1ba214e333cfb17d720 | MarKuchar/intro_to_algorithms | /1_Variables/operators.py | 1,205 | 4.15625 | 4 | # Operators
# =, -, *, /, // (floor division)
# % (modulo): 'mod' remainder
# ** (power)
print(10 % 3) # 1
print(10 ** 2) # 100
print(100 // 3) # 33
print(100 - 5)
# = : assignment
number = 7
number = number + 3 # increment number by 3
number += 3 # increment number by 3
# -= : decrement operator
print("number =... |
5b25724eae900e42228b5687f4f2691b7bb10031 | MarKuchar/intro_to_algorithms | /8_Functions/functions.py | 1,050 | 4.28125 | 4 | # Functions are a very convenient way to divide your code into useful blocks, make it more readable and help 'reuse' it.
# In python, functions are defined using the keyword 'def', followed by function's name.
# "input --> output", "A reusable block of code"
def print_menu():
print("----- Menu -----")
print("... |
1d7501c04e7e41331f36b5085202c7c1da7aa91b | MarKuchar/intro_to_algorithms | /4_Tuples/tuples_basics.py | 970 | 4.34375 | 4 | # Tuples are almost identical to lists
# The only big difference between lists and tuples is that tuples cannot be modified (Immutable)
# You can NOT add(append), changed(replace), or delete "IMMUTABLE LIST"
# elements from the tuple
vowels = ("a", "e", "i", "o", "u") # consonants (b, c, d, ...)
print(vowels[0])
prin... |
e783da31a78d9b2f0f786c0a7f5b9a7bd707833e | MarKuchar/intro_to_algorithms | /1_Variables/variable_type.py | 883 | 4.3125 | 4 | # Data types
# There are many different data types in Python
# int: integer
# float: floating point (10.23, 3.14, etc)
# bool: boolean (True, False)
# str: a sequence of characters in quotes "aa", 'aa'
language = "en_us"
print(type(language)) # check the type of the variable
users = 10
"""
print(users + language) #... |
cbd9220c96f2b5515e2684ec246d600b6b8d9e84 | BUITGGWP/Rec | /1.py | 259 | 3.734375 | 4 | # Наибольший общий делитель (НОД)
def nod(x, y):
if x == y:
return x
else:
if x > y:
return nod(x-y, y)
else:
return nod(x,y-x)
print(nod(int(input()), int(input()))) |
10bd386fc03b3f66ae447244acc971aeecb5a4c9 | r426/Week-2-Sequence-Types-Challenge-2 | /tupleType.py | 218 | 3.8125 | 4 | myTuple=(40,)
print(type(myTuple))
myTuple=(40)
print(type(myTuple))
myTuple1=(40,56,1.25,3,4.54,58,22,22,22,22)
print(max(myTuple1))
print(min(myTuple1))
print(myTuple1[2])
print(myTuple1*2)
print(myTuple1.count(22))
|
97ba3c78a08b56bd31b618b6cec58642474a17e2 | lilcsa/Restaurant_Menu | /Restaurant_Menu_Repetition.py | 518 | 3.890625 | 4 | print "Welcome to your menu program"
menu = {}
while True:
dish = raw_input("Enter name of dish: ")
price = raw_input("Enter price of dish: ")
menu[dish] = price
end = raw_input("Do you want to add another dish? (y/n)")
if end == "n":
break
print "Our daily menu: "
for it... |
44567368cb495beed9867494a4d292bd4915d037 | bsofcs/interviewPrep | /maxSumPathBT.py | 1,427 | 3.734375 | 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
sumTot=0
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
global sumTot
sumTot=float("-INF")
if root is None:... |
aa74e2480dc4bcdb1a413d099292aaa3845d50e3 | bsofcs/interviewPrep | /makeTreeFromLevelAndInOrder.py | 1,041 | 3.9375 | 4 | """
makeTreeFromLevelAndInOrder
"""
class Node:
def __init__(self,val):
self.right=None
self.left=None
self.data=val
def makeTreeFromLevelAndInOrder(levelOrder,inOrder):
if levelOrder is None or inOrder is None:
return
inStrt=0
inEnd=len(inOrder)-1
root=makeTreeUtil(levelorder,inorder,inStrt,inEnd)
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.