0

I have a script from a python class designed to check answers against a server that seems a bit cumbersome and I am trying to see if there is a better pythonic way of doing this.

I have a ton of tiny functions that perform quick operations, they are numbered due to the potentially high number of questions to be answered in the class (example, not live code):

def function_1(data):
    return data + 1

def function_2(data):
    return data**100

def function_n(data):
    return ((data + 2) * 4) // 16

and in the main function, it essentially prints out the output of those functions

def main():
    input = "20"
    print("#1", exercise.answer(1, function_1(input)))
    print("#2", exercise.answer(2, function_2(input)))
    print("#n", exercise.answer(n, function_n(input)))

I have been trying to see if there is a way to print the functions sequentially using a loop, something like this:

i = 1
while i < n+1
    print("#" + str(i), function_i(input))

This way I only have to add a new function up top, and increase the number n in the while loop, while also reducing the number of prints in the code itself. Any pointed direction would be helpful.

  • *Generally speaking*, if you have things named "foo_1", "foo_2" etc., you're doing *something* wrong. Those functions might be doing something that could simply be parameterised, e.g. `function(data, 100)`. If not this, then they're badly named and need more descriptive names. You could then put them in a list and apply them one after the other, e.g. `fs = [foo, bar]; for f in fs: print(f(input))`. What exactly will be the best thing to do for your particular situation we can't really tell you given this toy example. – deceze Mar 23 '20 at 13:53
  • @deceze I can update the question with a better representation. The example code is actually really close to the real script. I just didn't put answers to questions and the specific syntax for their answer submission library, which is basically `exercise.answer(1, function_1(data))`, so not a lot to be gained with that. – Wabbadabba Mar 23 '20 at 14:01
  • Then you probably want something like https://stackoverflow.com/a/4246028/476. – deceze Mar 23 '20 at 14:08
  • @deceze That worked beautifully. thank you. – Wabbadabba Mar 23 '20 at 14:31

0 Answers0