Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

python - How to print statement after return in function?

Here is the code as I currently have it:

def F(n):
    t=time.time()
    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    t1==time.time()
    return t
    F_time==t1-t
    print ('It took',F_time,'seconds to sort',n,'values using recursion')

I'm trying to print n numbers of the Fibonacci sequence and take the time before and after, but because of the return statements, it won't accept the variable after the return, nor the following print statement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Anything after a return statement will never be executed. A return statement instantly terminates the function and "returns" to the caller. So it's really not possible.

There are two ways to get (nearly) the same result though.

Method #1:

The time it takes to execute a return statement is almost negligable. Therefore you can move the necessary benchmark code above the return and get an almost identical result as if it actually executed after a 'return' statement.

def F(n):
    t=time.time()
    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    t1==time.time()
    F_time==t1-t
    print ('It took',F_time,'seconds to sort',n,'values using recursion')
    return t

Method #2:

Put your timing code outside the function, this is the preferred method.

def F(n):

    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    return t

t=time.time()
F(5)
t1==time.time()
F_time==t1-t
print ('It took',F_time,'seconds to sort',5,'values using recursion')

Hope this helped, good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...