Function Returns Wrong Answer

This is the place for queries that don't fit in any of the other categories.

Function Returns Wrong Answer

Postby webmanoffesto » Sat Apr 20, 2013 3:20 pm

Function to Calculate Factorial Arrives at Correct Answer but 'returns' the wrong answer
in the below code the
Code: Select all
print "inside the function", calculate_here

shows me that the code does arrive at the correct answer
but then the final answer given (by 'return') is wrong
the problem seems to be the way "return calculate_here" works

Please help me to fix this problem

Code: Select all
print "Factorial attempt #2"
def factorial(given_number):
    calculate_here = given_number
    while given_number > 0:
        print "inside the function", calculate_here
        calculate_here = calculate_here * (given_number - 1) # = 4 * 3;
        given_number = given_number - 1 # = 3
    return calculate_here
   
print "Factorial: 4! = 24. My answer = ",
print factorial(4)
#>>> 24 NOT 14
print  "Factorial: 5! = 120. My answer = ",  factorial(5)
#>>> 120 NOT 24
print  "Factorial: 6! = 720. My answer = ", factorial(6)
#>>> 720 NOT 35
print ""

print "Factorial attempt #3"
def factorial(given_number):
    index = 1
    # calculate_here = given_number
    while index <= given_number:
        print "inside the function", calculate_here
        calculate_here = index * (index + 1) # = 4 * 3;
        index = index + 1 # = 3
    return calculate_here
   
print "Factorial: 4! = 24. My answer = ",
print factorial(4)
#>>> 24 NOT 14
print  "Factorial: 5! = 120. My answer = ",  factorial(5)
#>>> 120 NOT 24
print  "Factorial: 6! = 720. My answer = ", factorial(6)
#>>> 720 NOT 35
webmanoffesto
 
Posts: 5
Joined: Sat Apr 20, 2013 11:28 am

Re: Function Returns Wrong Answer

Postby Yoriz » Sat Apr 20, 2013 3:44 pm

The print of calculate_here is in your while loop right before it gets altered by the following line
Code: Select all
calculate_here = calculate_here * (given_number - 1) # = 4 * 3

so the value that gets returned will not be the same one as is printed.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Function Returns Wrong Answer

Postby rrashkin » Sat Apr 20, 2013 3:49 pm

The problem is the loop calculates one more time than you want it to. If you change

calculate_here = calculate_here * (given_number - 1) # = 4 * 3;

to

if given_number>0: calculate_here = calculate_here * (given_number - 1) # = 4 * 3;

you'll see that it is ok.
___________________
Bob Rashkin
User avatar
rrashkin
 
Posts: 32
Joined: Tue Feb 12, 2013 4:47 pm


Return to General Coding Help

Who is online

Users browsing this forum: mckryall and 3 guests