text
stringlengths
37
1.41M
"""Diet Program Example for Linear Programming. - Author: Kyeongmin Woo - E-mail: wgm0601@gmail.com - Desc: - Minimize costs of all foods that meet nutritional requirements. - c_j: cost of the food j. - d_i: nutritional requirements for nutrient i. - D_{i,j}: degree to which nutrient i in the food j. ...
def numDecodings(s: str) -> int: if len(s) == 0 or (len(s) == 1 and s[0] == '0'): return 0 return numDecodingsHelper(s, len(s)) def numDecodingsHelper(s: str, n: int) -> int: if n == 0 or n == 1: return 1 count = 0 if s[n-1] > "0": count = numDecodingsHelper(s, n-1) i...
nums=[8,1,9,4,2] for i in range(len(nums)-1,0,-1): for j in range(i): if nums[j]>nums[j+1]: temp=nums[j] nums[j]=nums[j+1] nums[j+1]=temp nums2=[5,4,3,1,2] for i in range(len(nums2)): minpos=i for j in range(i,len(nums2)): if nums2[j]<nums2[minpos]: ...
""" User can input currency and header if under valid constraints and then move on to selections""" # global conversions dictionary conversions = { "USD": 1, "EUR": .9, "CAD": 1.4, "GBP": .8, "CHF": .95, "NZD": 1.66, "AUD": 1.62, "JPY": 107.92 } # global home currency variable home_cur...
#Aqui se cambia el titulo print("Demo para Reunion de Ingenieria") print("sesion: DevOps") print("\n by: moacosta / hegarcia \n") #asignacion de variables numA = int(input("Valor de A: ")) numB = int(input("Valor de B: ")) #sumatoria de numeros print("resultado de A + B : ", numA+numB ) #Agregar la resta print("res...
game_board = { '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '} board_space = [] for key in game_board: board_space.append(key) def printBoard(board): print('\t'+ board['7'] + '|' + board['8'] + '|' + board['...
qt = int(input('Quantas conjuntos você deseja inserir: ')) result = [] for x in range(qt): n = list(map(int, (input('Digite 3 números números: ').split()))) n.sort() result.append(n[0]) print(result)
''' 希尔排序:小块的插入排序! ''' def shell_sort(aList): n = len(aList) step = n // 2 # 增量 while step > 0: for i in range(step, n): # 各子部分插入排序 while i >= step and aList[i] < aList[i-step]: aList[i], aList[i-step] = aList[i-step], aList[i] i -= step print('排序中...
''' 插入排序:每次新加一个元素,交换找到合适的位置 ''' # 写法一: # def insert_sort(aList): # n = len(aList) # for i in range(0, n): # j = i # while j > 0: # if aList[j] > aList[j-1]: # aList[j], aList[j-1] = aList[j-1], aList[j] # j -= 1 # 写法二: def insert_sort(aList): n = len(...
while True: try: data = input() result = [] for i in data: if i not in result: result.append(i) print(''.join(result)) except: break
class Game(object): """""" def __init__(self,player,dealer,deck): #set up the initial self.player = player self.dealer = dealer self.deck = deck def play(self): ''' Run the game once ''' self.deck.shuffle() self.player.hand.empty_hand() ...
while(True): cont=0 bruh=0 b = input() a = b.lower() if(a=="*"): break for i in range(len(a)): if(a[i]==" "): bruh+=1 if(a[0]==a[i+1]): cont +=1 if(cont==bruh): print("Y") else: print("N")
# Erik Fisher # 6/18/2018 - Day 1 # CS 61A Notes # Introduction to Python # Expressions: 20 + 17 or sin(pi) # Operators: +, -, /, * # Call Expressions: add(2, 3) # operator(operand, operand) from operator import add, mul print(add(add(6, mul(4,6)), mul(3,5))) # prints 45 # demo of finding string inform...
# read full name from keyboard full_name = input() # initialize empty list to store each full name character as an entry reversed_list = [] # initialize empty string to store the reversed full name nome = '' # run for all characters inside full name string for i in range (len(full_name)): # insert the actual char...
# register # --first name, last name, password, email # --generate user account # login # --account number and password # bank operations # initializing the system import random import validation import database from getpass import getpass account_number_from_user = None def init(): print("Welcome to bankPHP"...
#COUNT LETTER def count_letter(word,letter): count = 0 for alpha in word: if alpha == letter: count += 1 return count count = count_letter("banana","a") print(count) #SLICER def slicer(): word = "banana" print(word[1:4]) slicer() print("====================================") ...
#def my_function(name,age): #print(name + "is" + age + "yrs old") #first_name = input("Enter your name: ") #age = input("Enter your age: ") #print("you are "+ first_name+ " and you are "+age+ " years old") def greet(name): print(f"hello {name} hw do you do?") return print("======") greet("jack") def ...
# Example of Abstract Method # This Example show that how one Method overrides another methods by same name # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # from abc import ABC,abstractmethod class Polygon(ABC): def noofsides(self): pass class Triangle(Polygon): # ...
# Example of running mutiple threads concurrently. # When you will run this program you will observe that # sometimes it will print Ram and sometimes it will print Shyam # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # import threading def my_thread(name): for i in range(...
# Example of Python Functions using def keyword # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # #Function definition def sum( a,b ): "It sumd two numbers" print('a',a,'b',b) c = a + b return c; print(sum(5,10)) print(sum(10,20)) #keyword argument d = sum(b=7,a=8)...
# Example of Encapsulation # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # class Person: #constructor def __init__(self): #instance variable self.name = "No name" #Method def display(self, name): print( "Hello", name) obj = P...
from datetime import date def calculateAge(birthDate,currentDate): today = date.today() age = currentDate.year - birthDate.year - ((currentDate.month, currentDate.day) <(birthDate.month, birthDate.day)) return age year=int(input("Enter your Birth Year = ")) month=int(input("Enter your Birth Mont...
# Example of TRY CATCH # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # a =4 b = 2 try: c= a/b print('C:',c) except ZeroDivisionError: print("check your divident is Zero") else: print("Your divident was greater than zero") finally: print("Exception testing is...
# Example of Comparison Operator # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # num1 = 10 num2 = 20 num3 = 50 print("Is Num3 > Num2=", num3 > num2) print("Is Num2 = Num3=", num3 == num2) print("Is Num1 != Num2", num1!= num2)
# Example of Creating Tuple # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # #creating tuple my_tuple = () print(my_tuple) #tuple of int, float, string tuple_list1 = (1, 2.8, "Hello Ram") print(tuple_list1) # tuple of string and list tuple_list2 = ("Book", [1, 2, 3]) print(tu...
# Example to find string using findall() # # @author SunilOS # @version 1.0 # @Copyright (c) SunilOS # @Url www.SunilOs.com # import re string = "The rain in Spain" result = re.findall("ai", string) print(result) if (result): print("YES! We have a match!") else: print("No match")
# -*- coding: utf-8 -* import pandas as pd import math import numpy as np import random import matplotlib.pyplot as plt class classifier(object): def __init__(self,dataSet): self.dataSet = dataSet def dist(num1, num2): t = (num1 - num2) ** 2 return float(t ** 0.5) def mean_dist(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # http://scikit-learn.org/stable/modules/feature_selection.html # 1.13.1. Removing features with low variance """ from sklearn.feature_selection import VarianceThreshold X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] sel = VarianceThreshold(threshold...
#-*-coding:utf-8-*- import string def WordFilter(sentence): """ 从一个句子或者文章段落中过滤出所有单词 返回一个字典,key为单词,value为出现次数 """ words = {} strip = string.whitespace + string.punctuation + string.digits + "\"'" for word in sentence.split(): word = word.strip(strip) if len(word) >= 2: ...
queijo = 50 presunto = 50 hamburguer = 100 qntHamburger = 0 while 1==1: try: qntHamburger = int(input("Insira o numero de hamburguers:\n")) break except ValueError: print("Valor invalido!") qntQueijo = qntHamburger*queijo*2 qntPresunto = qntHamburger*presunto qntHamburguer = qn...
# Acá va a un comentario if 3 > 5: # Acá va a un comentario print('Esto no se va a imprimir') # if 5 > 3: # Acá va otro comentario # print('5 es mayor a 3') x = 5 y = 'chanchito feliz' print(x, y) correo = 'chanchito@feliz.com' print(correo) _mi_var = 'chanchito' MIVAR = 'chanchito' a, b, c = 'Lala', 'Le...
# The lambda keyword in Python provides a shortcut for declaring small # anonymous functions. add = lambda x, y: x + y print(add(4, 6)) print((lambda x, y: x + y)(3, 5)) # ------------------------------------------------------ # Lambdas You Can Use # ------------------------------------------------------ tuples = [(...
""" Problem You have a collection of sorted sequences and you want to iterate over a sorted sequence of them all merged together. """ # Solution # The heapq.merge() function does exactly what you want. For example: import heapq a = [1, 4, 7, 10] b = [2, 5, 6, 11] for c in heapq.merge(a, b): print(c) # The iter...
# coding=utf-8 """"Factorial implemented with reduce and an anonymous function.""" from functools import reduce def fact(n): return reduce(lambda a, b: a * b, range(1, n + 1)) print(fact(5))
# Assignment statements in Python do not create copies of objects, # they only bind names to an object. For immutable objects, # that usually doesn't make a difference. # Way to clone the object # new_list = list(original_list) # new_dict = dict(original_dict) # new_set = set(original_set) # Making Shallow Copies x...
""" Problem You want to iterate over a sequence, but would like to keep track of which element of the sequence is currently being processed. """ # Solution # The built-in enumerate() function handles this quite nicely: my_list = ['a', 'b', 'c'] for idx, val in enumerate(my_list): print(idx, val) my_list = ['a', ...
# coding=utf-8 """Variable b is local, because it is assigned a value in the body of the function.""" '''But the fact is, when Python compiles the body of the function, it decides that b is a local variable because it is assigned within the function. The generated bytecode reflects this decision and will try to fetch...
""" Problem Your application receives temporal data in string format, but you want to convert those strings into datetime objects in order to perform nonstring operations on them. """ # Solution # Python’s standard datetime module is typically the easy solution for this. For example: from datetime import datetime te...
""" Problem You’re trying to match a text pattern using regular expressions, but it is identifying the longest possible matches of a pattern. Instead, you would like to change it to find the shortest possible match. """ # Solution # This problem often arises in patterns that try to match text enclosed inside a pair of...
""" Problem You have code that uses a while loop to iteratively process data because it involves a function or some kind of unusual test condition that doesn’t fall into the usual iteration pattern. """ # Solution # A somewhat common scenario in programs involving I/O is to write code like this: def process_data(dat...
# coding=utf-8 """average.py: a higher-order function to calculate a running average.""" def make_averager(): series = [] def averager(new_value): series.append(new_value) total = sum(series) return total/len(series) return averager avg = make_averager() print(avg(10)) print(a...
""" Problem You have multiple dictionaries or mappings that you want to logically combine into a single mapping to perform certain operations, such as looking up values or checking for the existence of keys. """ # Solution # An easy way to do this is to use the # ChainMap class from the collections module. from colle...
""" Problem You’ve written a function, but would like to attach some additional information to the arguments so that others know more about how a function is supposed to be used. """ # Solution # Function argument annotations can be a useful way to give programmers hints about # how a function is supposed to be used. ...
""" Problem You would like to define a generator function, but it involves extra state that you would like to expose to the user somehow. """ # Solution # If you want a generator to expose extra state to the user, don’t forget that you can easily # implement it as a class, putting the generator function code in the __...
"""" Problem You have an N-element tuple or sequence that you would like to unpack into a collection of N variables. """ p = (4, 5) x, y = p print(x, y) data = ['ACME', 50, 91.1, (2012, 12, 21)] name, shares, price, date = data print(name, shares, price, date) name, shares, price, (year, mon, day) = data print(year,...
def insertionsort(y): for i in range(1,len(y)): for j in range(i,0,-1): if y[j]<y[j-1]: y[j],y[j-1]=y[j-1],y[j] yield y
""" ORIGINAL Write a function that returns a string in which firstname is swapped with last name. name_shuffler('john McClane'); => "McClane john" """ """ SIMPLIFIED 1) Given a string with two words 2) Split the string 3) Return the words in reverse order """ def name_shuffler(str_): return " ".join(...
""" ORIGINAL Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50. Links referring to logical operations: AND, OR and XOR. First Example: Input: true, true, false, operator: AND Steps: true AND true -> true, true AND false -> false Output...
""" ORIGINAL Remove n exclamation marks in the sentence from left to right. n is positive integer. Examples remove("Hi!",1) === "Hi" remove("Hi!",100) === "Hi" remove("Hi!!!",1) === "Hi!!" remove("Hi!!!",100) === "Hi" remove("!Hi",1) === "Hi" remove("!Hi!",1) === "Hi!" remove("!Hi!",100) === "Hi" remove("!!!Hi !!h...
""" ORIGINAL Alright, my list is messy! Help me clean it up! First, start by moving the 1 from index 3 to index 0. Try to do this in a single step by using both .pop() and .insert(). It's OK if it takes you more than one step, though! """ """ SIMPLIFIED 1) Move 1 from index 3 to index 0 """ messy_list = ["a"...
""" ORIGINAL Ahoy Matey! Welcome to the seven seas. You are the captain of a pirate ship. You are in battle against the royal navy. You have cannons at the ready.... or are they? Your task is to check if the gunners are loaded and ready, if they are: Fire! If they aren't ready: Shiver me timbers! Your gunner...
""" ORIGINAL This is the first step to understanding FizzBuzz. Your inputs: a positive integer, n, greater than or equal to one. n is provided, you have NO CONTROL over its value. Your expected outputs: an array of positive integers from 1 to n Your job is to write an algorithm that gets you from the input to th...
#!/usr/bin/env python def primes_sieve2(limit): a = [True] * limit a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: yield i for n in xrange(i*i, limit, i): a[n] = False print str(n) + " quitado" import sys print list(primes_...
#!/usr/bin/python import random cnt = 0 # control code length rand = 0 # generate code pincode ='' # last code codelist = ('0','1','2','3','4','5','6','7','8','9') for cnt in range(0,6): pincode=pincode+codelist[int(random.uniform(0,9))] cnt+=1 print 'pin is : %s' % pincode
class Bola: def __init__(self, cor, circunferencia, material): self.cor = cor self.circunferencia = circunferencia self.material = material def trocar_cor(self, cor): self.cor = cor def mostrar_cor(self, cor): print(cor) while True: obj = Bola(str(input('Cor d...
""" Optuna example that optimizes multi-layer perceptrons using PyTorch. In this example, we optimize the validation accuracy of hand-written digit recognition using PyTorch and MNIST. We optimize the neural network architecture as well as the optimizer configuration. As it is too time consuming to use the whole MNIST...
""" Optuna example that optimizes convolutional neural network and data augmentation using FastAI V1. In this example, we optimize the hyperparameters of a convolutional neural network and data augmentation for hand-written digit recognition in terms of validation accuracy. The network is implemented by fastai and eva...
""" Optuna example that optimizes a neural network regressor for the wine quality dataset using Keras and records hyperparameters and metrics using MLflow. In this example, we optimize the learning rate and momentum of stochastic gradient descent optimizer to minimize the validation mean squared error for the wine qua...
import math def round_int(n): if n >= math.floor(n) + 0.5: return math.ceil(n) return math.floor(n) temps = list(map(int, input().split(" "))) for i in range(1,len(temps)): print(round_int((temps[i]-32)*(5/9)), end=" ")
import string import math import itertools def convert_arr_int(arr): new_arr = [] for e in arr: new_arr.append(int(e)) return new_arr def main(): with open("word.in", "r") as words_file: words_input = words_file.read().split("\n") words_info = words_input[0].split(" ") # n: t...
# *-* coding: utf-8 *-* valor_hora = float(input("Informe o valor pago pela hora de trabalho: ")) quantidade_hora = float(input("Informe a quantidade de horas trabalhadas no mês: ")) salario = valor_hora * quantidade_hora print("Valor da hora R$ {}, quantidade de horas trabalhadas no mês {}. " "Salário a receb...
def check_AB(kalimat): list_a = [] list_b = [] list_ab = [] for i in range(len(kalimat)): if kalimat[i] == "a": list_a.append(i) for i in range(len(kalimat)): if kalimat[i] == "b": list_b.append(i) for a in list_a: ...
def mostFrequentItem(arr) : set_item = set(arr) list_item = list(set_item) kamus = {} list_count = [] hasil = [] swapped = True while swapped: swapped = False maxIter = len(list_item)-1 for i in range(maxIter): val1 = arr.count(list_item[i]) v...
import threading import time from queue import Queue def thread1_func(lock,q): count = 1 while True: lock.acquire() print(q.qsize()) time.sleep(1) q.put(count) print(f"thread {threading.current_thread().name} putted {count} to queue") count += 1 ...
''' For creating objects, a class is like a blueprint. An obj has props and methods. Almost everything in Python is an obj ''' # Create class class User: # Constructor - a func that runs when you instantiate an obj from a class # self is like 'this' def __init__(self, name, email, age): self.name = name ...
# single line comment ''' Multiline comment/docstring (used to define a function's purpose) can be single or double quotes ''' """ Vars must start with a letter or an underscore - Can have numbers, but not start with one """ # x = 1 # cast as int as default # y = 2.5 # float # name = 'john' #...
import numpy as np from os import system import random ROWS = 6 COLUMNS = 7 IN_A_ROW = 4 EMPTY = 0 PLAYER = 1 CPU = 2 CPU_IS_FIRST = True CPU_WIN_BIAS = 10000000000 CPU_3_BIAS = 10 CPU_2_BIAS = 5 PLAYER_WIN_BIAS = -10000000 PLAYER_3_BIAS = -10000000 PLAYER_2_BIAS = -100 CENTER_BIAS = 4 CPU_DEPT...
import sys print ("Hello, Python!"); days = ['Monday', 'Tuesday'] paragraph = """This is a test paragraph. I want to see if you can keep going with it.""" item_one = "testing one " item_two = "testing two " item_three = "testing three" a = 5 b = 20 numList = [1,2,3,4,5] testList = ['brian','getz','program','python'...
import sys import spotipy import spotipy.util as util from Tkinter import * def print_array(tracks): for x in tracks: print x def print_results(sets): print "DUPLICATES" print_array(sets[2]) print "LIST 1" print_array(sets[0]) print "LIST 2" print_array(sets[1]) def make_string(a...
def findDigits(): for t in range(int(raw_input())): n = int(raw_input()) digits = [] x = n while x > 0: digits.append(x%10) x/=10 count = 0 for digit in digits: if digit != 0: if n%digit == 0: cou...
# -*- coding: utf-8 -*- """ Created on Mon Aug 05 04:12:52 2019 @author: catas """ import numpy as np import math import matplotlib.pyplot as plt print X = np.arange(-30,-20, dtype=np.float) Y1 = [] Y2 = [] for x in X: #Para valores practicos y = 1. t = 1. k = 1. while y ...
from datetime import datetime def obter_limite(): print("Bem Vindo à Loja de Jakeline Victor Pereira! Esta é a melhor Loja da Cidade! ") cargo = input('Informe seu cargo: ') salario = float(input('Informe seu salario: ')) ano_de_nascimento = int(input('Informe o ano de nascimento: ')) data_e_hora...
# -*- coding: utf-8 -*- def format_output_date(date, lang='ne'): if lang: date = date[lang] return '{} {} {}, {}'.format(date['year'], date['str_month'], date['day'], date['str_day_of_week']) def format_input_date(year, month, day): return '{}/{}/{}'.format(year,...
#!/usr/bin/env python # Logs Analysis Project by Leonardo Quitto # PostgreSQL database adapter for the Python programming language import psycopg2 import sys # Built-in Database provided by Udacity to complete this project DBNAME = "news" _question1 = """SELECT articles.title AS articles,count(log.path) AS ...
from pyagora.system import TradeExecutionException class LimitOrderException(Exception): pass class TradingAccount(object): def __init__(self, name, cash, inventory): self.name = name self.cash = cash self.inventory = dict(inventory) self.sell_trades = list() self.bu...
def valid_year(year): if year and year.isdigit: year = int(year) if year >1900 and year <2010: return year
class Employee: def __init__(self, first, last): self.first = first self.last = last @property def fullname(self): return '{} {}'.format(self.first, self.last) @fullname.setter def fullname(self, name): first, last = name.split() self.first = first s...
#27-03-21 from collections import namedtuple Location = namedtuple('Location', 'row column') Shape = namedtuple('Shape', 'width height') class GameBoard: #CREATOR #c it's columns/width #r it's rows/height def __init__(self, shape): #check whether shape is a Shape data type assert isi...
import numpy as np import numbers import torch from scipy.ndimage.interpolation import rotate def normalize_float(ndarr, min=-1): """Performs min-max normalization on a `numpy.ndarray` matrix. Parameters ---------- ndarr : numpy.ndarray The numpy array to normalize min : int/float ...
from StickyDicT import * from time import sleep # Create Sticky Dict called todo-list SD = Sticky('todo-list') # Make our Dict a list SD.Dict = list() # Add grocery shopping to the todo list SD.Dict.append("grocery shopping") # Verify todo list is in the cloud todo = OrmanNameSpace().sync()["stickies"]["todo-list"] pri...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # wykorzystana funkcja sum() def avg(input): return sum(input)/len(input) print(avg([2,2,2,2,2,2]) - 2 < 0.0000001) print(avg([4, 6, 55, 18, 17, 12]) - 18.666666666666668 < 0.0000001) print(avg([86, 89, 24, 45, 62, 17, 61, 63, 30, 13]...
from sys import exit from random import randint class Scene(object): def enter(self): self.scene = CentralCorridor() print self.scene exit(1) class Engine(object): def __init__(self, scene_map): print "Engine __init__ has scene_map", scene_map self.scene_map = scene_map def play(self): current_scene =...
import random #import time def fight(p,m,i): enemies = m.get_enemies() damage_modifier = random.randint(0,len(enemies)) turn = 0 while len(enemies) > 0: #time.sleep(1) turn+=1 while True: print("\nTurn: "+ str(turn)+"\n") #clear() #time.sleep(1) player_in = input("play (p) or heal (h)? ") #tim...
class TrieNode(object): def __init__(self): self.is_end = False self.child = [0] * 26 class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.__root = TrieNode() def addWord(self, word): """ Adds a...
# -*- coding:utf8 -*- # 基数排序 分MSD和LSD import math def LSDSort(array, d): i = 0 while i < d: s = [[] for _ in xrange(10)] for x in array: s[x/(10**i)%10].append(x) array = [y for x in s for y in x] i += 1 return array def generate(array, i, d): if i < 0: ...
# -*- coding:utf8 -*- # 插入排序 def insertSort(array): newarray = [] for x in array: for i in xrange(len(newarray)+1): if i == len(newarray) or x < newarray[i]: newarray.insert(i, x) break return newarray print insertSort([1,3,5,9,4,2,7,3])
class ListNode(object): def __init__(self, x): self.val = x self.next = None def printval(self): print self.val class Solution(object): def hasCycle(self, head): fastindex = head slowindex = head meetindex = None while fastindex and slowindex: ...
''' Created on Feb 25, 2018 @author: Shilpa ''' print("This line will be printed.") x = 1 if x==1: # indent four spaces print("x is 1.") myint = 7 print(myint) myfloat = 7.0 print(myfloat) myfloat = float(7) print(myfloat) mystring = "Don't worry about apostrophes" print(mystring) one = 1 two = 2 thre...
class Etiqueta: def __init__(self, codigo: int): self.codigo = codigo self.etiqueta = self.criar_etiqueta(codigo) def criar_etiqueta(self, codigo): return str(codigo) + 'ABCD' def __repr__(self): return f'<Etiqueta {self.codigo} {self.etiqueta} >' class Produto: def ...
def encode(codestring): '''alphabet to reverse alphabet in groups of 5 letters''' # format the codestring codestring = codestring.lower() codestring = codestring.replace(" ", "") codestring = codestring.replace(",", "") codestring = codestring.replace(".", "") # encode into reverse alp...
from functools import reduce def square_of_sum(num): '''Sum the numbers, then square the total''' # create range num_list = list(range(1, num+1)) # reduce range reduced_num = reduce(lambda x,y: x+y, num_list) # square the total square_of_sum = reduced_num**2 return square_of_sum def s...
import operator NORTH = (0, 1) EAST = (1, 0) SOUTH = (0, -1) WEST = (-1, 0) class Robot(object): """Simulates a robot with three possible movements: left turn, right turn and advance""" def __init__(self, bearing=NORTH, x=0, y=0): self.x = x self.y = y self.coordinates = (self.x, self...
class Solution: @staticmethod def reverse(number): one = int(number / 100) two = int(number % 100 / 10) three = int(number % 10) print(f"one {one} two {two} three {three}") return 100 * three + 10 * two + one if __name__ == '__main__': result = Solution...
import tkinter as tk import tkinter.font as tkfont from tkinter import * root=tk.Tk() root.title('Caeser cipher') root.geometry("800x500") root.resizable(width= FALSE, height=FALSE) canvas = tk.Canvas(root,height = 800, width=800, bg="blue") canvas.pack() bold_font = tkfont.Font(family="Helvetica",size=20,weight="bold"...
#Part 1 def numValidPasswordsCount(passwords): numValid = 0 for policy in passwords: minmax = policy[0].split("-") minimum, maximum = int(minmax[0]), int(minmax[1]) character = policy[1] password = policy[2] if(password.count(character) >= minimum and password.count(cha...
# I would like to replace "dishwasher" with "galaxy" in this example # Please fix it for me! # Expected ouput: In a galaxy far far away e = 'In a dishwasher far far away' e = e.replace('dishwasher', 'galaxy') print(e)
# create a function that takes a number, # divides ten with it, # and prints the result. # it should print "fail" if the parameter is 0 def divide(number): if number > 0: print(10/number) else: print('fail') divide(9)
''' Reuse your Sharpie class Create SharpieSet class it contains a list of Sharpie count_usable() -> sharpie is usable if it has ink in it remove_trash() -> removes all unusable sharpies ''' class Sharpie(): def __init__(self, color, width, ink_amount): self.color = color self.width = float(width)...
# Adds a and b, returns as result def add(a, b): return a + b # Returns the highest value from the three given params def max_of_three(a, b, c): maximum = 0 for i in (a, b, c): while i > maximum: maximum = i return maximum # Returns the median value of a list given as param def med...
print("Add 2 numbers here: ") a = int(input()) z = int(input()) if a < z: print(z) elif a > z: print(a) else: print("Your numbers are equal.")