0

Consider the following piece of code:

def integ(fncts, propagate, stpSz):
    conditions = propagate.copy()
    iterator = 0
    for i in fncts:
        conditions[iterator] = conditions[iterator] + stpSz *  i(0)
        iterator+=1

    return conditions

Where fncts is an array of functions, like this:

 f1 = lambda x: x
 f2 = lambda x: 2*x
 fncts = (f1, f2)

Problem is, the code above works for length(fncts)>1. However, if there is only one function, it fails. How I can make sure the code can be executed if the user inputs only one function?

2
  • How does it fail? What error do you get? Commented Mar 14, 2012 at 14:22
  • Please expand upon "it fails". Is there a traceback? If so, please add it to your question. I suspect that you are calling inteq like this integ((f1), propagate, stpSz) instead of like this integ((f1,), propagate, stpSz). Note the comma after f1. That makes it a tuple rather than just parenthesis. Commented Mar 14, 2012 at 14:24

2 Answers 2

5

I'm assuming you mean the user inputs fncts = f? You can either require the user to always a sequence, so fncts = [f] or fncts = (f,), or check whether callable(fncts); tuples and lists are not callable.

Sign up to request clarification or add additional context in comments.

2 Comments

Turns out I could just solve it using if len(fncts) > 1:, but thanks for answering so I'll give you the credit!
@thomas: If checking the length of fncts works, then this answer is incorrect. All the answers here assume that you were passing a function instead of a tuple to integ. However, taking length of a function gives a TypeError (e.g. len(lambda:1), so the assumption was incorrect. Next time please ask your question more precisely and respond to requests for clarification. If something "fails" please explain the expected behavior or post a traceback. You will get better answers that way.
1

Either throw an error if the first argument is not a list (at least a length 1 list) or check to see if fncts is a single function, then wrap it in a list before operating on it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.