text stringlengths 37 1.41M |
|---|
from stack import Stack
def postfix(infix_op):
"""Converts operation to postfix from a given
set of mathematical equation"""
prec = {}
prec['/'] = 3
prec['*'] = 3
prec['-'] = 2
prec['+'] = 2
prec['('] = 1
stack = Stack()
_list = []
tokens = infix_op.split()
for token ... |
def add_nums(num1, num2):
"""add two numbers without
addition operators using recursion"""
if num2 == 0:
return num1
else:
return add_nums(num1^num2, (num1&num2)<<1)
print(add_nums(5,7)) |
def knapsack_bottUp(W, wt, val, n):
"""Bottom up dynamic programming to find
the optimal weight/value to add to the knapsack
W = max weight knapsack can hold
wt = array of weights
val = array of values associated to weights
n = length of arrays
"""
# create a matrix of n+1 by W+1 of 0
... |
def knapsack_rec(W, val, weight, n):
"""recursive knapsac problem where
W = max weight knapsack can hold
val = array of values
weight = array of weights associated with values
n = length of the arrays
"""
# Base case
if n == 0 or W == 0:
return 0
# if weight of item is more t... |
class Game:
def __init__(self, definition_file):
self.board = self.__read_board(definition_file)
self.x = 0
self.y = 0
self.trees = 0
self.finished = False
def move(self, offset_x, offset_y):
self.x += offset_x
while self.x > len(self.board[0]) - 1:
... |
hour = int(input("JAM : "))
minu = int(input("MENIT : "))
dura = int(input("DURASI MENIT : "))
cari_jam = (dura + minu) // 60
menit = (dura+minu)%60
jam = (hour+cari_jam)%24
print(jam)
print(menit)
print(jam, ":", menit)
|
# Lab program example to subtract a number from another
# also shows how to read in a string, convert to int for calculation
# Good example of formatting
# Author: Oisin Casey
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
answer = x-y
print("{} minus {} is {} ".format(x, y, answer)) |
# This program reads in a string and strips any leading
# or trailing spaces. It also converts all letters to
# lower case. This program also outputs the length of
# the original string and the normalised one
# Author: Oisin Casey
rawString = input("Please enter a string: ")
normalisedString = rawString.strip().lower... |
# Program takes in a number from user and
# evaluates if it is odd or even using an
# if else statement
# Auhor: Oisin Casey
number = int(input("Enter an integer:"))
if (number % 2) == 0:
print("{} is an even number".format(number))
else:
print("{} is an odd number".format(number)) |
from random import randint
print "Hello!, what's your name?"
username = raw_input("(type your name): ")
print username,", I'm thinking of a number between 1 and 100."
print "Try to guess my number."
secret_number = randint(1, 100)
print secret_number
guess = None
number_of_guesses = 0
while guess is not secret_numb... |
# NO TOUCHING ======================================
from random import choice, randint
# randomly assigns values to these four variables
actually_sick = choice([True, False])
kinda_sick = choice([True, False])
hate_your_job = choice([True, False])
sick_days = randint(0, 10)
# NO TOUCHING ===========================... |
name = input("Input a Name ")
if name == "Arya Stark":
print("Valar Morghulis")
elif name == "Jon Snow":
print("yOu aRe MuH QuEen")
else:
print("Carry on ") |
def combine_words(word,**kwargs):
if(kwargs):
for key,val in kwargs.items():
if key=="suffix":
print(word+val)
elif key=="prefix":
print(val+word)
else:
print(word)
combine_words("child",prefix="man")
combine_words("child",suffix="ish")
combine_words("child")
def comb_words(word,**kwargs):
if "pr... |
print("Hey,How's it going?")
colt = input()
while(colt!="stop copying me!"):
if colt!= "stop copying me!":
print(colt)
colt = input()
print("UGH you win , I give up!") |
for num in range(1,20):
if num == 4 or num == 13:
print("Unlucky Numbers")
elif num%2 == 0:
print("Even")
else:
print("Odd") |
def sum_of_all_list(*args):
sum = 0
for num in args:
sum+= num
return sum
num = [1,2,3,4,5,]
#print(sum_of_all_list(num))----- gives error
print(sum_of_all_list(*num))
def display_names(a,b,c,**kwargs):
print(a+b*c)
print("OTHER STUFF")
print(kwargs)
data = dict(a=1,b=2,c=3,d=55,name="Rya")
print(display_na... |
# from csv import writer
# # def add_user(fname,lname):
# # with open("users.csv","a") as file:
# # headers = ("First Name","Last Name")
# # csv_writer = DictWriter(file,fieldnames=headers)
# # csv_writer.writeheader()
# # csv_writer.writerow(
# # {
# # "... |
animal = input("Enter your favorite Animal ")
if animal:
print(f"{animal} is my favorite too!")
else:
print("You did not answer the question")
#empty objects, empty strings,None and Zero |
from functools import wraps
def only_ints(fn):
@wraps(fn)
def wrapper(*args,**kwargs):
tuple_lst = [x for x in args if type(x)!= int]
if tuple_lst != []:
return "Please only invoke integers"
else:
return fn(*args,**kwargs)
return wrapper
@only_ints
def add(... |
nums = [1,34,4,3,4,531,5,4]
len(nums)
#calls nums.__len__() internally
#print("Hello how are you my darling tonight".__len__())
class SpecialList:
def __init__(self,data):
self._data = data
def __len__(self):
return self._data.__len__() // 2
pass
l1 = SpecialList([1,2,3,4,5,6,7,8,9,10])
print(len(l1))
|
#TemperConvert.py
#for i in range (3):
val = input("Please input a number(for exameple 32C): ")
if val[-1] in ['C', 'c']:
f = 1.8*float(val[0: -1]) + 32
print("The convert num %fF" %f);
elif val[-1] in ['F', 'f']:
c = (float(val[0: -1]) - 32) / 1.8
print("The convert number %fC" %c)
else:
... |
# Initialize offset
offset=8
# Code the while loop
while offset !=0:
print("correcting...")
offset=offset-1
print(offset) |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
... |
month = ["January", "February", "March", "April", "May"]
expenses = [2200, 2350, 2600, 2130, 2190]
print(
f"In {month[1]} you spent {expenses[1]-expenses[0]} extra compare to {month[0]}")
print(f"Total expense in first quarter is ", sum(expenses[0:3]))
print(f"Did you spend exactly $2000 in any month?", 2000 in ... |
def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
# Driver Code
duplicate = [1, 2, 1]
print(Remove(duplicate))
|
odd_max = input("Enter the maximum number of your choice")
odd_max = int(odd_max)
odd_numbers = []
for i in range(1, odd_max+1):
if i % 2 == 1:
odd_numbers.append(i)
print(odd_numbers)
|
import time
def time_convert(sec):
mins = sec // 60
sec = sec % 60
hours = mins // 60
mins = mins % 60
print("Time Lapsed = {2:.3f}".format(int(hours), int(mins), sec))
if time_lapsed == 4:
print("you are on time")
elif time_lapsed > 4:
print("You are too slow")
else:
... |
class Solution(object):
def intersect(self, nums1, nums2):
result = []
for i in range(1, len(nums1)):
for j in range(1, len(nums2)):
if nums1[i] == nums2[j]:
result.append(i)
return result
nums1 = [1, 2, 2, 1]
nums2 = [2, 2, 1]
print(Solution... |
class Solution:
def sockMerchant(self, n, ar):
result = []
for i in ar:
if n == 0:
return 0
else:
if i not in result:
result.append(i)
print((result))
n = 5
ar = 1, 1, 2, 1, 3
print(Solution.sockMerchant([], n, ar)... |
# Solution to https://projecteuler.net/problem=17
import utilities
first_digits = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
second_digits = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
tens = ["ten", "eleven", "twelve", "thirteen", "fourteen... |
class Node:
def __init__(self,data = None):
self.data = data
self.Next = None
class LinkedList:
def __init__(self):
self.head = None
def printlst(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.Next
def addbiggin... |
class Student:
def __init__(self, name: str, roll_number: int, address: str, phone_number: int):
self.name = name
self.roll_number = roll_number
self.address = address
self.phone_number = phone_number
s1 = Student("Sam", 2, "asero", "07048575749")
s2 = Student("John", 3, "ibadan", "... |
# ### Part 2: tf.data
# #### The CIFAR-100 Dataset
# In the second part of this assignment, you will use the [CIFAR-100 dataset](
# https://www.cs.toronto.edu/~kriz/cifar.html). This image dataset has 100 classes with 500 training images and 100
# test images per class. * A. Krizhevsky. "Learning Multiple Layer... |
"""
無名関数 lambda ラムダ式
lambda 引数: 式
複雑な文は書けない
"""
def calc(x, y, c):
return c(x, y)
add = lambda x, y: x + y
sub = lambda x, y: x - y
mul = lambda x, y: x * y
div = lambda x, y: x / y
pwr = lambda x, y: x ** y
print(calc(6, 3, add))
print(calc(6, 3, sub))
print(calc(6, 3, mul))
print(calc(6, 3, div))
print(calc(6, ... |
# encoding=utf8
jobs = {
"John": "Guitar",
"Paul": "Guitar",
"George": "Bass",
"Ringo": "Drums",
}
for name, job in jobs.items():
print("{}: {}".format(name, job))
names = ["John", "Paul", "George", "Ringo"]
for index, name in enumerate(names):
print("{}: {}".format(index, names[index]))
for... |
# Define your Node class below:
class Node:
# define __init__() method that takes two parameters: value and next_node
def __init__(self, value, next_node=None):
# save our vars to self
self.value = value
self.next_node = next_node
#define get_value and next node and return their corresponding ... |
# -*- coding: utf-8 -*-
import random
list = ["け", "も", "の"]
nokemono = ["の", "け", "も", "の"]
mononoke = ["も", "の", "の", "け"]
mokemoke = ["も", "け", "も", "け"]
nokemono_list = ["", "", "", ""]
count = 0
while True:
count += 1
rand_str = list[random.randint(0, len(list) - 1)]
print(rand_str, end='')
nokem... |
""" Python Top Down Shooter - ZombieDungeon
*
*
param:
Author: Stefan Nemanja Banov & Phillip Tran
Date: 06.06.2021
Version: 1.0.0
License: free
Sources:
[1] Fill a two dimensional Array:
Link: https://www.snakify.org/de/lessons/two_dimensional_lists... |
# The smallest positive number that is evenly divisible by all of the numbers
# from 1 to 20?
from math import factorial
def find_smallest_multiple(n):
for i in range(n, factorial(n) + 1, n):
if is_multiple(i, n):
return i
return -1
def is_multiple(x, n):
for i in range(1, n):
... |
"""Working with nan"""
import pandas as pd
val = float('nan') # also np.nan
print(val) # nan
print(val == float('nan')) # False
print(val == val) # False
print(pd.isnull(val)) # True
values = pd.Series([1.2, 2.3, float('nan'), 4.5])
# pd.isnull is a ufunc
print(pd.isnull(values)) # [False, False, True, False... |
def solve(games):
''' Solves the Circle of Defeat problem.
Takes a list of Game objects as input.
Returns an ordered list that represents a solution. '''
# Store a dictionary where keys are teams and values are lists of the teams they've beaten.
won_games = {}
def update_dict(winning_team, game):
if winning_... |
#pe10.py
import math
def isPrime(n):
if n in [0,1]:
return 0
if n == 4 or n == 9:
return 0
if n == 2:
return 1
i = 3
while i <= int(math.ceil(math.sqrt(n))):
if (n % i == 0):
return 0
i = i + 2
else:
return 1
sum = 2
j =... |
# convertData.py
#
# Converts the data:
# Scrapes the data and discards units text (kW, kW/hr, C etc)
# Converts data values from kW to W
# Converts time format to 24 hour format
#
# Input - Data.csv
# Output - convertData.csv
import csv
# Function to convert to 24 hour format
def convert_time(str):
"Converts ... |
#!/usr/bin/env python
"""
Het script vraagt de gebruiker om 2 natuurlijke getallen in te geven en
Deze 2 natuurlijke getallen te vermeerderen, verminderen, vermenigvuldigen of delen
"""
__author__ = "Timo Verbist"
__email__ = "timo.verbist@student.kdg.be"
__status__ = "finished"
# import
def main():
print("We g... |
# Practice problem 2: Add two
# A simple program that adds 2 to a number ten times
def main():
print("This program adds 2 to a number ten times")
x = eval(input("Enter a number: "))
for i in range(10):
x = x + 2
print(x)
main() |
from numpy import array
from numpy import argmax
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import numpy as np
import pandas as pd
from sklearn import preprocessing
# define example
data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']
... |
x = 2 # an int
y = 5 # another int
z = 3.14 # a float
print x + y
if x + y % 2 == 0:
print 'You are doomed'
else:
print 'You are still doomed'
print z
|
"""
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
"""
def addBinary(self, a, b):
#return bin(int(a,2) + int(b,2))[2:]
max_len = max(len(a), len(b))
a = a.zfil... |
"""
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words.
It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the parag... |
"""
Given a linked list, remove the n-th node from the end of list and return its head.
The algorithm makes one traversal of the list of LL nodes. Therefore time complexity is O(L)O(L).
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3... |
#!/usr/bin/env python
# Name: Tiancheng Guo
# Student number: 12455814
"""
This script visualizes data obtained from a .csv file
"""
import csv
import matplotlib.pyplot as plt
import numpy as np
# Global constants for the input file, first and last year
INPUT_CSV = "movies.csv"
START_YEAR = 2008
END_YEAR = 2018
# Gl... |
"""
8. Apply EM algorithm to cluster a set of data stored in a .CSV file. Use the same data set for
clustering using k-Means algorithm. Compare the results of these two algorithms and comment
on the quality of clustering. You can add Java/Python ML library classes/API in the program.
"""
import csv
import matplotlib.... |
import chess
import algorithm
import agent
def evaluate():
"""Evaluates the current status of the board by computing a score.
Calculates a total score which is the combination of two scores: the material
score and the mobility score. The material score is calculated for each piece
with a specific we... |
eps = 1e-5
def find_pi():
start = 0.0
pi = 1.0
prev = 0
while abs(pi - prev) > eps:
prev = pi
start = (2.0 + start)**(1/2)
pi *= (start / 2.0)
return 2*(1/pi)
print(find_pi())
|
#Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
n = int(input("Informe um Número: "))
if(n >= 0):
print("Valor é positivo!")
else:
print("Valor é negativo!") |
#Faça um programa que imprima na tela os números de 1 a 20, um abaixo do outro.
#Depois modifique o programa para que ele mostre os números um ao lado do outro.
for c in range(1, 21):
print(c)
for c in range (1, 21):
print(c, end=' ') |
#Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista.
#Caso o número já exista lá dentro, ele não será adicionado.
#No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
num = list()
aux = 0
resp = 'S'
while True:
aux = int(... |
#Faça um Programa que leia três números e mostre-os em ordem decrescente.
n1 = int(input('Primeiro Número: '))
n2 = int(input('Segundo Número: '))
n3 = int(input('Terceiro Número: '))
if n1 > n2 and n1 >n3:
print(n1)
elif n2 > n3 and n2 > n1:
print(n2)
elif n3 > n1 and n3 > n2:
print(n3)
#agora o numero do ... |
from random import randint
print('=' * 27)
print('PROGRAMA SUA VIDA VALE MAIS')
print('=' * 27)
speed = randint(0, 140)
velocidade = speed
m1 = 280.00
m2 = m1 + (m1 * 10) / 100
m3 = m2 + (m1 * 50) / 100
m4 = m3 + (m1 * 100)/ 100
if speed <= 30:
print('Você está muito devagar, pode atrapalhar a via...')
else:
if... |
#Faça um Programa que leia três números e mostre o maior deles.
n1 = int(input("Informe o Primeiro Número: "))
n2 = int(input("Informe o Segundo Número: "))
n3 = int(input("Informe o Terceiro Número: "))
if((n1 > n2) and (n1 > n3)):
print("O número {} é maior dos Três.".format(n1))
if(n2 < n3):
print("O número {} ... |
#Supondo que a população de um país A seja da ordem de 80000 habitantes com uma taxa anual de crescimento de 3% e que a população de B seja 200000 habitantes
#com uma taxa de crescimento de 1.5%. Faça um programa que calcule e escreva o número de anos necessários para que a população do país A ultrapasse ou iguale a
... |
#Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo compreendido por eles.
num1=int(input("digite um numero--> "))
num2=int(input("digite outro numero--> "))
while num2<num1:
num1=int(input("digite um numero--> "))
num2=int(input("digite outro numero--> "))
else:
for... |
#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 3 metros quadrados
#e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00.
#Informe ao usuário a quantidades de latas de tinta ... |
#Tendo como dados de entrada a altura de uma pessoa,
#construa um algoritmo que calcule seu peso ideal,
#usando a seguinte fórmula: (72.7*altura) - 58
'''alt = float(input('Digite sua altura: '))
form = (72.7 * alt) - 58
print(form)'''
#Tendo como dados de entrada a altura e o sexo de uma pessoa,
#construa um algoritmo... |
n1 = float(input('Primeira Nota: '))
n2 = float(input('Segunda Nota: '))
m = (n1 + n2) / 2
if m < 5:
print('Aluno tirou nota {:.1f} e {:.1f} e sua média foi {}.'.format(n1, n2, m))
print('REPROVADO.')
elif m >= 5 and m < 7:
print('Aluno tirou nota {:.1f} e {:.1f} e sua média foi {}.'.format(n1, n2, m))
... |
#Faça um programa que leia 5 números e informe o maior número.
maior = 0
for c in range(1, 6):
n = int(input(f'Informe o {c} número: '))
if n > maior:
maior = n
print(f'O maior número informado foi {maior}.') |
#Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
sexo = str(input("Informe se sexo [M] - Masculino e [F]Feminino: ").upper())
if(sexo == "M"):
print("Sexo Masculino")
elif(sexo == "F"):
print("Sexo Feminino")
else:
print("Você ... |
#charset-utf8
#Vetores do Programa
listaFilmes = []
listaAvaliacoes = []
#Dicionário do Programa
filmes = {}
#Variáveis
opcao = 0
avalia = 0
#Inicio do Programa
while opcao != 8:
print("============================================")
opcao = int(input('[1] - Inserir Filme\n'
'[2] - Listar... |
#Faça um Programa que peça os 3 lados de um triângulo.
#O programa deverá informar se os valores podem ser um triângulo.
#Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
#Dicas:
#Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro;
#... |
print('Antes de entrar no looping ')
for item in range(0, 10):
print(item)
if (item == 6):
print('A condição estabelecida retornou True')
break
print('Depois de sair so looping ')
'''Usando o break eu posso parar o meu laço no ato onde eu indicar .
ou seja posso fazer um laço para otimizar ... |
print('='*27)
print('==== Lista de Compras =====')
print('='*27)
preco = float(input('Preço total das compras: R$'))
print('''Qual a forma de pagamento que deseja realizar:
[1] à vista Dinheiro/Cheque com 10% de desconto. '
[2] à vista com cartão com 5% de desconto. '
[3] em até 2x no cartão: preço normal.'
[4] em at... |
#Faça um programa que calcule o mostre a média aritmética de N notas.
qtd = int(input('Informe quantas notas quer ler: '))
c = 1
soma = n = 0
while c <= qtd:
while n < 0 and n > 10:
n = float(input('Informe a {} ª nota: '.format(c)))
soma = soma + n
c += 1
media = soma / qtd
print(f'A media das notas é {media:.... |
#AnaliseDedadosEmUmaTupla
n = (int(input('Informe um Número: ')),
(int(input('Informe um Número: ')),
(int(input('Informe um Número: ')),
(int(input('Informe um Número: ')),
(int(input('Informe um Número: ')))
for c in n:
if c % 2 == 0:
print(n, end=' ')
print(f'Você Digitou os valores {n}')
print(f'O valor 9 a... |
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
#Calcule e mostre o total do seu salário no referido mês.
hora = float(input("Informe qual o valor da sua hora de trabalho: "))
qtdHora = int(input("Informe a quantidade de horas que você trabalha por semana: "))
mes = qt... |
# 3.1 Разработка прототипа приложения “Регистрация на конференцию” на основе фрагмента технического задания с использованием ООП.
import re
class Conf():
log = []
def __init__(self, dicts):
self.name = dicts["name"]
self.sname = dicts["sname"]
self.email = dicts["email"]
self.city = dicts["city"]... |
#returns i as a list of digits
def int_to_list(i):
list = [int(x) for x in str(i).zfill(1000)]
while list[0] == 0:
list.remove(0)
return list
#returns a list of the factors of i
def list_factors(i):
factors = []
m = 2
while m <= i:
if i%m == 0:
i /= m
factors.append(m... |
#returns the digits if i as a list
def int_to_list(i):
list = [int(x) for x in str(i).zfill(8)]
while list[0] == 0:
list.remove(0)
return list
list_of_decimals = []
x = 1
while len(list_of_decimals) < 1000000:
for y in int_to_list(x): list_of_decimals.append(y)
x += 1
out = li... |
#returns i as a list
def int_to_list(i):
list = [int(x) for x in str(i).zfill(1000)]
while list[0] == 0:
list.remove(0)
return list
#returns l as an int
def list_to_int(l):
return int("".join(str(x) for x in l))
out = 0
mults = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for n in range... |
cor = {
'fim':'\033[m',
'amarelo':'\033[1;033m',
'amarelof':'\033[7;033m',
'vermelho':'\033[1;031m',
'vermelhof':'\033[7;031m',
'azul':'\033[1;034m',
'verde':'\033[1;32m',
'verdef':'\033[7;32m',
'branco':'\033[1;030m'
}
primeiro = int(input('\nInsira o{} PRIM... |
cor = {
'fim':'\033[m',
'amarelo':'\033[1;033m',
'amarelof':'\033[7;033m',
'vermelho':'\033[1;031m',
'vermelhof':'\033[7;031m',
'azul':'\033[1;034m',
'verde':'\033[1;32m',
'verdef':'\033[7;32m',
'branco':'\033[1;030m'
}
primo = int(input('\nInsira um{} NÙMERO... |
velocidade = eval(input('\nInforme sua velocidade: '))
delta = velocidade - 80
if velocidade <= 80:
print('Parabéns, motorista consciente\n')
else:
print('Você foi multado por estar {:.0f}km/h acima da velocidade permitida'.format(delta))
print('Sua multa será de R${:.2f}\n'.format(delta * 7))
|
inteiro = eval(input('Insira um valor float para receber um inteiro: '))
print('O valor inteiro de {} é {:.0f}'.format(inteiro, inteiro // 1)) |
#MEU IMC
def imc(p,a):
'Funcção para cálculo de IMC onde p recebe o peso e a recebe altura'
if p/a**2 < 18.5:
print('Você está abaixo do peso')
elif p/a**2 >= 18.5 and p/a**2 < 25:
print('Você está com peso normal')
else:
print('Você está acima do peso')
|
a = eval(input('Insira um valor para A\n'))
b = eval(input('Insira um valor para B\n'))
c = eval(input('Insira um valor para C\n'))
if a == b and b == c:
print('Triangulo equilátero\n')
elif a == b or c == b or a ==c:
print('Triangulo Isóceles\n')
else:
print('Triangulo Escaleno\n')
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import random, string
class random_password():
def __init__(self):
self.char = string.printable[:-11]
def create_random_password(self, chars=None, seq=8):
if (chars != None) and (chars != ''):
self.char = chars
if seq >= len(self... |
#there are three types of setup and teardown which we can use
# 1st is setup and tear down method - these executes for each function i.e setup will execute before each
# function in a class and tear down method will execute after each function in a class
# 2nd is setup and tear down class - setup class will execute one... |
import requests
import urllib.request
from bs4 import BeautifulSoup
import sys
the_list = []
def check_readme(url):
print("url is :" + url)
req = requests.get(url) #requests url contents
soup = BeautifulSoup(req.text, "html.parser") #uses bs4 which parses the contents using html.parser
for link in soup.find_all(... |
import pandas as pd
import matplotlib.pyplot as plt
from data import games
# Select the attendance data from the games dataframe
attendance = games.loc[(games['type'] == 'info') & (games['multi2'] == 'attendance'), ['year', 'multi3']]
# Rename the columns
attendance.columns = ['year', 'attendance']
# Convert the att... |
from todo import Todo
class TodoList:
def __init__(self):
# properties
# - todo
self.todos = []
def display(self):
for todo in self.todos:
print(todo)
def add(self, title):
# instanciate a new Todo object
new_todo = Todo(title)
s... |
# problem and test cases:
# @hackerrank: https://www.hackerrank.com/challenges/simple-text-editor/problem
currentStr =""
Q = int(input())
stack=[]
for i in range(Q):
query = list(input().split(" "))
if(query[0]=='1'):
currentStr+=str(query[1])
stack.append({"add":len(str(query[1]))})
elif(q... |
with open('input.txt') as f:
numbers = [int(line.rstrip()) for line in f]
def part_one():
for n1 in numbers:
for n2 in numbers:
if n1 + n2 == 2020:
print(n1*n2)
return
def part_two():
for n1 in numbers:
for n2 in numbers:
for n3 in ... |
# adding the cubes of the same number like 45 add 4 cube + 5 cube
# 783//10 -> 78 {floor operator }
# if the sum of the cubes of the digits of the numbers is equal to the number itself called armstrong numbers
# % -----> used for finding the remainder .
user_input = int(input("provide_a_number : "))
sum = 0
t... |
# sets can't have the elements as lists and dictionary
# list can consists of sets but sets can't contain lists
# sets doesn't print repeated elements
num_set = {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 , 9}
for i in num_set:
print(i)
num_set.remove(4)
print(num_set)
|
# odd and even using define
def odd_even(number):
if (number % 2 == 0):
print(number , " : is even.")
else:
print(number , " : is odd.")
number = int(input("provide_a_number_to_chech_its_odd_or_even: "))
odd_even(number)
|
# alphabet decider
chr = input("provide_charecter: ")
asci = ord(chr)
if (ord("A") <= asci and ord("Z")>= asci):
print(chr+"is capital")
elif (ord("a") <= asci and ord("z")>= asci):
print(chr ,"is small ")
else:
print("not a chr")
if ((chr == 'a') or (chr == 'i') or (chr == 'o') or (chr == 'e')... |
# count of same alphabets at the end and starting of word and if word is equal to length three the count will increase
list = []
count = 0
count_same = 0
user_input = int(input("how_many_elements_do_you_want_in_list_1: "))
for i in range(1 , user_input + 1 ):
no_elements = input("enter_element_" + str(i)... |
# finding a perfect number in a range
def perfect_number(x):
sum = 0
for i in range(1 , x):
remainder = x%i
if remainder == 0:
sum += i
if sum == x:
return 1
#print(x , "is a perfect number : - ) ")
else:
return 0
#print(... |
#string slicing
var = "HELLO WORLD ! "
print(len(var))
print(var.strip())
print(var.title())
print(var.upper())
print(var.lower())
# very very case sensitive
print(var.replace("HELLO","HI"))
print(var.find("o"))
#to find a word in a string
# it takes the var in boolean
# it is also case sensitive
x = ... |
#height in feet and inches and outout in cm
#volume of sphere .
height_inches = float(input("height_in_inches: "))
height_feet = float(input("height_in_feet: "))
name = input("your_name: ")
net_inches = float( height_inches + (height_feet*12))
print(name,"\'s, height in centimeters:",net_inches*2.54)
|
# define function
# def():
number_1 = float(input("provide the system with a number_1 : "))
number_2 = float(input("provide the system with a number_2 : "))
number_3 = float(input("provide the system with a number_3 : "))
def larger_number(a, b):
if (a > b):
return a
return b
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.