How do I avoid repeating commands through a function?

1

I'm creating a program to do some mathematical accounts with some commands and have 1 line of code that repeats in all conditions, with only a small change in each condition. My question is how to create a function to call it instead of typing this line every time (I know it's not worth creating a function just to not repeat a line when sometimes I would even write more, but I think I'll need to learn to replace large chunks of code with functions). Here is my code and lastly the function I tried to create for it.

from script_calc import *


command = input()

if '!' in command:
    a = int(command.strip('!')) # esse comando que eu gostaria de substituir todas as vezes que ele é repetido mudando só o caractere que está dentro do strip.
    print(fact(a))

elif 'root' in command:
    a = int(command.strip('root'))
    print(root(a))

elif '²' in command:
    a = int(command.strip('²'))
    print(square(a))

elif '³' in command:
    a = int(command.strip('³'))
    print(cube(a))

The functions that were called:

from math import factorial


def fact(a):
    return factorial(a)


def root(a):
    return a ** (1/2)


def square(a):
    return a ** 2


def cube(a):
    return a ** 3

I tried to create this function to not repeat the command I said and gave error:

def same(x):
    a = int(command.strip({}).format(x))

And then run it like this:

elif 'root' in command:
        x = 'root'
        same(x) 
        print(root(a))

What is the error in this function?

    
asked by anonymous 28.03.2018 / 20:48

1 answer

1

A good way to avoid repeating these commands in the if else structure you have is by using a dictionary with its text to be found in the command and function to use:

commands = [
    {'match':'root', 'func': root },
    {'match':'!',    'func': fact },
    {'match':'²',    'func': square },
    {'match':'³',    'func': cube },
]

For consistency with the code I have already used English names

Then just use a for to iterate over each of the commands and if any match the match run it and show the value:

input_command = input()

for command in commands:
    if command["match"] in input_command:
        val = int(input_command.strip(command["match"]))
        print(command["func"](val))
        break 

See this example working on Ideone

In this last loop / loop command["match"] refers to the text to be found in the command and command["func"] the function to be executed. We can also write it in more detail:

input_command = input()

for command in commands:
    # o texto a ser procurado no comando
    match = command["match"] 

    if match in input_command:
        # valor obtido do comando
        val = int(input_command.strip(match)) 

        # obter a função armazenada no comando
        command_func = command["func"] 

        # executa-la passando o valor
        result = command_func(val)

        print(result)
        break 

With this solution adding a command boils down to adding a new object in the list of commands, leaving for unchanged.

    
28.03.2018 / 21:15