Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
How to write a function which has 2 nested functions inside and let computes sum / difference for any number of given items?

I have to write a function which has 2 nested functions inside and computes only sum or difference of as many numbers as we want. Every equation end with "=". I wrote sth like this but it still doesn't work. What I am doing wrong?

def calculator(x: int):
    
    def operation(operator: str):

        def calculation(y: int):
            while operator != "=":
                if operators[i] == "=":
                    result -= digits[j]
                elif operators[i] == "+":
                    result += digits[j]
                else:
                    break
            return result
        return operator
    return calculator(result) 

Function should work like that:

calculator(1)('+')(4)('-')(2)('=') 

The result is 3. I can't use any package import or global variables.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can also use a dictionary to define your operations, and make a very readable and simple function with space for expansion:

def calc(a: int): return lambda op: {
    '+': lambda b: calc(a+b),
    '-': lambda b: calc(a-b),
    '/': lambda b: calc(a/b),
    '*': lambda b: calc(a*b),
}.get(op, a)

print(calc(2)('+')(3)('-')(10)('/')(10)('*')(-100)('='))
over 4 years ago · Santiago Trujillo Relatório

0

Deducing from the form of the input, you need to return "functions" each time. One way of doing that is to use lambda:

def calculator(x: int):
    def operation(op: str, x: int):
        if op == '=':
            return x
        else:
            return lambda _: calculation(_, op, x)

    def calculation(y: int, op: str, x: int):
        if op == '+':
            return lambda _: operation(_, x + y)
        else:
            return lambda _: operation(_, x - y) # mind the order of x & y

    return lambda _: operation(_, x)

print(calculator(1)('+')(4)('-')(2)('=')) # 3
print(calculator(3)('-')(10)('+')(6)('=')) # -1

For example, consider calculator(1)('+')(4)('-')(2)('='). The first part calculator(1)('+') means that calculator(1) itself is a function, which is then to be applied with an argument ('+'). So calculator(x) need to return a function operation.

Also you might want to record the result (1 in this case), by passing it to operation; that's why I added a parameter x (meaning the current result) to operation. Then I used lambda x: operation(_, x) to return a "partial function".

By the same reasoning, operation returns calculation, which in turns returns operation and so on, until operation is given with '='.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda