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 |
|---|---|---|---|---|---|---|
bc7a23659f77f9fe3e9e9febf0599421996d1087 | OleaBlossom/py_eoc_solutions | /adamantiteStorage/brackets.py | 683 | 3.890625 | 4 | #!/usr/bin/env checkio --domain=epy run brackets
def brackets(expression):
return True or False
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print("Example:")
print(brackets("((5+3)*2+1)"))
assert brackets("((5+3)*2+1)") == True, "Simple"
... |
7e78521d6f676142fd5dab31db17b9ebcb56d32c | zoltanu/pythonfun | /Exercises/Exercise 3.py | 595 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 11 14:22:09 2018
@author: Udvardy
"""
"""This is exercise 3"""
print("This is excercise 3, please follow the instructions")
lista=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89];
lista2=[]
lista3=[]
print("The original list is [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]")
for elemen... |
16c862609f2b52921d214facaba3e87ef050dae7 | Nextc3/aulas-de-mainart | /Listas/Lista 6/q2.py | 1,682 | 4.15625 | 4 | '''
Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em
metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro
para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que
custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
• In... |
070eade4331c95bec0a35e6223c9053e772ed89f | Nextc3/aulas-de-mainart | /Listas/Lista 5 Camila Marinho/questao9.py | 294 | 3.640625 | 4 | lucro = {
True: 45, #menor que 20
False: 30 #maior que 20
}
valor_compra = float(input('Entre com o valor do produto: '))
porcentagem_lucro = lucro[valor_compra < 20] / 100
valor_venda = valor_compra + valor_compra * porcentagem_lucro
print('Valor da venda: {}.'.format(valor_venda))
|
ac220aa44fa066813e81878b527106195b08ecd4 | Nextc3/aulas-de-mainart | /Listas/Lista 5 Camila Marinho/questao13.py | 183 | 3.9375 | 4 | multiplo_3 = {
True: 'É múltiplo de 3.',
False: 'Não é múltiplo de 3.'
}
numero = int(input('Entre com um número: '))
resto = numero % 3
print(multiplo_3[resto == 0])
|
deac9d6024ce82f36c08b88799eafbf4173ba236 | Nextc3/aulas-de-mainart | /Listas/Lista 5/q4.py | 202 | 4.125 | 4 | numero1 = int(input("Entre com o numero1: "))
numero2 = int(input("Entre com o numero2: "))
dict_decisao = {True:numero1, False:numero2}
print("Maior numero: {}".format(dict_decisao[numero1 > numero2])) |
33380c8884a16b7844ca43f873d27064cf3828cb | Nextc3/aulas-de-mainart | /Listas/Lista 7/q5.py | 251 | 4.0625 | 4 | #5.Entrar com nomes enquanto forem diferentes de FIM e imprimir o primeiro caracter de cada nome;
nome = input("Entre com um nome: ")
while nome != "FIM":
print("Primeira letra do nome: {}".format(nome[0]))
nome = input("Entre com um nome: ")
|
3909d5c93696bd65d1fd8d67667af512fb1f11e2 | Nextc3/aulas-de-mainart | /Listas/Lista 5/q7.py | 408 | 4.0625 | 4 | maior = 0
menor = 0
intermediario = 0
numero1 = int(input("Entre com o numero1: "))
numero2 = int(input("Entre com o numero2: "))
numero3 = int(input("Entre com o numero3: "))
lista_numero = [numero1,numero2,numero3]
lista_numero.sort()
menor = lista_numero[0]
intermediario = lista_numero[1]
maior = lista_numero[2]
pr... |
31f7539a1e78ae31d49cfb85d0c1988eb667cb90 | Nextc3/aulas-de-mainart | /Listas/Lista 5 Camila Marinho/questao7.py | 316 | 4.03125 | 4 | lista = []
numero1 = int(input('Entre com o primeiro número: '))
numero2 = int(input('Entre com o segundo número: '))
numero3 = int(input('Entre com o terceiro número: '))
lista.append(numero1)
lista.append(numero2)
lista.append(numero3)
lista.sort()
maior = lista[2]
menor = lista[0]
intermediario = lista[1]
|
37c03014315027f8ffd8f3206642a4da7160b2e4 | Nextc3/aulas-de-mainart | /Listas/Lista 7/q6.py | 396 | 3.984375 | 4 | #6.Entrar com vários números ate entrar com o numero 999. para cada numero imprimir seus divisores;
numero = int(input("Entre com um número: "))
while numero < 999:
resto = 1
for i in range(1,numero):
resto = numero % i
if resto == 0:
print("Divisor: {}".format(i))
print("Divis... |
dc1d39577e73ac2d329eb7802b85b98f53bf42a3 | Nextc3/aulas-de-mainart | /Listas/Lista 7/q9tentativa2.py | 1,911 | 3.828125 | 4 | '''
9.Uma empresa de
fornecimento de energia elétrica faz a leitura mensal dos medidores de
consumo. para cada consumidor, são digitados os seguintes dados:
a)Numero do consumidor;
b)Quantidade de kWh consumidos durante o mês;
c)tipo do consumidor ->
1-residencial, preço em reias de kWh = 0,3 /
2-comercial, ... |
83b736e4713869f159425a1093201a9db2d37107 | Nextc3/aulas-de-mainart | /Listas/Lista 5 Camila Marinho/questao15.py | 365 | 3.71875 | 4 | emprestimo = {
True: 'O empréstimo pode ser concedido.', #menor ou igual que 30%
False: 'O empréstimo não pode ser concedido.' #maior que 30%
}
salario_bruto = float(input('Entre com o salário bruto: '))
prestacao = float(input('Entre com o valor da prestação: '))
porcentagem = prestacao / salario_bruto * 100... |
07579444d64fb7037612731d380db0354e131cac | jbaisani/coding-interview-python | /src/problems/p24_merge_sorted_list.py | 1,528 | 3.59375 | 4 | """
p24_merge_sorted_list
~~~~~~~~~~~~~~
问题:合并两个排序链表
输入两个递增排序的链表,合并这两个链表并使得新链表的节点仍然是排序的。
:copyright: (c) 2017 by 0xE8551CCB.
:license: MIT, see LICENSE for more details.
"""
from src.datastructures.linkedlist.single import List, Node
from src.helpers import to_pylist
@to_pylist
def merge_t... |
ac17f95f77c0cf1060bd5f48feaa2573c1480614 | jbaisani/coding-interview-python | /src/problems/p18_delete_node_from_list.py | 1,733 | 3.609375 | 4 | """
p18_delete_node_from_list
~~~~~~~~~~~~~~~~~~~~~~~~
题目:删除链表的节点
给定单向链表的头指针和一个节点指针,定义一个函数在 O(1) 时间内删除
该节点。
:copyright: (c) 2017 by 0xE8551CCB.
:license: MIT, see LICENSE for more details.
"""
from src.datastructures.linkedlist.single import List
def delete(data, val):
if data ... |
0b5771f19abdc174131dbe1c9cf14af2e8718d76 | jbaisani/coding-interview-python | /src/problems/p25_print_matrix_cw.py | 2,264 | 3.59375 | 4 | """
p25_print_matrix_cw
~~~~~~~~~~~~~~
问题:顺时针打印矩阵
输入一个矩阵,按照从外到里,顺时针方式打印出每个元素。
:copyright: (c) 2017 by 0xE8551CCB.
:license: MIT, see LICENSE for more details.
"""
GO_RIGHT = 0
GO_DOWN = 1
GO_LEFT = 2
GO_UP = 3
def visit_matrix_in_clockwise_order(matrix, rows, columns):
"""
定义四种... |
2c2a730c9d8b64d650b0d45abbc648958105c77b | jbaisani/coding-interview-python | /src/problems/p09_impl_stack_with_two_queues.py | 1,299 | 3.734375 | 4 | """
p09_impl_stack_with_two_queues
~~~~~~~~~~~~~~
题目:使用两个队列实现一个栈
要求实现一个栈,使用两个队列模拟栈的操作,实现 `pop` 和 `push` 方法
:copyright: (c) 2017 by 0xE8551CCB.
:license: MIT, see LICENSE for more details.
"""
class Stack(object):
def __init__(self):
# 为简单起见,使用两个 `list` 容器模拟队列的操作
self... |
7b277c524e1f11e209ae644f42f6b99c08fd6faf | BrilliantGrant/Password-Locker | /test_user.py | 848 | 3.734375 | 4 | import unittest #Importing the unittest module
from user import User #Import the user class"""
class Testuser(unittest.TestCase):
"""Test class that defines test cases for the contact behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases"""
def setUp(self):
"""Set up method to ... |
c2191f214941b06a9d1acab523e72e361555a032 | rotonnn/LeetCodeRecord | /Medium/排序链表.py | 498 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head :return
val=[]
while head:
val.append(head.val)
head=hea... |
fab98b77cfcb5d61939d164e7a1851135948b6a7 | rotonnn/LeetCodeRecord | /Easy/对称二叉树.py | 526 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def z(self,l,r):
if not(l or r):
return True
if l and r and l.val==r.val:
#print(l.val,r... |
ab9afb9db13e592a1a2a78d0376a96de755707bd | rootrUW/Python210-W19 | /students/KevinCavanaugh/session2/grid_printer.py | 447 | 3.765625 | 4 | def column(a):
print("+", end=" ")
for i in range(a-1):
print("- - - - +", end=" ")
print("- - - - +")
def rows(a):
print("|", end=" ")
for i in range(a-1):
print(" |", end=" ")
print(" |")
def grid_printer(a,b):
column(a)
for i in range(b):
for ... |
86ca90fd31a09060144e0a06bf68b5423967344f | rootrUW/Python210-W19 | /students/KevinCavanaugh/session3/list_lab.py | 1,668 | 4.1875 | 4 | #!/usr/bin/env python3
# ----------------------------------------------------------------------- #
# Title: List_Lab
# Author: Kevin Cavanaugh
# Change Log: (Who,What,When)
# kcavanau, created document & completed assignment, 01/29/2019
# ----------------------------------------------------------------------- #
impor... |
180959cde04bceb9dc0a5ad79722f5b41cd400d9 | Mohon111/Learning-Python | /Lesson-2.py | 109 | 3.921875 | 4 | var1 = 5
var2 = 10
var3 = var1 + var2
print(var3)
print("Hello! I'm Mohon Basu")
print('Hello! I\'m Mohon Basu') |
636abbd36eac1f0bc491da76448ced57baa6c09d | hamiltons4/100LittlePythonPrograms | /ex66.py | 107 | 3.65625 | 4 | d = dict(weather = "clima", earth = "terra", rain = "chuva")
word = input("Enter word: ")
print(d[word])
|
6c87bc01d9ae6677fd130201d1794b7c4252e914 | hamiltons4/100LittlePythonPrograms | /ex42.py | 283 | 3.84375 | 4 | a = [1,2,3]
b = (4,5,6)
#for i, j in zip(a,b):
# print(i + j) The old way. I did it as below.
#c = zip(a,b)
#listc = list(c)
#d = map(sum, listc)
#e = list(d)
e = list(map(sum,list(zip(a,b))))
for item in e:
# print(str(item) + "\n")
print(str(item))
|
b221dd914a8e3bd4d1ae3f4d63c74f612b67b59a | hamiltons4/100LittlePythonPrograms | /ex21.py | 173 | 3.96875 | 4 | d = {"a":1, "b": 2, "c":3}
d = dict((k, v) for k, v in d.items() if v<= 1)
print(d)
#or
a = {"a":1, "b": 2, "c":3}
a = {k: v for k, v in d.items() if v <= 1}
print(a)
|
e87ed39bab0a8cbbeced825943d5ade73f77ab75 | hamiltons4/100LittlePythonPrograms | /ex46.py | 300 | 3.59375 | 4 | import string
letterString = string.ascii_lowercase
letterList = list(letterString)
my_list = list()
for i in letterList:
print(i)
ff = open(i+".txt", "r")
#a = str(f.read())
my_list.append(ff.read())
ff.close()
print(my_list)
|
aed4d6aa3e9256d4f0e43b879b23bc36a4dcab4a | JBW1997/hello-world | /数字类型.py | 640 | 4.625 | 5 | """
#分类:整数、浮点数、复数
#整数:python可以处理任意大小的整数
"""
#交互式复赋值定义变量
num1, num2 =1, 2
print(num1,num2)
#连续定义多个变量
num3 =1
num5 =num4 =num3
print(num3, num4, num5)
"""
浮点数:由整数和小数组成,浮点数可能会有四舍五入的误差
"""
f1 = 1.1
f2 = 2.2
print(f1 + f2)
"""
复数:由实部和虚部组成,a+bj
"""
#数字类型转换
print(int(1.11))
print(float(1))
print(int("12... |
e04c3046d2c0555ef9322bc5f7fe2ce7b60de575 | SHHS-Computers-Club/RandSpeech | /main.py | 3,532 | 3.65625 | 4 | from random import shuffle, randint
def main():
text, pool = '', ''
def getfile():
file = input('File? >>> ').replace('\\','/')
try:
with open(file) as f:
text = f.read()
f.closed
except:
try:
with open(file, mode='rb') ... |
1833a26337b51a51d53d9bae0c087e65896b622c | brajkowski/OregonTrail | /modules/misfortunes.py | 10,720 | 4.0625 | 4 | """
This module is responsible for all of the random events that occur in the game.
"""
import random
import puzzle
from game_io import get_input_int_protected
def randomize(player):
"""
Main entry-point for random events from the game engine.
Determines if a random event should occur and randomly selects one.
... |
31af1b6ef28c1960b3be512b89c8dbde44345fc3 | toddaulwurm/introduction | /file.py | 3,180 | 3.90625 | 4 | num1 = 42 #variable declaration, init number
num2 = 2.3 #variable declaration, init number
boolean = True #variable dec, init boolean
string = 'Hello World' #var dec, init string
pizza_toppings = ['Pepperoni', 'Sausage', 'Jalepenos', 'Cheese', 'Olives'] #list init
person = {'name': 'John', 'location': 'Salt Lake', 'ag... |
2f886bb4be9cb7b049b5ed3ab98801b4f2f67907 | maxharlow/csvbar | /csvbar.py | 2,080 | 3.5 | 4 | # coding: utf-8
import argparse
import locale
import csv
import sys
import io
import os
def main():
locale.setlocale(locale.LC_ALL, '')
try:
args = arguments()
labels, data = read(args['FILE'])
display(labels, data, args['width'])
except BaseException as e: sys.exit(e)
def argumen... |
f1674070d3ef9a7dfbe758a75b5376ab2a657e41 | hachibkhan19/algorithm | /linear_search.py | 448 | 3.640625 | 4 | pos = 0
def linear_search(lst, n):
for i in range(len(lst)): # space complexity 0(1), time complexity(n)
if lst[i] == n:
globals()['pos'] = i # best case complexity 0(1), worst case complexity 0(n)
return True # average case complexity 0(n)
... |
6ab9e9ddb8c7ea384e3a6e334c4e7a4d9d9be017 | vishalbelsare/fireflower | /fireflower/types.py | 4,893 | 3.796875 | 4 | import numpy as np
import pandas as pd
class FeatureType(object):
"""
FeatureType determines how datatypes are stored internally in Series
objects, and how they're serialized to .csv.
invariants:
- serialized representation is unique (no '1' vs '1.0')
- no type conversion occurs upon round-tr... |
ac818237e81499c145d9be5d5a4029bfb2dca191 | Elkantar-git/EdF_Python | /majuscule.py | 266 | 3.734375 | 4 | arg = input('')
argl = len(arg)
argf = ''
etape = 0
for i in range(0, argl):
etape += 1
if arg[i] == ' ':
etape -= 1
next
if etape % 2 == 0:
argf = argf + arg[i].upper()
else:
argf = argf + arg[i].lower()
print(argf) |
1ac25a1c90c8e9e141f9f0ca8a409288f78624fd | zabuchan/common | /show_history_when_matched.py | 513 | 3.53125 | 4 | from collections import deque
def show_previous_lines_when_matched(lines, pattern, previous_lines=2):
previous_lines = deque(maxlen=previous_lines)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
if __name__ == '__main__':
with open('error_log.txt', 'r') as fi... |
3e33f796f8ba09801e07d815f0468dfcf5cfc402 | GCMacarena/Experimental-stimulus-Smooth-Pursuit | /codigoestimulo.py | 6,007 | 3.796875 | 4 | import turtle
import time
# Tiempo:
def advance(angulo, sentido, distancia, pasos, espera):
if sentido == "horario":
ball.right(angulo)
if sentido == "antihorario":
ball.left(angulo)
distanciaPorPaso = distancia / pasos #cuanta distancia recorre por pasos
x = 0 #empiezo con ... |
4d99dc045167385caaf8c8a70219697913b45cb1 | iloveleejunghyun/ReinforcementLearning | /teststr.py | 189 | 3.609375 | 4 |
class A:
def __init__(self, x, y):
self.x = x
self.y = y
super().__init__()
def __str__(self):
return f"{self.x}, {self.y}"
a = A(1, 2)
print(a)
|
0d7033f7abf147dc777de44c3975924a7ba91c0b | oliverhamburger/Keypad-Door-Lock | /keypad_doorlock.py | 3,551 | 3.53125 | 4 | #servo GPIO pins
#yellow servo wire to pin 11
#orange (middle) wire to pin 4
#brown wire to pin 6
#Code Reference
#https://maker.pro/raspberry-pi/tutorial/how-to-use-a-keypad-with-a-raspberry-pi-4
#https://www.youtube.com/watch?v=xHDT4CwjUQE
import RPi.GPIO as GPIO
import time
class Number:
def __init__(sel... |
cbf5db10c2df69334efc6076cbc201712ae0768a | eykei/document_sorter | /document_sorter.py | 952 | 3.546875 | 4 | '''
description: Sorts all documents in a folder and places them into a folder based on the year it was created.
usage: specify the directory path, then run the file
status: Working
todo:
'''
import os, datetime, shutil
directoryPath="C:\\Users\\Austin\\Documents\\my documents\\old\\"
for file in os.listdir(director... |
c54e5b7aa744dc1195ad33ef3e617bfdf58c0f71 | Daky60/python-kurs | /lecture5.py | 4,323 | 4.15625 | 4 |
X = 1 ## int
Y = 4 ## int
addresses = {"Adam": "Ormvägen 5", ## dict
"Bella": "Klockgatan 1",
"Cornelia": "Vikingagatan 3"}
cars = ["Volvo", "Opel", "BMW"] ## list
numbers1 = {1, 2, 3, X, 6} ## set
numbers2 = {Y, 2, 3, 4, 7} ## set
for i in (X, Y, addresses, cars, numbers1, numbers2):
print(type(i)) ... |
9e1f90f23037372e5a40f1ae9f1478bb0327de39 | michelbl/intro-info | /meteo.py | 1,323 | 3.609375 | 4 | import requests
import json
response = requests.get("https://api.openweathermap.org/data/2.5/weather?q=Paris,fr&appid=281f2f47a07f35357ba3cefcc47c7f52&units=metric&mode=json&lang=fr")
print(response)
print(response.status_code)
print(type(response))
print(response.text)
print(type(response.text))
"""
#Exemple tiré... |
f7ed41213ad449300f2d100c7a2cbc75158d1722 | mike-233/learn_python | /testCode/passwordGenerator.py | 415 | 3.796875 | 4 |
import random
import string
def get_random_password_string(length_password) :
password_charaters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(password_charaters) for x in range(length_password))
print("Your password generator is : "+password)
n... |
ce619542d41fd7f2465eea7f4974e3c9d3c050d6 | wilfort/python | /example/typles.py | 717 | 4.375 | 4 | #
thistuple = ("apple", "banana", "cherry")
print(thistuple)
#
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
#
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
# the value is stille the same:
print(thistuple)
###################################################
###############... |
987858b722cddad7d419ca5efa67efdbbda9fc0f | MikoGD/test | /lab5_card_game.py | 6,320 | 4.03125 | 4 | """
# course: Object-oriented programming, year 2, semester 1
# academic year: 201920
# author: B. Schoen-Phelan
# date: 17-10-2019
# purpose: Lab 5 - GUI and card game using queue
"""
from tkinter import *
# to use the queue FIFO
from queue import Queue
# to use the shuffle for shuffling the cards
from random import... |
a766e4654ff24282d152cd57211fb87e798e1f58 | trietle123/pythonml | /TFANN/TFPlot.py | 3,335 | 3.59375 | 4 | '''
TFPlot.py
This file functions to plot performance of a
neural network during training.
'''
import numpy as np
import math
import matplotlib.pyplot as mpl
import matplotlib.animation as mpla
from sklearn.metrics import mean_squared_error as MSE
from sklearn.preprocessing import scale
from TFANN import MLPB
from Stoc... |
44d1876e05f6ef702ea5e472ef201eb92feee55c | saha-shyamasree/Proteomics | /Python/fileMerging.py | 775 | 3.59375 | 4 | ### This is a python script to merge 2 files. This code is used to merge ORFs file and a contaminants list.
import argparse
parser = parser = argparse.ArgumentParser(description='This is a python script to merge two files.')
parser.add_argument("-1", "--file1", help="full path of file1", metavar="File path")
parser.a... |
1d62dd60720a09b1c2b782b256f1f539c8e431da | rezabayu/sedati | /kattis-Trik.py | 270 | 3.671875 | 4 | order = input()
pos = ['Ball', None, None]
for letter in order:
if letter == 'A':
pos[0], pos[1] = pos[1], pos[0]
elif letter == 'B':
pos[1], pos[2] = pos[2], pos[1]
else:
pos[0], pos[2] = pos[2], pos[0]
print(pos.index('Ball') + 1)
|
e6d4cc906a3cd320711c29a6db976af457182725 | rezabayu/sedati | /kattis-amazingcanon.py | 626 | 3.546875 | 4 | import math
N = int(input())
def tinggi(v0, t, ang):
tinggi = v0 * t * math.sin(ang) - 0.5 * 9.81 * (t**2)
return tinggi
def waktu(x1, v0, ang):
waktu = x1 / (v0 * math.cos(ang))
return waktu
hasil = []
for i in range(N):
data = input().split(" ")
v0, ang, x1, h1, h2 = float(data[0]), float(d... |
f54b2b88344ae2e9c5b8db443dd77c2e5dda8b39 | thamilarasi43/thamilarasi | /playerarray.py | 197 | 3.84375 | 4 | def printArray(r, n1):
for i in range(0,n1):
print ("%d"%( r[i]),end=" ")
r = [243, 140, 240, 141, 142, 46, 74]
n1 = len(r)
pancakeSort(r, n1);
print ("Sorted Array ")
printArray(r,n1)
|
5f03aaf986f47b0e58aaa31cb311591f8cd92a82 | DSHero/Back_end | /文件操作05.py | 202 | 3.59375 | 4 | # 复制文件,小文件复制将file1中的内容复制到file2中
file1 = open('text1.txt', 'r')
file2 = open('text2.txt', 'w')
text = file1.read()
file2.write(text)
file1.close()
file2.close()
|
c1d8af3d5459aced974a65a55d1a266d2a0f312c | EvgenyEysner/TicTacToe | /final_tictactoe.py | 7,706 | 3.765625 | 4 | # Крестики-нолики
import random
# Вывожу на экран иснтрукцию для игрока
def playInstruct():
print(
'''
Добро пожаловать в игру Крестики-нолики!
С Вами будет сражаться компьютер.
Что бы сделать свой ход, введите цифру от 1 до 9.
Числа соответсвуют клавишам на клавиатуре:
7 |... |
50837ca962f9aa6bc9b399971c1cde8a99d79900 | RichardFlynn/KattisProblems | /provincesandgold.py | 312 | 3.984375 | 4 | gold,silver,copper=map(int,input().split())
total=3*gold+2*silver+copper
if total>7:
print("Province or Gold")
elif total>5:
print("Duchy or Gold")
elif total>4:
print("Duchy or Silver")
elif total>2:
print("Estate or Silver")
elif total>1:
print("Estate or Copper")
else:
print("Copper") |
b8694cb96de3d86147bb6abd15dc8243f56cae97 | RichardFlynn/KattisProblems | /skener.py | 230 | 3.578125 | 4 | rows,columns,newrows,newcolumns=map(int,input().split())
out=""
for r in range(rows):
outrow=""
row=input()
for c in range(columns):
outrow+=row[c]*newcolumns
outrow+="\n"
out+=outrow*newrows
print(out) |
750d09c56745bd3b714d0fdc7ad737e36f657433 | RichardFlynn/KattisProblems | /tarifa.py | 124 | 3.515625 | 4 | limit=int(input())
months=int(input())
total=limit*months+limit
for _ in range(months):
total-=int(input())
print(total) |
cc576aa8d972e749299da14bb3e68c4bb5c4083e | RichardFlynn/KattisProblems | /licensetolaunch.py | 165 | 3.625 | 4 | input()
junklist=list(map(int,input().split()))
smallest=0
for i in range(1,len(junklist)):
if junklist[i]<junklist[smallest]:
smallest=i
print(smallest) |
0ed7eed81ff1b5046b5b8edd4dcbe889605f78e7 | RichardFlynn/KattisProblems | /peg.py | 174 | 3.5 | 4 | pegboard=[' ',' ']
for _ in range(7):
pegboard.append(' '+input()+' ')
pegboard+=[' ',' ']
for line in pegboard:
print(line) |
1765cd5926e687d3c93a44f874f17ce0bd6661eb | RichardFlynn/KattisProblems | /filip.py | 127 | 3.609375 | 4 | def flip(s):
t=""
for c in s:
t=c+t
return int(t)
num1,num2=map(flip,input().split())
print(max(num1,num2)) |
61ca94748bdca02ad9d26465ef76a89c004cf26d | guanchanglong/python | /python学习1.3(列表与循环的运用).py | 1,131 | 3.96875 | 4 | #a=['x','y','z']
#for a in a: #for循环后面的冒号不要忘记
#for循环每次输出列表的一个元素
# print(a)#缩进很重要,忘记缩进和不必要的缩进都会造成错误
#a=[1,2,3,4,5,6]
#for b in range(1,6): #range函数
# print(b)
#num=list(range(1,6))#函数list将range的结果直接转化为列表,生成一个数字列表
#print(num)
#num1=list(range(50 , 100 , 2))
#开始 结束 步长
#print(num1)
#sq... |
a65c82105d0f37eed1364b4b42e330a5467df5aa | Ti1mmy/sorting-algorithms | /main.py | 331 | 3.84375 | 4 | def swap(a, b):
temp = my_list[a]
my_list[a] = my_list[b]
my_list[b] = temp
my_list = [1, 3, 5, 8, 2, 9, 7, 3, 4, 1, 6]
for i in range(len(my_list)):
min_index = i
for j in range(i + 1, len(my_list)):
if my_list[min_index] > my_list[j]:
min_index = j
swap(i, min_index)
pri... |
f5802a508ec28e1b7fdb7ad931687c8b99d216d1 | BardisRenos/Algorithms | /Plus_Minus_Count.py | 460 | 3.921875 | 4 |
arr = [2, 3, 6, 0, 0, -9, -8]
def plus_minus_count(arr):
count_positive = 0
count_zero = 0
count_negative = 0
for i in arr:
if i < 0:
count_negative += 1
elif i > 0:
count_positive += 1
else:
count_zero += 1
return cou... |
cbfa5c716c231ee09cfd3786fd32f677e318eba4 | pandyakavi/Data-Structure | /Decimal_to_Binary.py | 390 | 3.625 | 4 | from Stack_Class import Stack_Class as stack
#dividend / divisor = quotient
#12 / 3 = 4
remainder = stack()
dividend = int(raw_input())
divisor = 2
while dividend//divisor >= 0:
if dividend == 0:
break
else:
remainder.Push(dividend%divisor)
dividend//= divisor
remainder.Print()
sum=0
for i in range(rema... |
91a2d20bac726e7a65d08651eac5950dab74d416 | MatthewKosloski/starting-out-with-python | /chapters/05/15.py | 518 | 3.71875 | 4 | # Program 5-15
CONTRIBUTION_RATE = 0.05 # global constant
def main():
gross_pay = float(input('Enter gross pay: '))
bonus = float(input('Enter bonus: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
def show_pay_contrib(gross):
contrib = gross * CONTRIBUTION_RATE
print('Contribution for gross pay: $'... |
7d08b0746a4b0d83c7cb5d4e32c817a214900670 | MatthewKosloski/starting-out-with-python | /chapters/11/vehicles.py | 1,661 | 3.765625 | 4 |
# Program 11-1
class Automobile:
def __init__(self, make, model, mileage, price):
self.__make = make
self.__model = model
self.__mileage = mileage
self.__price = price
def set_make(self, make):
self.__make = make
def set_model(self, model):
self.__model = model
def set_mileage(self, mileage):
sel... |
3360acb61d90f26d049f1864d7c5c826476ad0b8 | MatthewKosloski/starting-out-with-python | /chapters/10/04.py | 361 | 3.953125 | 4 | # Program 10-4
# This program imports the coin module and
# creates an instance of the Coin class.
import coin
def main():
my_coin = coin.Coin()
print('Side facing up:', my_coin.get_sideup())
# Toss the coin
print('I am going to toss the coin ten times:')
for toss in range(10):
my_coin.toss()
print('Toss'... |
31a8e5477e67a0dce340298786ca799938f635bc | MatthewKosloski/starting-out-with-python | /homework/line_numbers/line_numbers.py | 407 | 3.796875 | 4 | # Matthew Kosloski
# Exercise 6-3
# CPSC 3310-01 SP2018
def main():
filename = input('Name of the file: ')
try:
infile = open(filename, 'r')
result = ''
current_line = 1
for line in infile:
result += f'{current_line}: {line}'
current_line += 1
infile.close()
except IOError:
print(f'Failed t... |
54e2053097d2bb36af79e38490d90be6586cc81e | MatthewKosloski/starting-out-with-python | /chapters/06/09.py | 273 | 3.515625 | 4 | # Program 6-9
# Reads all values in the sales.txt file
def main():
sales_file = open('sales.txt', 'r')
line = sales_file.readline()
while line != '':
amount = float(line)
print(format(amount, ',.2f'))
line = sales_file.readline()
sales_file.close()
main() |
9bf185e97b1c81a0ac4fe3dd7166db777cb7a032 | MatthewKosloski/starting-out-with-python | /chapters/07/03.py | 371 | 4.59375 | 5 | # Program 7-3
# Demonstrates how the append
# method can be used to add
# items to a list.
def main():
name_list = []
again = 'y'
while again.lower() == 'y':
name = input('Enter a name: ')
name_list.append(name)
again = input('Add another name? (y/n): ')
print()
print('Here are the names you entered... |
3ae72ab5b4b40599ca663c2e1c1eadbdc34904dc | MatthewKosloski/starting-out-with-python | /chapters/03/06.py | 539 | 4.34375 | 4 | # Program 3-6
# This program gets a numeric test score from the
# user and displays the corresponding letter grade.
# Variables to represent the grade thresholds
A_score = 90
B_score = 80
C_score = 70
D_score = 60
# Get a test score from the user.
score = int(input('Enter your test score: '))
# Determine the grade.... |
86af468a7861d37abfbf0c345ba4db77fb2d508f | MatthewKosloski/starting-out-with-python | /chapters/05/04.py | 157 | 3.796875 | 4 | # Program 5-4
# Local variable error demo.
def main():
get_name()
print('Hello', name) # Error
def get_name():
name = input('Enter your name: ')
main() |
ef3fca65a2e5701628ad968b9be7c358dbb95325 | MatthewKosloski/starting-out-with-python | /chapters/06/13.py | 710 | 4.125 | 4 | # Program 6-13
# Gets employee data from the user and
# saves it as records in the employee.txt file.
def main():
number_of_employees = int(input('How many employee records' +
'do you want to create? '))
employee_file = open('employees.txt', 'w')
# Get each employee's data and
# write it to employees.txt
... |
519ce83fed6f9df3bc17c810db2c6ffacd79d397 | MatthewKosloski/starting-out-with-python | /homework/factorial.py | 415 | 4.1875 | 4 | # Matthew Kosloski
# Exercise 4-11
# CPSC 3310-01 SP2018
num = int(input('Enter a number >= 0 for factorial: '))
while num != -1:
# Calculate and display factorial if number is >= 0
if num >= 0:
factorial = 1
for i in range(1, num + 1):
factorial *= i
print('Factorial of', num, 'is', factorial)
prin... |
7df30941d588d01e2e1adb68f19e7889b016c2ac | MatthewKosloski/starting-out-with-python | /chapters/06/16.py | 391 | 3.828125 | 4 | # Program 6-16
# Displays coffee.txt records.
def main():
coffee_file = open('coffee.txt', 'r')
description = coffee_file.readline()
while description != '':
quantity = float(coffee_file.readline())
description = description.rstrip('\n')
print('Description:', description)
print('Quantity:', quantity)... |
5bee66cb2090e4b9dba3669b3aae497b9a42227d | MatthewKosloski/starting-out-with-python | /chapters/06/23.py | 375 | 4.125 | 4 | # Program 6-23
# Handles a ValueError exception.
def main():
try:
hours = int(input('How many hours did you work? '))
pay_rate = float(input('Enter your hourly pay rate: '))
gross_pay = hours * pay_rate
print(f"Gross pay: ${format(gross_pay, ',.2f')}")
except ValueError:
print('ERROR: Hours worked and h... |
d43e8b23538cf42f944943865fa14593c29b8071 | MatthewKosloski/starting-out-with-python | /chapters/04/12.py | 446 | 4.4375 | 4 | # Program 4-12
# This program calculates the sum of a series
# of numbers entered by the user.
# The maximum number
max = 5
# Initialize the accumulator
total = 0
# Explain the purpose of the program
print('This program calculates the\nsum of',
max, 'numbers you will enter.\n')
# Get the numbers and accumulate them... |
30bd227c3394fc4f470e851c54f9a2740e4068ed | MatthewKosloski/starting-out-with-python | /chapters/07/07.py | 508 | 4.15625 | 4 | # Program 7-7
# Calculates the gross pay for each
# barista.
NUM_EMPLOYEES = 6
def main():
hours = [0] * NUM_EMPLOYEES
for index in range(NUM_EMPLOYEES):
print('Enter the hours worked by employee ', \
index + 1, ': ', sep='', end='')
hours[index] = float(input())
pay_rate = float(input('Enter the hourly p... |
441bee12976cb345a05b93a4d6f7e212352e9217 | MatthewKosloski/starting-out-with-python | /chapters/04/01.py | 632 | 4.15625 | 4 | # Program 4-1
# This program calculates sales commissions.
# Create a variable to control the loop
keep_going = 'y'
# Calculate a series of commissions
while keep_going == 'y':
# Get a salesperson's sales and commission rate.
sales = float(input('Enter the amount of sales: '))
comm_rate = float(input('Enter the co... |
4ffbf0b30ca6ce1ce180c183490e572d4bea1e19 | arrgee23/NLP | /server.py | 2,919 | 3.578125 | 4 | #!/usr/bin/env python2
"""
Very simple HTTP server in python.
Usage::
./dummy-web-server.py [<port>]
Send a GET request::
curl http://localhost
Send a HEAD request::
curl -I http://localhost
Send a POST request::
curl -d "foo=bar&bin=baz" http://localhost
"""
from BaseHTTPServer import BaseHTTPRequestHa... |
3e419d7848bae0579e3cf256a7584cfa7e6493e9 | vinodsake/Instruction-Set-Architecture-Simulator-for-PDP-11 | /fetch_file.py | 1,731 | 3.515625 | 4 | '''
File: Fetch.py
Purpose:
Get the start address from the user if not specified
Fetch the instruction
Update the PC
Call Execute Function
'''
import loader_file
import memory_access
from memory_access import *
# Importing Global variables from loader
start_address_identify = loader_file.start_a... |
29fa4c90735f42f443e88214bfc19c1ccfa78b6e | vandreschaedler/learning_python | /007formattingString.py | 369 | 3.578125 | 4 | """
string,
integer,
float
bool
"""
nome = 'Vandré'
print(nome, type(nome))
idade = 37
print(idade, type(idade))
altura = 1.76
print(altura, type(altura))
peso = 92
print(peso, type(peso))
imc = peso / (altura**2)
print(f'{nome} tem {idade} anos de idade e seu imc é: {imc:.2f}')
print('{} tem {} anos de idade ... |
f4f22956256b6573e4b3d6c9e84ef0db80f056a8 | vandreschaedler/learning_python | /008entryData.py | 192 | 3.6875 | 4 | nome = input('Qual o seu nome? ')
idade = input('Qual a sua idade? ')
ano_nascimento = 2019 - int(idade)
print(f'Nome do usuário é {nome} e sua idade {idade}, nascido em {ano_nascimento}.') |
623305636b6eabf818bdc6e4ad67cf45d15d2208 | AnthonySDi/python-fizzbuzz | /main.py | 758 | 4.34375 | 4 | def fizzBuzz(num):
'''
Receives num from main and determines if it is divisable by 3, 5, or both and prints the int with fizz, buzz, or fizzbuzz respectfully.
helper function to main()
keyword arguments:
num: int
'''
if(num % 3 == 0 and num % 5 == 0):
#num is divisable by both 3 and 5
print(s... |
4bc839e35a312925a9861d396935f8382f8460ea | mjk-git-code/mjk-python-code | /my.py | 174 | 3.71875 | 4 | #my.py
name = input("What your name?")
name = 'Old user' if name == 'MJK' else 'New user'
print(name)
#等价于:
#if(food == 'lamb'):
# reply = 'yuck'
#else:
# reply = 'yum' |
1a90ce09acecbc49594df22079bf00a5ff8562e7 | Sidhi186/my-first-blog | /Test.py | 157 | 3.625 | 4 |
def hi(qw):
print('Привет, ' + qw + '!')
girls = ['Лиза','Соня','Леня','Оля','Monica','You']
for i in range(1, 8):
print(i)
|
5041b58737f4e19eddcd0338db5dcdf290590ecf | 8L4NK/CrabStick | /src/common.py | 669 | 3.578125 | 4 | def yes_no(response, recomended):
"""Chooses between True and False based on user response to a runtime question"""
first_char = response[0].lower()
if first_char == "y":
return True
if first_char == "N":
return False
if first_char is None:
return yes_no
else:
ret... |
5a89044633c32e3492b8db457230b5dac405beca | jjmosca/cs50 | /PS6/mario.py | 768 | 4.09375 | 4 | from sys import exit
from cs50 import get_int
def main():
# Ask user for pyramid height (must be from 1 to 8)
while True:
height = get_int("Height: ")
if height >= 1 and height <= 8:
break
pyramid(height)
def space(l): # Function that prints n number of spaces
print(" " ... |
91bb43e8692e88cede2b0374718305fef59da68c | wysockilukas/excelsheet2html | /excelsheet2html/core.py | 3,835 | 3.65625 | 4 | """Read excel file and convert it to html string"""
import openpyxl
import excelsheet2html.helper_functions as my_func
from excelsheet2html.stylesheet.stylesheet import StyleSheet
from excelsheet2html.dom.dom import DOM
from excelsheet2html.config.config import MyGlobals
import excelsheet2html.config.config as config
... |
0555c6d1cb8a22878790b6192fd4d3484a2e6c3a | markccchiang/synchrotron-motion-simulator | /track-electron.py | 1,658 | 3.515625 | 4 | #!/usr/bin/env python
from math import *
import numpy as np
import matplotlib.pyplot as plt
import BasicFunc as func
import Input as para
#################################################################################
num_of_turns = para.app3_num_of_turns # total number of turns for a ramping cycle
#################... |
0e9757b96c72c5ac70ae3bf16135e4eeb25cf826 | a92920/recommender_systems | /recommender_system_project/recommmender_system_project/recommender_system_base.py | 6,016 | 4.0625 | 4 | from abc import ABC, abstractmethod
import pandas
class RecommenderSystemBase(ABC):
"""The base class for the recommender system
Attributes
----------
movies_dataframe : pandas.DataFrame
A dataframe with all the movies metadata (movies_metadata, keywords, credits, descriptions, etc).
... |
f0e24ab088e66b24dd86af3122fd5332408dc63e | SyedTanzimAlam/Machine_Learning_with_scikit_learn | /loocv.py | 678 | 3.5 | 4 | """@author: Tanzim"""
# Evaluate using Leave One Out Cross Validation
import pandas as pd
filename = "PUT THE .csv file"
colnames = ['Column names in quotes seperated by comma']
dataset = pd.read_csv(filename, names=colnames).values
# separate array into input and output components
X = dataset[:,0:8] # rows:columns
Y =... |
e8450f3324e01b1ed17d8a5bfccbc38eb0711db7 | SyedTanzimAlam/Machine_Learning_with_scikit_learn | /training_and_testing.py | 692 | 3.640625 | 4 | """@author: Tanzim"""
# Evaluate using a train and a test set
import pandas as pd
filename = "PUT THE .csv file"
colnames = ['Column names in quotes seperated by comma']
dataset = pd.read_csv(filename, names=colnames).values
# separate array into input and output components
X = dataset[:,0:8] # rows:columns
Y = dataset... |
05f0578d150f7fc9eb4ce6ae57fe85694657b098 | SahilBastola/lab_exercise | /question no 8.py | 242 | 4.375 | 4 |
#write a python program which accepts the radius of a circle from the user and compute the area (area of circle = pier**2
radius=float(input("Enter the value of radius:"))
pie= 22/7
area = pie*radius**2
print(f"the area of circle is {area}") |
24a031fcf33d039c92cf9b37fdd57d25ec5e5d7b | VarthanV/Basic-Python-Files | /dict.py | 887 | 3.96875 | 4 | new={'jen':'c', 'bob':'Python','joe':'java'}
for name,lan in new.items():
print(name.title()+ "likes"+lan)
if(new['jen']=='c'):
print('True')
else:
print("False")
n={'jen':[20,163,'introvert'],'joe':[13,152,'extrovert']}
for name ,details in n.items():
print(name.title() +" "+ "is")
for detail in details:
pri... |
3efac74987d0246f44a8911a5a9d9a62034ad280 | VarthanV/Basic-Python-Files | /test1.py | 269 | 3.890625 | 4 | current_users=['pavan','rahul','rajaram','harish','chinni']
newusers=['chinni','pavan','aa','b','cc']
for user in newusers:
if(user in current_users):
print(user+"re enter a new name")
if(user not in current_users):
print(user+"it i available")
|
0522e1f13c3c14c661d349b52d96bb28217a18dd | VarthanV/Basic-Python-Files | /ad.py | 316 | 3.546875 | 4 | from user import User
class Admin(User):
def __init__(self,name,age,height,attempts):
super().__init__(name,age,height,attempts)
def privileges(self):
if(self.name=='admin'):
priv=['Can add','can edit','can post']
for prop in priv:
print(prop)
else:
print("no homie no previliges for u")
|
458d922a72a855df57a7f3812f5aa2f05a446431 | VarthanV/Basic-Python-Files | /movie.py | 874 | 4.03125 | 4 | name=input("Enter your name")
age=int(input("Enter your age"))
if(age<3):
print(name.title()+",you are free to go")
elif(age<=12):
print(name.title()+"ticket costs 10 dollars")
elif(age>12):
print(name.title()+"ticket costs 15 dollars")
print("Enjoy the movie")
top=""
tomato=False
while... |
d70a8c3c77e0a2125ae251ae797e7d0e391bc153 | VarthanV/Basic-Python-Files | /testo.py | 4,509 | 4.03125 | 4 | x=[1,2,3,4,5,6]
for i in range (0,len(x)):
print(x[i])
magicians =['alice','beacon','pork','shit']
for a in magicians:
print(a)
for a in magicians:
print(a.title()+"that was a great trick")
print(a.upper()+"please do the next trick i can't wait\n")
animals=['cat','Tiger','Cheetah']
for animal in animals:
print(a... |
307e4ca82c543e16d29d03cf9631961218c409ab | johnkirch123/python | /udemy-mega-course/exercises/forIteration.py | 303 | 4.21875 | 4 | def celsius_to_farenheit(c):
if c > -273.15:
return c * 9/5 + 32
else:
return "Impossible temperature."
#print(celsius_to_farenheit(float(input("Enter Celsius for conversion: "))))
temperatures=[10, -20, -289, 100]
for temp in temperatures:
print(celsius_to_farenheit(temp))
|
ddf8461526aab57d94af72bea371f9ef579b7e78 | lilijo6/python-challenge | /PyPoll/main.py | 2,497 | 3.84375 | 4 | #Importing the applications that are needed to open the resource file and calculating months
import os
import csv
#defining the path for the file
csvpath = os.path.join("..","Pypoll", "Resources", "election_data.csv")
#Setting the initial values
votes = {}
total_votes = 0
candidate_vote_percentage = []
maxValue = 0
... |
be1bcbb2118d393a7d7a6cfc86fe2562dc1db529 | dfds/python-for-absolute-beginners | /doc_examples.py | 1,123 | 4.3125 | 4 | #!/usr/bin/env python3
class Person:
"""
This class defines a person ;)
"""
def __init__(self, name: str, age: int) -> None:
"""
This is the class constructur.
:param name: The person's name.
:param age: The person's age.
:type name: str
:type age: int
... |
df322ff4d8e34548d2b2b3d870c623d25e9e6c21 | hacktoolkit/django-htk | /utils/maths/trigonometry.py | 323 | 3.859375 | 4 | # https://en.wikipedia.org/wiki/Trigonometry
# Python Standard Library Imports
import math
def deg2rad(degrees):
"""Degrees to radians
"""
radians = math.pi * degrees/180.0
return radians
def rad2deg(radians):
"""Radians to degrees
"""
degrees = 180.0 * radians / math.pi
return degre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.