5/15 confusion


#1

Hello, I used the following code for 5:

def factorial(x):
  if x==0:
    return 1
  else:
    a=1
    z=1
    while a<=x:
      z *= a
      a+=1
    return z

and this is showing not valid without an error sign. I put the same code (except for changing return to print and and getting input prompt) in repl.it as below:

def factorial(x):
  if x==0:
    print 1
  else:
    a=1
    z=1
    while a<=x:
      z *= a
      a+=1
    print z
factorial(int(raw_input()))

and it seems to give the correct answers for all positive integers. Thank you in advance.


#2

And what is the question?

your code is correct, i reset the exercise, put your code in, it ran fine

If you want to see the output in the lesson you also need to add a function call, and a print statement before the function call to print the returned result


#3

@netblaster01154,

you can use a recursive call to simplify the solution. Like this:

def factorial(x):
if x < 2:
return 1
else:
return x * factorial(x-1)


#4

why? recursion is O(N2), and its not a simple thing to understand


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.