text stringlengths 37 1.41M |
|---|
import unittest
from app.office import Office
from app.room import Room
class Test_class_Office(unittest.TestCase):
def test_office_is_subclass_of_Room(self):
self.assertTrue(issubclass(Office, Room), msg='Office is not a subclass of Room')
def test_office(self):
office = Office('room_name',... |
import unittest
from app.staff import Staff
from app.person import Person
class Test_class_Staff(unittest.TestCase):
def test_staff_is_subclass_of_Person(self):
self.assertTrue(issubclass(Staff, Person), msg='Staff is not a subclass of Person')
def test_staff_is_instance_of_class_Staff(self):
... |
def factorielle(n):
"""retourne la factorielle de n. """
res=1
for i in range (1,n+1):
## Ici res contient (i-1)!
res*= i
## Ici res contient i!
return res
def estPremier(n):
res = True
for k in range (1,n):
## Ici, res est vrai ssi les éléments dans [[2,k[[ ne divise pas n
if n%k==0:
res = False... |
# Recherche d'une chaine dans une autre
## entrée m et t deux chaines str
#Sortie : Bool si m appartient ou non à t
def estPresentPlacei(m,t,i):
res = True
for j in range (0,len(m)):
if t[i+j]==m[j]:
None
else:
res = False
return res
def estPresent(m,t):
res = False
for i in range (0,len(t)-len(m))... |
def f(a,b):
x = 0
y = a
## Ici, a= b*x +y
while y>=b:
## Ici, a= b*x +y
x+=1
y-=b
## Ici, a= b*x +y
count+=1
return (x,y)
def fLisible(a,b):
""" Entrée : -a,b entiers
Sortie : -couple (quotient,reste) ## OU (a//b , a%b)
Effet : -Division euclidienne de a par b
"""
quotient = 0
reste =... |
import os
vendas = {}
compras = {}
def header(word="Gerenciador de Veiculos"):
print("="*15)
print(word)
print("="*15)
def menu():
# list with all the options from the menu
options = { 1: "Comprar Veiculos", 2: "Listar Veiculos", 3: "Atualizar Veiculos", 4: "Vender Veiculos", 5: "Listar Compras",... |
nome = input("Digite seu nome: ")
qtd_char = len(nome)
if qtd_char <= 0:
print("{} seu nome é nulo e invalido".format(nome))
elif qtd_char <= 4:
print("{} seu nome é curto".format(nome))
elif qtd_char <= 6:
print("{} seu nome é normal".format(nome))
else:
print("{} seu nome é muito grande".format(nome))
|
def main():
while True:
print(("=" * 6) + (" Menu ") + ("=" * 6))
print("1 - Continuar")
print("0 - Sair")
try:
option = int(input("Digite a opcao: "))
except:
print("Digite um valor inteiro.")
if option < 0 or option > 1:
print("Invalid option.")
elif option == 0:
break;
elif option == 1... |
def saudacao(nome, sobrenome):
print("Hi, {} {}!".format(nome, sobrenome))
def main():
nome = input("Digite seu primeiro nome: ")
sobrenome = input("Digite seu sobrenome: ")
saudacao(nome, sobrenome)
main() |
L_total = [9, 5, 6, 4, 8, 12, 11, 15, 0, 1, 3, 2]
L_par = []
L_impar = []
for number in L_total:
if (number % 2) == 0:
L_par.append(number)
else:
L_impar.append(number)
print("Lista impar: {}".format(L_impar))
print("Lista par: {}".format(L_par)) |
# Napisati program kojim se ilustruje upotreba struktura podataka:
# stek, skup, mapa, torke.
# Skup
imena = set()
for ime in ['Milan', 'Jovan', 'Marko', 'Milos', 'Lazar', 'Marko']:
imena.add(ime)
print(imena)
print(set(['Milan', 'Jovan', 'Marko', 'Milos', 'Lazar', 'Marko']))
# Stek
stek = []
stek.append(1)
stek... |
# Napisati program koji racuna odnos kardinalnosti skupova duze i sire za
# zadati direktorijum. Datoteka pripada skupu duze ukoliko ima vise redova
# od maksimalnog broja karaktera po redu, u suprotnom pripada skupu sire.
# Sa standardnog ulaza se unosi putanja do direktorijuma. Potrebno je obici
# sve datoteke u za... |
# Napisati program koji imitira rad bafera. Maksimalan broj elemenata
# u baferu je 5. Korisnik sa standardnog ulaza unosi podatke do unosa
# reci quit. Program ih smesta u bafer, posto se bafer napuni unosi se
# ispisuju na standardni izlaz i bafer se prazni.
buffer = []
i = 0
while True:
unos = input()
if... |
# Dati su novcici od 1, 2, 5, 10, 20 dinara. Napisati program koji
# pronalazi sve moguce kombinacije tako da zbir svih novcica bude 50.
# Sve rezultate ispisati na standardni izlaz koristeci datu komandu ispisa.
import constraint
problem = constraint.Problem()
problem.addVariable("1 din", range(0, 51))
problem.add... |
# Napisati program koji sa standardnog ulaza ucitava
# dva broja i na standardni izlaz ispisuje njihov zbir.
a = int(input("Uneti prvi broj: "))
b = int(input("Uneti drugi broj: "))
suma = lambda a,b: a + b
print("Suma: {}".format(suma(a, b))) |
# Program implementira automat za prepoznavanje
# ulaza sa parnim brojem 0. Prelasci se odredjuju
# naredbama granjanja.
import sys
stanje = 'P'
zavrsno = 'P'
prelazi = {
'P':{'0':'N', '1':'P'},
'N':{'0':'P', '1':'N'}
}
while True:
try:
c = input('Unesite 0 ili 1:')
if(c != '0' and c != '... |
# Sa standardnog ulaza se unose reci do reci quit. Napisati
# program koji ispisuje unete reci eliminisuci duplikate.
lista = []
while True:
unos = input()
if unos == 'quit':
break
lista.append(unos)
skup = set(lista)
print(skup) |
import json
import os
from typing import Dict, List
current_dir = os.path.dirname(__file__)
data_path = 'data.json'
abs_path = os.path.join(current_dir, data_path)
def read_data() -> List[Dict]:
""" Get all data from data.json file.
Reads all data from the json file and returns a list
containing all data.
... |
"""
Вариант 2, задача 2
Создать класс Fraction, который должен иметь два поля: числитель a и знаменатель b.
Оба поля должны быть типа int. Реализовать методы: сокращение дробей, сравнение, сложение и умножение.
Данная программа может выполнять операции непосредственно с дробями, например a,b,c - дроби, тогда:
c = a +... |
import turtle
turtle.shape("turtle")
'''
#노가다
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
#좀 편함
for i in range(4):
turtle.forward(100)
turtle.right(90)
#더 편함
def drawRec(size):
for i in rang... |
#Sumar los O primeros numeros
import os
#Declaracion de variables
c=0
suma=0
z=int(os.sys.argv[1])
while(c<=z):
print(c)
suma += c
c += 1
#fin_iteracion
print("La suma de los O primeros numeros es:", suma)
print("Fin del bucle")
|
#Sumar los Q primeros numeros
import os
#Declaracion de variables
e=0
suma=0
v=int(os.sys.argv[1])
while(e<=v):
print(e)
suma += e
e += 1
#fin_iteracion
print("La suma de los Q primeros numeros es:", suma)
print("Fin del bucle")
|
#Sumar los M primeros numeros
import os
#Declaracion de variables
a=0
suma=0
x=int(os.sys.argv[1])
while(a<=x):
print(a)
suma += a
a += 1
#fin_iteracion
print("La suma de los M primeros numeros es:", suma)
print("Fin del bucle")
|
def validator(*args):
"""
Checks if user input is an integer.
Parameters:
*args (String) : "+" Checks for positive integers;
"-" Checks for negative integers;
"" Checks for any integers;
"""
while True:
try:
user_input = i... |
#Receta 4: Obtener una Cantidad Arbitraria de Elementos Mínimos y Máximos
import heapq
numeros = [7, 9, 1, 3, 5, 8, 7, 6, 2, 3, 1, 0, -8, -9, 5, -2]
print(heapq.nsmallest(3,numeros))
print(heapq.nlargest(3,numeros))
print()
productos = [
{ 'nombre': 'Mouse', 'precio': 35 },
{ 'nombre': 'Teclado', 'precio':... |
import calendar
print(calendar.weekheader(3))
print(calendar.firstweekday())
print(calendar.month(2020,11))
print(calendar.monthcalendar(2020,11))
print(calendar.calendar(2020))
dayOfTheWeek= calendar.weekday(2020,11,6)
print(dayOfTheWeek)
isLeapYear= calendar.isleap(2020)
print(isLeapYear)
howM... |
# The factorial of a positive integer n is defined as the product of the
# sequence , n-1, n-2, ...1 and the factorial of 0 is defined as being 1. Solve
# this using both loops and recursion.
#
# https://github.com/karan/Projects-Solutions/blob/master/README.md
#
# Lacey Sanchez
# Recursion
def find_factorial_rec(n):... |
from cs50 import SQL
import sys
# Wrong Usage Check
if (len(sys.argv) != 2):
print("Usage: python roster.py house")
exit()
db = SQL("sqlite:///students.db")
# Execute the sqlit command to get a list and store it in memory.
data = db.execute("SELECT first,middle,last,birth FROM students WHERE house = ? ORDER ... |
print('*'*30)
marks = int(input('enter marks\t'))
if marks >=70:
print('you made it-you passed')
if marks >=90:
if marks == 100:
print("distinction")
elif marks >=98 or marks ==99:
print('A++')
elif marks >=95 <=97:
print('print A-')
elif marks >=91 ... |
# An adventure game
import time
def room1():
global health
print(" You arrive at your friends house after a long trip.")
print("""
'I'll pick you up at 8 tommorow morning' your mother shouted as she
watched you head up the drive""")
print(" 1: Wave goodbye")
print(" 2: Ignore"... |
#!/usr/bin/env python
import re
import sys
from pyspark import SparkContext
def main():
if len(sys.argv) != 2:
sys.stderr.write('Usage: {} <search_term>'.format(sys.argv[0]))
sys.exit()
# Create the SparkContext
sc = SparkContext(appName='SparkWordSearch')
# Broadcast the requested t... |
#!/usr/bin/env python
# coding: utf-8
# **The Sparks Foundation**
# **Data Science and Business Analytics Internship**
# **Task-2 :Prediction using UnSupervised ML**
#
# **TASK :From the given ‘Iris’ dataset, predict the optimum number of clusters
# and represent it visually**
# **By-Priyanka Mohanta**
# In[1]:
... |
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next = next_node
class LinkedList:
def __init__(self):
self.head = None
def add_to_head(self, value):
self.head = Node(value, self.head)
def remove(self, value):
'''
Fin... |
mes = int( input("Ingrese el mes de su elección [1-12]: ") )
estacion = None
if (mes >= 1 and mes <= 2) or mes == 12:
estacion = "Invierno"
elif mes >= 3 and mes <= 5:
estacion = "Primavera"
elif mes >= 6 and mes <= 8:
estacion = "Verano"
elif mes >= 9 and mes <= 11:
estacion = "Otoño"
else:
estaci... |
print("Proporcione los siguientes datos del libro:")
nombre = input("Proporcione el nombre del libro: ")
id = int( input("Poporcione el ID:") )
precio = float( input("Proporcione el precio: $") )
envioGratuito = input("Indica si el envio es gratuito (True/False): ")
if envioGratuito == "True":
envioGratuito = True... |
# Clases
# Sintaxis básica
class Persona:
# Constructor de la clase
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
# Crear un objeto, nueva instancia de la clase
persona = Persona("Alejandra", 26)
print(persona.nombre)
print(persona.edad)
print ("Tu nombre es {0} y ti... |
class Persona:
def __init__(self, nombre):
self.__nombre = nombre
# Método sobreescrito de la clase padre object
def __add__(self, otro):
return self.__nombre + " " + otro.__nombre
def __sub__(self, otro):
return "Operación no soportada"
p1 = Persona("Alex")
p2 = Perso... |
from figura_geometrica import FiguraGeometrica
from color import Color
class Rectangulo(FiguraGeometrica, Color):
def __init__(self, ancho, alto, color):
FiguraGeometrica.__init__(self, ancho, alto)
Color.__init__(self, color)
def area(self):
return self.get_alto() * self.get_ancho... |
#####
# Tested on Windows 7 32-bit
# With Python version 3.1.2
#####
for num in range(1, 101):
# This builds a range of numbers
# from 1 to 100 (because a range is not inclusive)
if num % 3 == 0 and num % 5 == 0:
# Checks to see if the number divides into both 3 and 5 with no remainder
# Notice that it checks ... |
start = 10
end = 20
startc = 30
endd = 40
num= 22
test = (start<num<end) or (startc<num<endd)
print(test)
num2 = 11
test2 = (start<num2<end) or (startc<num2<endd)
print(tes |
def temperature(temp):
print('What is the temperature in celsius?')
temp = input()
fahrenheit = int(temp) * 9/5 +32
return fahrenheit
final = temperature('temp')
print((f'The temperature is {final} in fahrenheit!'))
|
def factorial(number , accumulator=1):
if number == 1:
return accumulator
return factorial(number - 1, number*accumulator)
print(factorial(5)) |
import random
def get_integer(prompt):
while True:
temp = input(prompt)
if temp.isnumeric():
return int(temp)
highest = 10
answer = random.randint(1,highest)
print(answer) # TODO: Remove this line after testing
print("Please guess number between 1 and 10: ")
guess = get_integer("Enter... |
# 01234567890123
parrot = "Norwegian Blue"
print(parrot)
# # print(parrot[3])
# #POSITIVE INDEX
# print(parrot[3])
# print(parrot[4])
# print(parrot[9])
# print(parrot[3])
# print(parrot[6])
# print(parrot[8])
# #Negative Index
# print()
# print("Using Negative index")
# print(parrot[-11])
# print(parrot[-1... |
def fibonacci(number):
"""Fibonacci using for loop
Args:
number ([int]): [`n` th fibonacci number to be find]
Returns:
[int]: [return `n` th fibonacci number]
"""
if 0 <= number <= 1:
return number
first, second = 0,1
result = None
for f in range(number-1):
... |
# This is concept of TUPLE
a = b = c = d = e = f = 12
print(a, b, c, d, e, f)
# RHS is a Tuple
x, y = 1, 2
print(x, y)
data = 1, 2, 3
print(data.__class__) # Prints tuple
x, y, z = data
print(x, y, z)
# Unpacking the list
# We can unpack any sequence type
data_list = [12, 13, 14]
x, y, z = data_list
print(x, y, z)... |
alphabets = [
"a",
"b",
"c",
"d",
"e",
"f",
]
for alphabet in alphabets:
print(alphabet)
separator = " | "
output = separator.join(alphabets)
print(output)
print(", ".join(alphabets)) |
import nltk
File = open("D:\IFS\input\source.txt") # open file
lines = File.read() # read all lines
sentences = nltk.sent_tokenize(lines) # tokenize sentences
nouns = [] # empty to array to hold all nouns
for sentence in sentences:
for word, pos in nltk.pos_tag(nltk.word_tokenize(str(sentence))):
if (... |
"""
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
"""
"""
例1:2AF5换算成10进制:
第0位: 5 * 16^0 = 5
第1位: F * 16^1 =15*16^1= 240
第2位: A * 16^2= 10* 16^2=2560
第3位: 2 * 16^3 = 8192
结果就是:5 * 16^0 + 15 * 16^1 + 10 * 16^2 + 2 * 16^3 = 10997
例2:CE换算成10进制:
第0位:E*16^0=14*16^0=14
第1位:C*16^1=12*16^1=192
结果就是:14*16^0+12*16^1=206
"""
while True:... |
"""
python实现顺序栈
1。目标:实现栈(后进先出)
2。设计
"""
class ListStack:
def __init__(self):
"""初始化一个空栈"""
self.elems = []
def push(self, item):
"""入栈操作"""
self.elems.append(item)
def destack(self):
"""出栈操作"""
if not self.elems:
raise Exception('destac... |
class MyClass:
def __init__(self):
self.__data = 10
def __func01(self):
print("func01 被执行了")
m01 = MyClass()
# print(m01.__data) # 报错 type object 'MyClass' has no attribute '__data'
print(m01.__dict__)
m01._MyClass__func01() # 隐形变量的显示方式 但是不建议,是臭流氓做法
print(m01._MyClass__data)
class A:
... |
def get_text(name):
return "My name is, {0} and i don't like decorators".format(name)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def main():
name = (raw_input("Enter your name to demonstrate decorator"))
print ("*******calling name... |
def convetor(num, word):
# number 1 solution
print("*********converting interger to a string**********")
print("Data type before conversion")
print (type(num))
print("Data type after conversion")
mo = str(num)
print (type(mo))
# number 2 solution
print("*********converting string t... |
class Vehicle:
def __init__(self, **kwargs):
self.var = kwargs
def mile (self):
print ("The car model")
def year (self):
print(" The year of the model")
def get_param (self):
return self.var
def get_param (self, key):
return self.var.get(key)
def main ()... |
import unittest
def person_number(person_count: int) -> int:
return person_count
def get_pizza_number() -> int:
return 2
def get_number_slice_by_people(people: int, pizza: int) -> int:
default_slice_by_pizza = 8
return pizza * default_slice_by_pizza // people
class TestOne(unittest.TestCase):
... |
def merge(arr,l,m,r):
n1=m-l+1
n2=r-m
left=[0]*n1
right=[0]*n2
i=0
j=0
while(i<n1):
left[i]=arr[l+i]
i=i+1
while(j<n2):
right[j]=arr[m+1+j]
j=j+1
i=0
j=0
k=l
while i<n1 and j<n2:
if left[i]<=right[j]:
arr[k]=left[i]
... |
"""
Provided with consumption data over a given period of time,
the program output a classified list for all your products.
structure of the excel must be:
sku | nc
where sku - item number
nc - number of consumption
"""
import numpy as np
import pandas as pd
path = './sample_data/data.xl... |
# Extended Slices
# [begin:end:step]
# if begin and end are off-option statement and a step get positive value,
# sequences are going to positive way with positive step.
# if a step get negative value, then sequences are going to reverse way
# with abs(value)
def reverse(str=''):
return str[::-1]
|
# Learning Sets and Frozen sets in python
# Sets
# The data type "set", which is a collection type, has been part of Python since version 2.4.
# A set contains an unordered collection of unique and immutable objects.
# The set data type is, as the name implies, a Python implementation of the sets
# as they are known ... |
# Formatting in python
from math import sqrt
print("Art: %5d, Price is %8.2f" %(432, 345.69))
print("Art: {a:<5d}, Price is {b:<8.2f}".format(a=432, b=3456.7967))
def print_sqrts(start, end):
"""
Printing pretty formatted strings
:param start:
:param end:
:return None:
"""
for i in range... |
import numpy as np
dim_0 = np.array(24)
dim_1 = np.array([1,2,3])
dim_2 = np.array([[1,2,3],[1,2,3]])
dim_3 = np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]])
print(dim_0)
print(dim_1)
print(dim_2)
print(dim_3)
#print dimensions
print(dim_0.ndim)
print(dim_1.ndim)
print(dim_2.ndim)
print(dim_3.ndim)
#creating array w... |
import numpy as np
a = np.array([1,2,3,4,5])
ar = np.array([[1,2,3,4,5],[1,2,3,4,5]])
arr = np.array([[[1,2,3,4,5],[1,2,3,4,5]],[[1,2,3,4,5],[1,2,3,4,5]]])
#iterating a one dimension array
for x in a:
print(x)
#iterating two dimension array
for x in ar:
print(x)
#printing every single array element in two d... |
print("User input")
print("*************************************")
p = int(input("Enter the Prime number P: "))
q = int(input("Enter the Prime number Q: "))
e = int(input("Enter tha value for e: "))
m = int(input("Enter the value for M: "))
print("************************************")
def rsa():
n = p*q
pi_n ... |
class inheritdemo:
def __init__(self,text):
self.text=text
class hello(inheritdemo):
def quote(self):
print("it is coming from hello class")
class hi(inheritdemo):
def quote1(self):
print("it is coming from hi class")
text1=hello("hello")
text2=hi("hi")
print(text1.text)... |
"""
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "a*"
输出: true
解释: 因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前... |
"""
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
... |
"""
题目已被锁
"""
class Solution(object):
def generateSentences(self, synonyms, text):
"""
:type synonyms: List[List[str]]
:type text: str
:rtype: List[str]
"""
def dfs(n):
if n == length:
result.add(" ".join(word_list))
return... |
"""
有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。
每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。
给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。
由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。
示例 1:
输入:steps = 3, arrLen = 2
输出:4
解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。
向右,向左,不动
不动,向右,向左
向右,不动,向左
不动,不动,不动
示例 2:
输入:steps = 2,... |
"""
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[i... |
"""
给你一个整数数组 nums,请你返回其中位数为 偶数 的数字的个数。
示例 1:
输入:nums = [12,345,2,6,7896]
输出:2
解释:
12 是 2 位数字(位数为偶数)
345 是 3 位数字(位数为奇数)
2 是 1 位数字(位数为奇数)
6 是 1 位数字 位数为奇数)
7896 是 4 位数字(位数为偶数)
因此只有 12 和 7896 是位数为偶数的数字
示例 2:
输入:nums = [555,901,482,1771]
输出:1
解释:
只有 1771 是位数为偶数的数字。
提示:
1 <= nums.length <= 500
1 <= nums[i]... |
# 일반적인 병합 정렬 알고리즘
def merge_sort(a) :
n = len(a)
if n <= 1 : # 종료조건
return
# 그룹을 나누어 각각 병합 정렬을 호출
mid = n // 2
g1 = a[:mid]
g2 = a[mid:]
merge_sort(g1) # g1 = [3, 6, 8, 9, 10]
merge_sort(g2) # g2 = [1, 2, 4, 5, 7]
# print('mid : ', mid)
# print('g1 : ', g1)
# p... |
import gevent
from gevent import socket
'''
Implementation 1
'''
urls = ["www.google.com","www.agrostar.in","www.facebook.com"]
jobs = [gevent.spawn(socket.gethostbyname,url) for url in urls ]
gevent.joinall(jobs,timeout=2)
print([job.value for job in jobs])
'''
Instead we could also write code as below
Implementati... |
class Point:
x = 0
y = 0
def __init__(self, init_x, init_y):
""" Create a new point at the given coordinates. """
self.x = init_x
self.y = init_y
def get_x(self):
return self.x
def get_y(self):
return self.y
def distance_from_origin(self):
retu... |
import time
print("----------ATM MACHINE----------")
print("Welcome to xxxx ATM")
print("Swipe Your Card please")
amount=10000
#your password is 2222
y="2222"
print("_________________")
x=input("enter your pin")
print("checking........................!!")
time.sleep(1)
if x==y:
print("___________... |
import wikipedia_utils
"""
Returns a key-value dictionary of the extractable values from the wikipedia
infobox.
"""
def getInfobox(page):
# Download the raw page content and then parse it into nested dictionaries.
page = wikipedia_utils.GetWikipediaPage(page)
parsedPage = wikipedia_utils.ParseTemplates(page["te... |
# coding=utf-8
# 如何对字符串进行左,右,居中对齐
# 使用str.ljust(),str.rjust(), str.center()进行对齐
# 使用内置的format方法
s = 'abc'
print s.ljust(20)
print s.ljust(20, '=')# 以=作为填充物进行填充,字符靠左
print s.rljust(20)
print s.rjust(20, '=')# 以=作为填充物进行填充,字符靠右
print s.center(20)
print s.center(20, '=')#以=作为填充物,字符居中
print format(s, '<20')#做对齐
print format... |
########################################
# @AUTHOR TAYLOR ROMAIN #
# @DATE 3-6-2021 #
# __main__.py #
########################################
import matplotlib.pyplot as plt
import math
import numpy as np
from math import log10, floor
from tabulate import tabulate
... |
class Animal:
def __init__(self, e,a):
self.especie = e
self.edad = a
def correr (self):
print("soy un {}."
"Estory corriendo".format(self.especie))
def crecer (self, edad = 0):
if (self.edad + edad) > 14:
self.vivo = False
el... |
class Duck:
def __init__(self,nombre):
self.duck_nombre = nombre
def quack (Self):
print("Quack")
def walk (self):
print("walks like a duck")
donald = Duck ("donal")
donald.quack()
donald.walk()
print("cual es tu nombre", donald.duck_nombre)
|
#!/usr/bin/python3
"""
function that queries the Reddit API and returns the number of subscribers
(not active users, total subscribers) for a given subreddit.
If an invalid subreddit is given, the function should return 0.
"""
import requests
def number_of_subscribers(subreddit):
main_url = 'https://www.reddit.co... |
from benchmark import benchmark
def iterate_digits(x):
result = []
while x > 0:
result.insert(0, x % 10)
x = x // 10
return result
def is_valid_password(x):
digits = str(x)
if len(digits) != 6:
return False
has_two_consecutive = False
for i, j in zip(digits, ... |
import time
def benchmark(func):
"""
A timer decorator
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
start = time.time()
value = func(*args, **kwargs)
end = time.time()
runtime = end - start
... |
"""Escreva um programa que leia um valor em metros e o exiba convertido em milímetros"""
metros = int(input("Por favor informe uma quantidade em metro: "))
m = metros
km = metros / 1000
h = metros / 100
dam = metros / 10
dm = metros * 10
cm = metros * 100
milimetros= (metros*1000)
print('A medida de {:.1f}m correspon... |
n = int(input("Quantos dias alugado ? "))
x = float(input('Quantos km rodados ? '))
dia = 60
km = 0.15
total = (dia * n) + (x * km)
print('Total a pagar é de R$: {:.2f}'.format(total))
|
n = str(input('Digite uma frase: ')).strip().lower()
print('A letra A aparece {} vezes na frase.'.format(n.count('a')))
print('A primeira letra A aparece na posição {}. '.format(n.find('a')+1))
print('A ultima letra A apareceu na posição {}.'.format(n.rfind('a')+1))
|
#!python
#
# SpellingBee solver. Words containing only letters from a string,
# and word must contain first letter.
#
from english_words import english_words_alpha_set
from typing import List, Tuple, Dict
import sys
class SpellingBee:
def __init__(self, letters: str):
self.letters = letters.lower()
... |
# Python code to find the area of a circle
def area(r):
print("Radius entered: ",r)
pi = 3.14
area = pi * (r**2)
return area
radius = float(input("Enter the radius of the circle: "))
print("Area of circle is: ", area(radius))
|
# Python code to reverse the list items
list = []
num = int(input("Emter the elements to add in the list: "))
for i in range(0,num):
element = int(input("Enter the element: "))
list.append(element)
print("List items:",list)
# Creating an empty list to store the reversed list
rev_list = []
# storing the re... |
# Python code to print negative numbers in a list
lst = []
num = int(input("Enter the number of elements to insert: "))
for i in range(0,num):
ele = int(input("Enter both negative and positive numbers: "))
lst.append(ele)
print("Entered list: ",lst)
print("Negative number in list: ")
for x in lst:
if x... |
# Python code to find whether a number is prime or not
def primeNumber(n):
print("Number entered is: ",n)
if (n<=1):
print("Nither Prime nor composite")
for i in range(2,n):
if (n % i ==0):
print("Not Prime")
else:
print("Prime")
break
n... |
# Python code to find the length of the list
list = []
num = int(input("Enter the number of elements to add in list: "))
for i in range(0,num):
element = int(input("Enter the element: "))
list.append(element)
print("Length of the list is: ", len(list)) |
# Python code to remove unwanted elements form a list(here we are removing even numbers).
# Creating a empty list
lst =[]
# Taking number of inputs
num = int(input("Enter the number of elements to insert in list: "))
# Taking user inputs
for i in range(0,num):
ele= int(input("Enter the number:"))
lst.appen... |
# Python code to find the sum of array
def sumOdArray(arr):
sum = 0
for i in arr:
sum = sum +i
return sum
# defining an empty array
arr=[]
# storing values in the empty array
arr = [12,3,8,75]
# storing array sum in ans variable
ans = sumOdArray(arr)
# printing sum of array
print("Sum of ... |
#coding=utf-8
"""
date:2017-08-19
@author: ray
一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
"""
a = int(raw_input("请输入一个数:\n"))
x = str(a)
flag = True
for i in range(len(x)/2):
if x[i] != x[-i-1]:
flag = False
break
if flag:
print "%d 是一个回文数!" % a
else:
print "%d 不是一个回文数!" % a |
#coding=utf-8
"""
date:2017-08-19
@author: ray
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
"""
'''
a = 2.0
b = 1.0
s = 0
for n in range(1,21):
s += a / b
t = a
a = a + b
b = t
print s
'''
a = 2.0
b = 1.0
l = []
for n in range(1,21):
l.append(a / b)
b,a = a,a + b
print l
print r... |
#coding=utf-8
"""
date:2017-08-17
@author: ray
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
"""
"""
for n in range(100,1000):
i = n/100 #百位上的数
j = n/10%10 #十位上的数
k = n%10 #各位上的数
if n == i**3 + j**3 + k**3:
p... |
# BiYing Pan(bp483)
# CS 171-062
import random
random.seed()
# create a setupDoors()
def setupDoors():
G = 'goat'
G = 'goat'
C = 'car'
doors = ['G', 'G', 'C']
random.shuffle(doors)
return doors
# create a playerDoor()
def playerDoor():
return random.randint(1,3)
# create a montyDo... |
#!/bin/python
#coding=gb2312
from datetime import datetime
import time
import datetime as dt
class DateTimeTool:
def __init__(self):
pass
@staticmethod
def today():
return datetime.today().strftime('%Y%m%d')
@staticmethod
def todayStr():
return datetime.today().strftime('%Y-%m-%d')
@staticmethod
de... |
# k-Nearest Neighbor (by myself) k = 1
# Pros: simple
# Cons:
# computationally intensive(have to iterate through all the points)
# some features are more informative than others, but it's not easy to represent that in KNN.
from scipy.spatial import distance
from sklearn import datasets
from sklearn.model_selection im... |
import random
a = 30
b = int(input("how mant people might show up?"))
c = random.randint(1,16)
food = ("Turkey","Apple Pie","Mashed Potatoes","Mac & Cheese")
total = a + b + c
print("Welcome to my program for Thanksgiving!")
asnwer = "n"
while answer != "y":
for item in food:
print ("W... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.