blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1aa3e2e6cddc9823ce4d526748daec1f2f05e0c3 | Mintri1199/CS2.2 | /graph_tests.py | 7,333 | 3.65625 | 4 | from graph import Graph, Vertex
import unittest
class VertexTests(unittest.TestCase):
def setUp(self):
self.vertex = Vertex("A")
def test_init(self):
assert self.vertex.id is 'A'
assert not self.vertex.neighbors
def test_add_neighbor(self):
# Adding a neighbor
ne... |
1e177b2b58dcb0692f24540f1c9f619f5940a535 | guoweifeng216/pythonlearn | /checkio/Absolute_Sorting.py | 570 | 3.5 | 4 | #coding=utf-8
"""
@athor:weifeng.guo
@data:2018/12/13 10:46
@filename:Absolute_Sorting
"""
def checkio(tuple_num):
tuple_list = []
abs_tmp = []
for i in range(len(tuple_num)):
if tuple_num[i] < 0:
tuple_list.append(abs(tuple_num[i]))
abs_tmp.append(abs(tuple_num[i]))
... |
2e25d7e4b46caa08928b017a8c4b140a119d6775 | guoweifeng216/pythonlearn | /day3/string.py | 892 | 4 | 4 | name = "mary"
#name.capitalize()#首字母大写
#name.count(a)#统计a出现的次数
print(name.center(50,"-"))
print(name.endswith("ry"))
print(name.expandtabs())
print(name.find("a"))
print(name.format(name='alex',year=23))
print(name.format_map({'name':'alex','year:12'}))
'abc'.isalnum()#阿拉伯数字
'abx123'.isalpha()
'12a'.isdecimal()
'1a'.is... |
8dda66526bf711a8e8d806906abc626e7777808b | guoweifeng216/pythonlearn | /python_design/dict_count.py | 1,153 | 4.125 | 4 | def main():
listWords=formListWords("Greeting.txt")
freq=createFrequencyDictionary(listWords)
displayWordCount(listWords,freq)
dispalyMostCommonWords(freq)
def formListWords(filename):
infile=open(filename)
originalLine=infile.readline().lower()
line=""
for ch in originalLine:
i... |
cd23563127fd3586d084072447a66c0ab581613a | guoweifeng216/pythonlearn | /checkio/find_same.py | 501 | 3.5625 | 4 | def checkio(list1):
len_list=len(list1)
len0=len(list1[0])
len1 = len(list1[1])
len2 = len(list1[2])
list2=list1
list3=zip(*list1)
print list3
if len0==3 and len1==3 and len2==3 and len_list==3:
for word in zip(*list1):
if word[0]==word[1]==word[2] and word[0]!='.':
... |
58bafd00bc4a07c356fbcb9218eb1aef9cdd29ba | guoweifeng216/pythonlearn | /checkio/check_word.py | 496 | 4.0625 | 4 | def count_words(srinng1,tupple1):
srinng1=srinng1.lower()
count_word=0
for word in tupple1:
if (word in srinng1):
count_word=count_word+1
print count_word
return count_word
# count_words()
count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"})
count_words("Bana... |
e7d5ad8e33189d6a97816cd6bbc3fb5bb6564a8f | guoweifeng216/pythonlearn | /day1/homework2.py | 551 | 3.578125 | 4 | import codecs
_username = "weifeng"
_password = "abc123"
#username = input("username:")
#password = input("password:")
cnt=0
while cnt < 3:
username = input("username:")
password = input("password:")
with codecs.open("log.txt","a+") as f:
f.write(username+'\n')
if _username ==username an... |
fa6b7161bd281d839199bdbacab871566bb0b450 | mklanglois/cracking-the-coding-interview | /Ch 1 - Arrays and Strings/1.1 - isUnique/isUnique.py | 638 | 4.3125 | 4 | # 1.1.) Implement an algorithm to determine if a string has all unique
# characters. What if you cannot use additional data structures?
# Clarifying Questions:
# - What set of characters does the input string contain?
def isUnique(str):
charList = [] # list containing all unique characters of str
f... |
f02be011a11f50b360aada1e2faee03f05f949bf | ebanner/project_euler | /amicable.py | 697 | 3.65625 | 4 | import math
def proper_divisors(n):
divisors = []
for divisor in range(1,int(math.sqrt(n))+1):
if (n % divisor == 0):
divisors.append(divisor)
if (divisor != math.sqrt(n) and divisor != 1):
divisors.append(int(n/divisor))
return divisors
def d(n):
total ... |
caccf248b6575c18eac971ca40b6939af6d5b2a2 | james-j-obrien/ENGG1000-CompSci-Simulator | /tester.py | 626 | 3.78125 | 4 | import draw, lines
import random
def randPoint(x1, x2, y1, y2):
return (random.randint(x1, x2), random.randint(y1, y2))
def randLine(x1, x2, y1, y2):
return (randPoint(x1, x2, y1, y2), randPoint(x1, x2, y1, y2))
TILE = 50
for row in range(-10, 10):
for col in range(-10, 10):
a = ran... |
059b53c6dd970142f95695b69381db530e2ff001 | dawidstrom/celautomap | /board.py | 4,347 | 3.953125 | 4 | import random as rand
import pdb
# Arbitrarily named tiles, '*' denotes an empty tile.
#tile_types = ['*', '1', '2', '3', '4', '5', '6']
tile_types = ['*', '1', '2']
class Board:
def __init__(self, size):
#self.board = self.__rand_board(size)
self.board = self.__perlin_board(size)
def evolve(... |
d7f6a6d3fb358b194c470c07a4b06023a262f6c7 | flyupwards/python3_source_code | /ch03a/ex0312.py | 242 | 3.625 | 4 | name = input("请输入姓名:")
# score1为数值,需要参与数学计算,使用eval()函数
score1 = eval(input("请输入科目1成绩:"))
score2 = eval(input("请输入科目2成绩:"))
print("\n您的总成绩是:", (score1 + score2))
|
de371b6427892f58d508a0233dd6e6f63327278c | flyupwards/python3_source_code | /ch07a/ex0709.py | 621 | 3.625 | 4 | class DemoClass2:
def __init__(self, year=0, month=0, day=0):
self.day = day
self.month = month
self.year = year
@classmethod
def get_date(cls, string_date):
# 第一个参数cls, 表示调用当前的类名
year, month, day = map(int, string_date.split('-'))
date1 = cls(year, month, da... |
bf687c1d64afa75706a0786045eef7e84bdd5da8 | flyupwards/python3_source_code | /ch04a/ex0406.py | 283 | 3.984375 | 4 | # program0308.py
'''计算1!+2!+……+5!'''
def factorial(n): # 计算阶乘的函数
t = 1
for i in range(1, n + 1):
t = t * i
return t
# 计算阶乘和
k = 6
sum1 = 0
for i in range(1, 6):
sum1 += factorial(i)
print("1!+2!+……+5!=", sum1)
|
a8fde3578ff9ece039cf4616d33403218d96ab74 | flyupwards/python3_source_code | /ch03a/ex0305.py | 749 | 3.75 | 4 | print(r'\n')
print('a\nc')
print(b'123')
print(bin(8))
print(bin(123).replace("0b", ""))
a = "Hello"
b = " Python"
print(a + b)
print(a * 2)
print(a[1])
print(a[1:4])
print('H' in a)
print('M' not in a)
print(r'\n')
str1 = "Hi,Python!"
# str1重复显示两次,str1未发生变化
print(str1 * 2)
# 测试str1在内存中的标识
print(id(str1), str1)
... |
996618483bd4e4956f625be6c9d46534b5a78993 | flyupwards/python3_source_code | /ch06a/ex0617.py | 163 | 3.65625 | 4 | # program0517.py
def factorial(i):
"求指定参数的阶乘"
t = 1
for i in range(1, i + 1):
t *= i
return t
print(factorial(6)) # 720
|
8d04bc5b1df2b58b36fcc988216580ac72136227 | flyupwards/python3_source_code | /ch03a/ex0311.py | 542 | 4.125 | 4 | str1 = "hi, Python, hi, Java!"
print(str1)
print(str1.split()) # 默认使用空格做分配符,str1中无空格,列表中只有一个元素
print(str1.split(",")) # 使用逗号做分配符,3个逗号,分隔3次
print(str1)
print(str1.split(",", 2)) # 使用逗号做分配符,限制分隔2次
lst = ['sfg', ' Python', 'hsfgi', 'Java! ']
s = '' # 空字符
s2 = ' ' # 空格
print(lst)
print(s.join(lst)) # 将列表连接为字符串
pr... |
882e93dd6956f9fc2ff286244aac69aee8f44106 | flyupwards/python3_source_code | /ch09a/ex0914.py | 378 | 3.65625 | 4 | # program0714.py
import os, os.path, sys
fname = input("请输入需要更名的文件:")
gname = input("请输入更名后的文件名:")
if not os.path.exists(fname):
print("{}文件不存在".format(fname))
sys.exit(0)
elif os.path.exists(gname):
print("{}文件已存在".format(gname))
sys.exit(0)
else:
os.rename(fname, gname)
print("rename success")
|
afa2fc9ce18c97694f4b8a1be9b56ed7d0b0eb28 | flyupwards/python3_source_code | /ch05a/ex0518.py | 617 | 3.53125 | 4 | # program0418.py
list1 = [1, 42, 3, -7, 8, 9, -10, 5]
# 二分查找要求查找的序列时有序的,假设是升序列表
list1.sort()
print(list1)
find = eval(input("请输入要查看的数据:"))
low = 0
high = len(list1) - 1
flag = False
while low <= high:
mid = int((low + high) / 2)
if list1[mid] == find:
flag = True
break
# 左半边
elif list... |
46ac6f2762e4e651348499eea3496620d2735530 | pyDiablo/password_generator | /p_gen.py | 1,623 | 4.3125 | 4 | """
Password Generator
Written by: @pyDiablo
Help Provided by: u/JohnnyJordaan and u/CommonConsistent525
Generates a password of a given length
and copies it to the clipboard.
"""
import secrets
import pyperclip
import sys
# Constants
CHARACTER_SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop... |
368ecf81af1e83144f66a8aba95626ba22cda1c2 | karlfinnerty/vector | /vector_test_1.py | 746 | 3.984375 | 4 | from vector import Vector
def components():
a = []
print("Please enter 3 digits to initialize the vector (if the vector has only 2 components, enter third input as 0).")
n = input()
while n != '' and len(a) < 3:
a.append(float(n))
n = input()
if len(a) == 3:
z = a[2]
y = a[1]
x = a[0]
re... |
37dee639190516a48ef5da28ec61efe4bdcb7566 | snagarajugari/TicTacToe | /ticTacToe.py | 5,934 | 4.28125 | 4 | print('Welcome to Tic Tac Toe!');
"""
This function asks whether to start the game.
Use while loop to continually ask until we get a correct answer.
"""
def start_game():
while True:
response = input('Do you want to start the game, Yes or No?' );
if response.lower() == 'yes':
... |
6ea268848958a177c8aaddabdfb48311f20b7fe1 | sathishmanthani/python-intro | /code/Assignment_8.1.py | 3,163 | 4.46875 | 4 | # Course Name: Introduction to Programming DSC510
# Date: 7/27/2019
# Author: Sathish Manthani
# Description: This program will read data from a file and Calculates total words in it. It also calculates number of occurrences of each word and writes it to given output file.
# Usage: This program reads from Gittysburg.tx... |
b9d7594459f9e901ef06d51e13120dc4cb4c4bbc | sathishmanthani/python-intro | /code/files.py | 477 | 3.96875 | 4 |
file1 = open('test_file.txt', 'r')
print(file1.read())
#for i in range(5):
# file1.write("This is line %d\r" %(i+1))
file1.close()
# Python code to illustrate context manager
with open("test_file.txt") as file:
contents = file.read()
print(contents)
with open("test_file.txt") as file:
contents = file... |
06b23218f7e52e5ead1610dd276f226ad88d67a4 | tareqmahmud/Competitive-Programming | /HackerRank/30-Days-of-Code/Day 3: Intro to Conditional Statements/condition.py | 503 | 4.15625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
"""
If N is odd, print Weird
If N is even and in the inclusive range of 2 to 5, print Not Weird
If N is even and in the inclusive range of 6 to 20, print Weird
If N is even and greater than , print Not Weird
"""
if __name__ == '_... |
c99a3f990b52b6bace3ab8e1fd016528098f238f | tareqmahmud/Competitive-Programming | /HackerRank/HackerRank-Python/Introduction/Arithmetic Operators.py | 257 | 3.953125 | 4 | if __name__ == "__main__":
number1 = int(input())
number2 = int(input())
# Sum of two numbers
print(number1 + number2)
# Difference of two numbers
print(number1 - number2)
# Product of two numbers
print(number1 * number2)
|
96ddb074441ac7c104ab9f9e841efa6c3926ff63 | tareqmahmud/Competitive-Programming | /HackerRank/HackerRank-Python/Strings/Text Wrap.py | 251 | 3.8125 | 4 | def wrap(string, max_width):
count = 0
return_string = ""
for word in string:
if count == max_width:
return_string += "\n"
count = 0
return_string += word
count += 1
return return_string
|
c5ad9ab5c023bf137e722ffb00d41d2c8a99ea0e | enochgeorge9x9/automate-the-boring-stuffs-with-python | /Part I/Exercise8 Practice Questions ch2.py | 1,289 | 3.953125 | 4 | '''
1. True and False
2. and, or, not
3.
True and True = True
True and False = False
False and True = False
False and False = False
True or True = True
True or False = True
False or True = True
False or False = False
not True = False
not False = True
4.
False
False
True
False
False
True
5. < ... |
7ced9642d8ece8183f23d9e33e2e81715e181b6c | tonumikk/Learn-Python | /taxi_meter.py | 508 | 3.734375 | 4 | # Taxi meter exercise
class TaxiMeter():
def __init__(self, milesTraveled):
self.miles = milesTraveled
def getFare(self):
print "Your trip was %r miles long" % self.miles
print "...and it cost you %r dollars" % (self.miles * 3)
while True:
question = raw_input("Wou... |
2ab0bc386945780b6a2c2154ff82e276bdc351be | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex013.py | 158 | 3.671875 | 4 | SALARIO = float(input('Digite o salário atual do funcionário:'))
print('Após o aumento, o salário do funcionário passou a ser R$ %.2f' % (SALARIO*1.15))
|
7d50b773888068d09ac868d11093817e877ac002 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex074.py | 258 | 3.5 | 4 | from random import randint
LIST = randint(0, 999), randint(0, 999), randint(0, 999), randint(0, 999), randint(0, 999)
print(f'Os números sorteados foram: {LIST}')
print(f'O menor número sorteado foi {min(LIST)} e o maior número sorteado foi {max(LIST)}')
|
437184103c21bf4e887e1cbad8386b7779753a98 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex075.py | 561 | 4.03125 | 4 | print('Você vai digitar quatro números')
LISTA = (int(input('Digite o primeiro número:')),
int(input('Digite o segundo número:')),
int(input('Digite o terceiro número:')),
int(input('Digite o quarto número:')))
print(f'O número 9 apareceu {LISTA.count(9)} vezes')
if 3 in LISTA:
print(f'O... |
274940ba440fdd443e397815d042569637821d79 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex041.py | 376 | 3.96875 | 4 | import datetime
DATA = datetime.datetime.now()
ANO = int(input('Digite o ano de nascimento do atleta:'))
D = DATA.year - ANO
if D <= 9:
print('Sua categoria é MIRIM!')
elif D <= 14:
print('Sua categoria é INFANTIL!')
elif D <= 19:
print('Sua categoria é JUNIOR!')
elif D <= 20:
print('Sua categoria é SÊN... |
74e494595ee5ac4a51dc5a4877e9489e01f7ae52 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex048.py | 254 | 3.65625 | 4 | s = 0
C = 0
for c in range(1, 500, 2):
if c % 3 == 0:
s = s + c
C += 1
print('O somatório entre todos os números ímpares que são multiplos de 3')
print('e que se encontram no intervalo entre 1 até 500 é: {}'.format(s))
print(C)
|
773fffe2296bf51fedde0323d910e5d2f5c6d544 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex083.py | 446 | 3.703125 | 4 | EXP = list(input('Digite uma expressão:'))
P1 = P2 = c = 0
while c < len(EXP):
if EXP[c] == '(':
P1 += 1
elif EXP[c] == ')':
P2 += 1
c += 1
if P2 > P1:
print('Parenteses em ordem incorreta')
quit()
if P1 > P2:
print('Há mais parenteses abertos do que fechados')
elif P... |
54257c1bca0094c7d96102e09ae9c74b62e23d24 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex096.py | 488 | 3.9375 | 4 | def area(b, h):
a = (b * h).__round__(2)
print(f'A largura do terreno vale {b}m e o comprimento vale {h}m')
print(f'A Área do terreno é igual a {a}m²')
linha()
def linha():
print('-' * 80)
linha()
print(f"{'Boa Tarde! Nesse Programa iremos calcular a área de um terreno':^80}")
linha()
L = float(... |
a8c9c125da19a707513a108872f34c717ab088da | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex030.py | 254 | 3.921875 | 4 | N = int(input('Digite um valor inteiro diferente de zero:'))
if N == 0:
print('Eu falei diferente de 0 seu doente!')
else:
if (N % 2) == 1:
print('O número {} é impar'.format(N))
else:
print('O número {} é par'.format(N))
|
f24f3407c90c15a9dec6acc3e24bbc234a238950 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex104.py | 366 | 4 | 4 | def leiaint(frase):
while True:
num = str(input(frase))
if num.isnumeric():
num = int(num)
if type(num) == int:
return num
else:
print('\033[0;31mERRO! Digite um número inteiro válido\033[m')
n = leiaint('Digite um número inteiro:')
print... |
5cec8c881082a1cbdde400b622e8a0e513837b38 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex037.py | 534 | 4.0625 | 4 | num = int(input('Digite um numero inteiro:'))
print('''Escolha a base para conversão:
[0] converter para BINÁRIO
[1] converter para OCTAL
[2] converter para HEXADECIMAL''')
opção = int(input())
if opção == 0:
print('{} convertido para BINÁRIO é igual a {}'.format(num, bin(num)[2:]))
elif opção == 1:
print('{} c... |
33c08e38999583e6c733f2d4a70d3f50f965f8cf | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex054.py | 862 | 3.859375 | 4 | import datetime
ATUAL = datetime.date.today()
X = 0
for c in range(0, 7):
NOME = input(str('Digite a primeira data de nascimento (Formato: DD-MM-AAAA):'))
if int(ATUAL.year) < int(NOME[6:]):
print('FORMATO INCORRETO')
quit()
if int(NOME[3:5]) > 12:
print('FORMATO INCORRETO')
... |
a218747e278bc3e9a3d1fec841b08c15759f0ca2 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex049.py | 138 | 3.75 | 4 | for c in range(1, 10):
print('==============================')
for i in range(1, 10):
print('{}x{}={}'.format(c, i, c*i))
|
427d11d8e735e0c68eb08a8d15160dfe8d1172bb | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex081.py | 604 | 4.0625 | 4 | LISTA = list()
while True:
LISTA.append(int(input('Digite um número:')))
while True:
R = str(input('Deseja continuar? [S/N]')).upper().strip()[0]
if R != 'S' and R != 'N':
print('Resposta inválida, tente novamente...')
else:
break
if R == 'N':
print('P... |
b9b372196688f956d4308848a8c6f4ae712470b4 | NaufalAulia/Quiz-Alpro | /Quiz42_NAUFAL AULIA MEIKA_1201183340..py | 113 | 3.609375 | 4 | fruits = ["Nanas", "Apel", "Pepaya", "Kentang"]
x = 0
while x < len(fruits) :
print(fruits[x])
x += 1 |
9c0f85bba9a38f64fa940a4a76d1da819748e9c3 | jackSeery/Python3DMatrix | /Python3DPixelArray.py | 3,156 | 4.34375 | 4 | """
MatrixCoordinates with Pixels
Testing 3D coordinates and trying to test displaying pixels
"""
#Python 3D Positioning Test System
#uses a 3D matrix to create a three-axis coordinate system, which can be moved around using keyboard input
#pygame and all methods used are just for quick user input purposes, can and wi... |
0644731b3a083811e57e9de9672804e88098ee67 | greed-dev/sudoku-solver | /solve.py | 1,942 | 3.671875 | 4 | board = [
[0, 1, 0, 0, 8, 6, 0, 0, 7],
[0, 0, 0, 0, 0, 4, 9, 0, 5],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 5, 0, 0, 3, 2],
[1, 0, 0, 0, 0, 0, 0, 0, 0],
[5, 0, 0, 0, 9, 0, 7, 0, 0],
[0, 0, 6, 0, 1, 0, 0, 0, 9],
[3, 4, 0, 0, 0, 0, 0, 0, 1],
[8, 0, 0, 0, 3, 0, 0, 5, 0]
]
def display... |
3c59cd436c5aafd490f295afcc3e867ade4ad1d2 | CamileM/Engineering54-Vehicle_Exercise | /vehicles_class.py | 420 | 3.796875 | 4 |
# === DEFINE CLASS HERE: ===
class Vehicle():
# === THE CHARACTERISTICS FOR A VEHICLE ===
def __init__(self, number_passengers, cargo_size):
self.number_passengers = number_passengers
self.cargo_size = cargo_size
# === THE METHODS / BEHAVIOURS FOR A VEHICLE ===
def accelerate(self)... |
556a6b7468da0a6bd9d828dc9c2dc46e2695ded9 | pavikabilan/pavi | /AAPYTHON task.py | 1,731 | 4.09375 | 4 | # prime numbers
class Prime:
def prime_num(self):
self.n=int(input("enter the number:"))
self.a=[]
self.b=[]
for self.i in range(self.n):
self.a.append(self.i)
print(self.a , end = " " )
for self.j in self.a:
if self.j>1:
for ... |
176288eb034be8d78b16055edc2615979b985bf3 | victorlau1/coverletter | /coverletter/coverletter.py | 3,726 | 3.640625 | 4 | import os
class CoverLetterParser:
separators = {
1: '[]',
2: '{}',
3: '//'
}
def __init__(self, document, words):
self.words = words
separator = self.select_separator()
self.parse_document(document, separator)
def parse_document(self, document, separator):
"""
... |
a255395a00d68a0698da194b096c766e6861c401 | piotrek9999/Mario | /SuperMarioDemo/SuperMarioDemo/classes/gap.py | 867 | 3.765625 | 4 | """ Class Gap. """
import pygame as pg
from pygame import sprite
class Gap(sprite.Sprite):
"""
This is a class for Gap object.
Attributes:
image : The image of Gap.
rect : The coordinates of Gap.
back_x : The value of Gap's 'x' coordinate on background.
"""
def __init__(... |
e4b33d4f8e1f36cf5c786c974ae821e9595f7047 | mrithunjaybr/Linked-List-1 | /LinkedListCycle2.py | 838 | 3.796875 | 4 | // Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow=head
... |
e78b6bd5cd5c07c3b7b1c0bd87e976831c160591 | martinez022jose/POO-Python | /Ejercicio3/ejercicioV3.py | 3,699 | 3.734375 | 4 | """
1. Crear una clase producto con los siguientes atributos:
- codigo
- nombre
- precio
Creale un constructor, getter y setter y una funcion llamada calcular_total, donde le pasaremos unas unidades y
nos debe calcular el precio final.
2. Añadir una clase pedido que tiene como atributos:
- lista de productos
... |
9d644b90bdee9f3658bc0c6d72e756f93542c77a | VadVor/Learning_Python | /Chapter_1/fullpoetry.py | 911 | 3.90625 | 4 | # -*- coding: utf-8 -*-
import random
article=["то","этак","как-бы","так",]
noun=["человек","кот","животное","собака",]
verb=["бежит","прыгнул","поплыл","летит",]
adverb=["плохой","тихий","мутный","спокойный",]
def note():
x=random.randint(1,2)
y1=random.choice(article)
y2=random.choice(noun)
y3=rand... |
bac0dbe94e36709051d6a7b97823b8bbd8305a53 | BranFerr/Guessing_Number | /Homework1.py | 1,676 | 3.953125 | 4 | #This is a guess the number game.
import random
def CheckWinner(_winner, _myName, _guess):
if int(_winner) == 1:
print('Good job, ' + str(_myName) + '! You guessed my number in ' + str(_guess) + ' guesses!')
else:
print('Sorry ' + str(_myName) + '! You DID NOT guess my number ')
#prin... |
e828955ab3afaea07e027f74fade6e5a5658c53e | saikiran0204/dijkstra_cli | /dijkstras_cli.py | 2,358 | 3.875 | 4 | def matrix_to_graph(list1):
global number_of_nodes
g = {}
for i in range(number_of_nodes):
g[i] = {}
for i in range(number_of_nodes):
for j in range(number_of_nodes):
if i != j and list1[i][j] != 0:
g[i][j] = list1[i][j]
elif i == j:
... |
18cdd81a99ec7220b67f47ddfdbe4f91acbec9dd | byteEpoch/python_course | /src/class_4/max_and_min.py | 338 | 3.984375 | 4 | # Función para encontrar el número máximo y mínimo de una lista.
def max_and_min(nums):
max_num = nums[0]
min_num = nums[0]
for num in nums:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
return max_num, min_num
print(max_and_min([3, 44, 100, 1... |
f5953b69d9fb4aaa1f084cb46a660a4e7c92d54d | byteEpoch/python_course | /src/class_2/exercise_1.py | 187 | 3.890625 | 4 | print(2)
for i in range(3, 101):
found = False
for j in range(2, i // 2 + 1):
if i % j == 0:
found = True
break
if not found:
print(i)
|
1d214dc3dd8b4c77f37d7afa6dee6d88da570893 | byteEpoch/python_course | /src/class_4/code.py | 7,970 | 4.15625 | 4 | # Importamos el modulo copy
import copy
# Importamos el modulo random
import random
# Las listas en python nos permiten almacenar n valores en una sola variable.
# En este caso estamos creando una lista de 5 valores numéricos.
my_list = [1, 2, 3, 4, 5]
# Para acceder a los valores, ya sea para modificarlos, o bien pa... |
87dc3ef0ecc429c524fb3165874c33e299251e05 | MarsPanther/machine-translation-research | /example_python.py | 711 | 3.65625 | 4 | def read_data(file_name):
word_lists = []
with open(file_name, 'r') as f:
for line in f:
word_lists.append(line.strip())
return word_lists
def word_lemma_list():
word_list = read_data('/home/tsegaye/Desktop/data/scripts/word_stem_list.txt')
word_lema_list = {}
for each_w... |
649365ac29a9f030319286ca5b2ac2f01034d532 | tmu-nlp/NLPtutorial2019 | /hirao/tutorial00/tutorial00.py | 649 | 3.796875 | 4 | # tutorial00
# ファイルの中の単語の頻度を数えるプログラムを作成
from collections import defaultdict
DEBUG = True
# ディクショナリの初期値を0に設定
d = defaultdict(lambda: 0)
# デバッグモードの場合は短文を入力にする
input_path = "../test/00-input.txt" \
if DEBUG else "../data/wiki-en-train.word"
with open(input_path) as f:
# 1行ずつ
for s_line in f:
# 文を単語に... |
749af26ecd757da450aae1ad43f6a041e6441eb7 | rhotter/ISSI-immunology | /filter2.py | 3,051 | 3.5 | 4 | """
This file runs the different filter parameters and creates a new filtered total file that respects
the specified parameters. In addition, the respective frequency files for each index are filtered
to only include positions that are included in the total file.
"""
import csv
from app import incFilters, ... |
626350884d2fd64577d7c60b4a3054ac77f4c346 | Lan-Muzi/LeetCode | /09_palindromeNumber.py | 615 | 3.640625 | 4 | #方式一
# class Solution:
# def isPalindrome(self, x):
# num = 0
# a = abs(x)
# while(a != 0):
# temp = a % 10
# num = num * 10 + temp
# a = int(a / 10)
# if x >= 0 and x == num:
# return True
# else:
# return False
# 方式二
c... |
8794ed810b0a87f6d625a461fd8340ec58464313 | puhakkaJ/Y1_2019 | /r3/caffeine_calculator211.py | 2,205 | 4.1875 | 4 | '''
Created on 17.9.2019
@author: jenni
'''
def main():
CAFFEINE_IN_COFFEE_CUP = 120 # mg, milligrams
CAFFEINE_IN_TEA_CUP = 40 # mg
MAX_RECOMMENDED_INTAKE = 400 # mg
LETHAL_DOSE = 10000 # mg
i = 1
k = 0
s = 0
yhteensa = 0
print("The program calculates an ... |
bca81934e82a8f9b1e5deea39c9ac007b033b847 | puhakkaJ/Y1_2019 | /r4/batteries.py | 1,132 | 3.75 | 4 | '''
Created on 22.9.2019
@author: jenni
'''
def calculate_storage_size(battery_orders_weight):
osa = battery_orders_weight / 150
varasto = ( osa / 0.1 )
print("Required storage size is", varasto , "cubic meters.")
def calculate_emissions(storage_size):
sähkö = storage_size * 200
määrä = sähk... |
5978b9153ff4b5df88c6d3bb876396b156dbafee | puhakkaJ/Y1_2019 | /r7/bikestations_distances.py | 5,104 | 3.9375 | 4 | '''
Created on 18.10.2019
@author: jenni
'''
def find_shortest_and_longest(lista):
LONGITUDE_DEGREE_LENGTH = 55.26 # km
LATITUDE_DEGREE_LENGTH = 111.2 # km
isoin = 0.0
pienin = 1000.0
for avain in lista:
lista1 = lista[avain]
pituus1 = float(lista1[0] * LONGITUDE_DEGREE_L... |
cab919b3d06c042a4ab1bc7900ad319519a32d2e | puhakkaJ/Y1_2019 | /r8/screen_times.py | 2,655 | 3.90625 | 4 | '''
Created on 19.10.2019
@author: jenni
'''
import datetime
def print_file_contents(name_of_the_file):
"Prints the contents of the file with the name 'name_of_the_file'. Make sure the file is not still open elsewhere before calling this function."
file = open(name_of_the_file, 'r')
line = file.readline(... |
33f857930522420d1bede63b8e9cbc435ecc9247 | vivekdhir77/Universe-Making | /Making Universe(Game).py | 69,737 | 4.375 | 4 | print(""" MAKING UNIVERSE
'Making Universe' is a simple yet creative game based on mixing and combining elements.
Once elements are combined, new ones will be created.
Everything is made from 4 basic elements
1. Fire, you can refer it as 'f' in the game
2. Water, you can refer it as 'w' in the game
3. Air, you ... |
ee56d9dbe5e4460a85fee0950f2a9fb89ccbf223 | Michael-Ch/python-project-lvl1 | /brain_games/scripts/brain_gcd.py | 971 | 3.703125 | 4 | #!/usr/bin/env python3
from random import randint
from brain_games.cli import welcome_user
from .brain_even import game_flow, felicitation, game, fault
def math():
NUM1 = randint(1, 25)
NUM2 = randint(1, 25)
(A, B) = (NUM1, NUM2)
while (A != 0) & (B != 0):
if A > B:
A = A % B
... |
937c3e3bc400c4ba9801bdf43cf4bd69de5ffd0f | MatthewFraser22/StackPalindrome | /main.py | 248 | 4.28125 | 4 | from function import palindrome
print("Enter a word to determine if it is a palindrome.")
pal = (input(": "))
result = palindrome(pal)
if result == True:
print("This is a palindrome")
else:
print("This is not a palindrome")
|
18a63525a9083e0a090caf9e21801ec017a0b956 | marsmans13/twitter-markov-chains | /markov.py | 3,110 | 3.78125 | 4 | """Generate Markov text from text files."""
from random import choice
import sys
import twitter
import os
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
""... |
b549c7ec639cd8e441f77e160ef198a8ca4b1cfa | Pupation/GalaxyGallery | /utils/provider/size_parser.py | 417 | 3.625 | 4 | from typing import Tuple
UNIT = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
def parse_size(size: int) -> Tuple[float, str]:
unit_level = 0
while size > 1024 and unit_level < len(UNIT):
size /= 1024
unit_level += 1
return (round(size, 2), UNIT[unit_level])
if __name__ == '__main_... |
ed6e922c2cd9d16ad3b4a643b6b0b704840df297 | Lynnecarie/dayone | /fizz_buzz.py | 200 | 3.609375 | 4 | def fizz_buzz(t):
if t%3==0 and t%5==0:
return "FizzBuzz"
elif t%3==0 and t%5!=0:
return "Fizz"
elif t%3!=0 and t%5==0:
return "Buzz"
else:
return t
|
00be6e8949e0a89d0a7c991bbd232e555ea576da | willmead/intro_to_python | /src/retired/robot_greeter_2.py | 897 | 3.890625 | 4 | """
Robot Greeter 2.0
Date: 28/03/20
Author: Will
The Robot Greeter 2.0 will ask questions of the user
and react differently depending on the response it receives.
"""
print("I am a Personal Robot Greeter 2.0")
# Name
name = input("What is your name?")
print(f"Hello {name}, have a great day!")
# Age
age = int(input... |
e86e593f4d12f680d283328b61f51fcc2107058b | willmead/intro_to_python | /src/retired/robot_greeter_1.py | 444 | 3.890625 | 4 | """
Robot Greeter 1.0
Date: 28/03/20
Author: Will
The Robot Greeter ask questions of the
user and respond using the information
it receives.
"""
print("I am a Personal Robot Greeter")
name = input("What is your name?")
print(f"Hello {name}, have a great day!")
age = int(input("How old are you?"))
print(f"You are {a... |
1b6329eb9d290220cdca80412c049636f12c8732 | willmead/intro_to_python | /src/retired/graphics/calculator2.py | 1,531 | 3.65625 | 4 | from tkinter import *
class Calculator:
def __init__(self, parent):
self.parent = parent
self.container = Frame()
self.container.grid()
self.string = ''
self.entry(0, 0)
self.button('1', 1, 0)
self.button('2', 1, 1)
self.button('3', 1, 2)
... |
f84cdbe2ae4a827fda296d3d3682071467d48749 | davidenole/Catan | /variables.py | 2,274 | 3.796875 | 4 | from math import sin, cos, pi
import pygame
from colours import *
''' screen variables '''
L = 800
''' variables used in the tiles '''
# converts a three-coordinate point to an xy cartesian point
def convert(p, q, r):
x = (q+r)*cos(pi/6)
y = p + (q-r)*sin(pi/6)
return (x,y)
tileRadius = 80
centres = [ (0,0,0)... |
cac4189041bf34a6fef66806e2b54e977057ccbe | karim-zaidi/digital_twin | /code/Boundary_test.py | 378 | 3.609375 | 4 | import unittest
from Boundary import Boundary
from Point import P
class Boundary_test(unittest.TestCase):
def test_0_create_boundary(self):
p1, p2 = P(0, 0), P(10,0)
boundary = Boundary(p1, p2)
self.assertIsInstance(boundary, Boundary)
self.assertTrue(boundary.p1 == p1 and boundary... |
7b6aeb721c1134954383bd6d96971a1a1d3884e8 | vitorpbarbosa7/DL_Python | /S5_ClassificacaoMulticlasse/1_iris_simples_2.py | 2,050 | 3.53125 | 4 | # Importacao dos pacotes
import pandas as pd
#Rede neural
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
#%% Leitura dos dados
data = pd.read_csv('iris.csv')
#%% Divisao X e y
X = data.drop('class', axis = 1).values
y = data['class'].values
# %%Label enconder para... |
2259951479d067b2352109fd7094c4f48b8a3e0d | JaharshKotha/Algorithm-Optimality | /A*search.py | 1,544 | 3.796875 | 4 | """Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
import util
priority_queue = util.PriorityQueue()
start_state = problem.getStartState()
if (problem.isGoalState(start_state)):
return None
flg = 0
res = []
visited = set()
... |
d899442d8a87da3fa500b644fb2c9b56050acb0b | qwaqwa93/NandProject2 | /nandify.py | 10,195 | 3.5625 | 4 | """ NandProject Written by Park Jongmin
project #3 from CS492 "Nand to Tetris"
Usages: python nandify.py (inputfile) [Try this ->] python nandify.py testInput.txt
- inputfile is optional
- It will get inputs from stdin if you miss giving inputfile as an argument
- It will make some .hdl f... |
209b93a565f3307f19b705fa7dd4236f9ca741c0 | AkosSK/Binary_Search | /main.py | 425 | 3.765625 | 4 | lowerBound = 0
array=[10,20,30,40,50,60,70,80,90,100]
upperBound = len(array) - 1
item=50
Found = False
while Found == False and lowerBound <= upperBound:
Midpoint = int(round((lowerBound + (upperBound - lowerBound) / 2),0))
if array(Midpoint) == item:
Found = True
elif array(Midpoint) < item:
lowerBound = ... |
f7a6d48596d2d8efa0a4c1e334b1b539bedc7cc3 | CCM345/daily_training_python | /004 http/http_server获取指定的网页.py | 3,448 | 3.609375 | 4 | import socket
import re
"""
TCP 的服务端
1,socket 创建socket
2.bind 绑定IP和端口
3.listen 处于监听状态
4.accept 接进来客户端的连接
5.recv/send 接受或者发送信息
6.close 关闭
"""
def tcp_creat_socket():
tcp_ser = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
return tcp_ser
def tcp_bind_listern_info(tcp_socket):
SER_IP = "127.... |
201cd1843ea08a3056d0ae4a1802a55f8a52b7b4 | CCM345/daily_training_python | /condition_if_array_dict.py | 3,127 | 3.8125 | 4 | """"
0710
列表的练习
"""
def split_line():
print("++++++++++++分割线++++++++++++++++++++++分割线+++++++++++++++++++++分割线++++++++++++++\n")
def split_line2():
print("$$$$$$$$$$$$分割线$$$$$$$$$$$$$$$$$$$$$$分割线$$$$$$$$$$$$$$$$$$$$$分割线$$$$$$$$$$$$$$\n")
split_line()
menu = ["Chinese", "English", "math","secience", "music", "ot... |
bb6bfff1e3e4089d991dfafd4b5c0d20bdfe6de6 | altanizio/python | /binomial.py | 615 | 3.765625 | 4 | #Binomial programa
import math
import mathprob
def binomial(x,n,p):
return mathprob.combinacao(n,x)*math.pow(p,x)*math.pow(1-p,n-x)
print("X~Bin(n,p)")
n=int(input("n="))
p=float(input("p="))
if p>1:
print("erro")
exit()
aux=0
for i in range(0,n+1):
print("x"+str(i), "=", binomial(i,n,p))
... |
ad514c9aea53be0d9896da4fd0857fa6438f5696 | lks1227/dsc80-sp20 | /discussions/07/disc07.py | 908 | 3.53125 | 4 | import requests
import time
def url_list():
"""
A list of urls to scrape.
:Example:
>>> isinstance(url_list(), list)
True
>>> len(url_list()) > 1
True
"""
url_lis = []
for i in range(26):
url_lis.append('http://example.webscraping.com/places/default/index/'+str(i))
... |
758a7126cb01830538be7ba11e9177374b98fdc5 | seanbrhn3/AI-with-python | /practice/random_test_data.py | 944 | 3.578125 | 4 | #Creating a csv file with random data to then use for testing purposes
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import normalize
def make_Data():
with open("test_data.csv",'w') as data:
for i in range(1,1001):
data.write(str(random.randint(0,i)... |
881f69697c7bff6988eeefef7fa63189d007c2e0 | seanbrhn3/AI-with-python | /fashion_neural_net.py | 2,813 | 3.84375 | 4 | #Using tensor flows keras library to build a neural netowrk
import tensorflow as tf
from tensorflow import keras
#Helper libraries
import numpy as np
import matplotlib.pyplot as plt
#download dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels),(test_images, test_labels) = fashion_mnist... |
0056b0d236b87c316ba9ee77fa8f12025971bad4 | dinkartaneja/Python-Classrooms | /mytupple.py | 187 | 4.1875 | 4 | #myTupple=(2,6)
#print(myTupple)
#print(myTupple[1: ])
fac=1
num=int(input("Enter the number: "))
for i in range(1,num + 1):
fac=fac*i
print("The result of your factorial is: ",fac) |
9c0e3971c7ab124196efd8ed8ea4a0757a766a3f | shanthi1929/learning | /shanthi_assign/rand.py | 254 | 4.15625 | 4 | import random
def diction(n):
x=1
if n%3 == 0 or n%5==0 and n%15==0:
r = {x: pow(n,3)}
else:
if n%3 == 0 or n%5==0:
r = {x:random.random()}
return r
n=int(input("Enter a number:"))
i=diction(n)
print(i)
|
93fd161decf60984f0b7a61b69cf400801cfc6c0 | shanthi1929/learning | /shanthi_assign/area.py | 1,094 | 4.1875 | 4 | #!/usr/bin/python
def square(L):
return L*L
def rectangle(width,height):
return width*height
def circle(radius):
return 3.14159*radius**2
def options():
print()
print("Options:")
print("Press s: to calculate area of a square")
print("Press c: to calculate area of a circle")
print("Press ... |
2b2d7003373e15d8062825b7c87f288cc275c2c8 | shanthi1929/learning | /shanthi_assign/dict.py | 129 | 4 | 4 | def diction(n):
squares = {x: x*x for x in range(1,n+1)}
return squares
n=int(input("Enter a number:"))
i=diction(n)
print(i)
|
6747a31fe45db9565df6c137502569d6fd66fbb0 | Gaston276/Projets_ISN_2020 | /Lilou-Sofian-Yannick/class_personnages.py | 2,424 | 3.640625 | 4 | from random import *
class heros :
def __init__(self) :
self.epee=0
self.force=self.epee*25
self.bouclier=0
self.potions=0
self.argent=100
self.defense=False
self.pv=50
self.pvmax=50
self.esquive=10
def combat(self,soldat) :... |
4c5406cb82cbe8f387a87e05864db74b45ca73ba | GuilletThomas/CSI2_TP11 | /ex4.py | 794 | 3.53125 | 4 | class Duree:
def __init__(self, heure, minute, seconde):
self.__h = heure
self.__m = minute
self.__s = seconde
def __str__(self):
return str(self.__h)+"h"+str(self.__m)+"m"+str(self.__s)+"s"
def __add__(self, other):
return Duree(self.__h+other.__h, self.__m+other._... |
094598c977839169f93bf7ec347b83df14df5f8a | tanveeralam27/frequent-sting | /frequent string.py | 390 | 3.59375 | 4 | def calc(inputstr):
myDict = {}
for char in inputstr:
if char in myDict:
myDict[char] += 1
else:
myDict[char] = 1
return(sorted(myDict.items(),key=lambda x: x[1],reverse=True))
inputstr = input("enter the string you want to check:")
res = calc(inputstr)
fo... |
ab63e1104f6782e092b079387239990842420f9e | salmanul-fares/py-automation | /2-moderate/4-regex_findall.py | 1,167 | 4.25 | 4 | import re
'''While search() will return a Match object of the first matched text
in the searched string, the findall() method will return the strings of every
match in the searched string.'''
indianMobilePhoneRegex = re.compile(r'''
(
#country code
(
(\+|0|00)?91
(\ |-)?
... |
2247c3996f465119f6af58a9daa1fea766a31d4d | salmanul-fares/py-automation | /1-simple/4-copy_lists.py | 563 | 4 | 4 | #in python the list reference is passed when = is used
#copy solves the issue
import copy
spam = ['a',2, [1,34,'sal',[1,2]], 'salman']
fakecopy = spam #fakecopy is only a reference to spam
goodCopy = copy.copy(spam) #seperate list made (duplicate)
deepCopy = copy.deepcopy(spam) #seperate list wi... |
f04146eb1fe936cb479a499030448c30177775b9 | andreyryabtsev/jets-tutorials | /calcpi.py | 686 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math, random, sys
#from accept-reject import get_rnd
def find_pi(n):
arr = np.empty(n)
for i in range (0, n):
arr[i] = np.sqrt((random.random() * 2 - 1) ** 2 + (random.random() * 2 - 1) ** 2) < 1
return np.sum(arr) / n * 4
def several_pi(n... |
189c12fa5af758f9975903fef0643433259c47b9 | tiilde/Paradigmas_de_Programacao_em_Python | /numConcatenados.py | 656 | 4.15625 | 4 | # Desenvolva utlizando Laços de Repetição
# Escreva um programa em Python que lê uma sequência de dígitos, sendo
# cada um dos dígitos fornecido numa linha separada, e calcula o número inteiro composto
# por esses dígitos, pela ordem fornecida. Para terminar a sequência de dígitos é fornecido
# ao programa o inteiro −... |
532a072dee35da27dfd537ba454d74663e42c39e | JonathanSaldivar/CSE | /Jonathan_Saldivar-Inheritance.py | 6,141 | 3.546875 | 4 | class Item(object):
def __init__(self, name):
self.name = name
class LaserGun(Item):
def __init__(self, name):
super(LaserGun, self).__init__(name)
self.damage = 150
self.usage = 100
def shoot(self):
self.usage -= 1
print("You have %d lasers left" % self.us... |
f81efc5df51c41679696e4450cc9c0dc37fca217 | DEEPTHA26/guvi | /codekata/48.py | 178 | 4.3125 | 4 | num = int(input("enter the number"))
sum = 0
for n in range(num):
numbers = int(input())
sum += numbers
avg = sum/num
print('Average of ', num, ' numbers is :', avg)
|
b4c71a12feab15674581d35b7103591749b49bdb | DEEPTHA26/guvi | /codekata/50.py | 145 | 3.5625 | 4 | a=int(input())
b=0
c=0
for i in range (0,a):
b=2**i
if b == a:
print("yes")
c=1
break
if c == 0:
print("no")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.