Factorial() frustration


#1

This is under "Practice Makes Perfect", Number 5. "factorial"

Ok so I wrote the code below, and the module said that I completed the challenge and that I could move on to the next one, but it just printed "None" to the screen. So I obviously didn't do something right. Can someone help explain: A) why it told me I was right; and B) what I can adjust to have the function actually work?

Thank you in advance!

Link to the lesson: link

def factorial(x):
    if x == 0:
        return 1
    elif x == 1:
        return 1
    else:
        while x > 0:
            return x * factorial(x-1)
            x = x-1
    return factorial(x)
    
factorial(7)

#2

There are several examples of a recursion for this problem, but the general idea is to use an algorithm approach using what has been taught. Recursion is not covered in this track.

Here is one example to consider...

>>> def factorial(n):
	return 1 if n in (0, 1) else n * factorial(n - 1)

>>> factorial(7)
5040
>>> factorial(0)
1
>>> factorial(1)
1
>>>

Now try to do this without recursion.


#3

Thanks for the response but I'm not sure I understand. I don't recall there being any lesson on algorithms or recursion.


#4

Recursion, no, but algorithms, yes, though perhaps not spelled out at such. We have covered conditionals and control flow, loops and iterables, and functions, which are the working parts of any algorithm. Think a sequence of steps followed. There may be conditions that apply, and there may be repetition, as applies.

for i in range(10):
    print i + 1

As elementary as it is, the above is an algorithm to print the numbers from 1 to 10. We can add a conditional so it prints only even numbers...

for i in range(10):
    if i % 2:
        print i + 1

Continued...

In describing n!, we coudl break it down to pseudo-algorithm on paper...

7! = 7 * 6!
6! = 6 * 5!
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1 * 0!

We don't know how many steps there will be in any one problem so we would write code like this, but an algorithm that works on each step, in order.

7! = 7 * 6 * 5 * 4 * 3 * 2 * 1

Likewise, we would not spell out the hard code arithmetic since it is not dynamic, or variable.

>>> n = x = 7
>>> while n > 1:
    n -= 1
    x *= n

    
>>> x
5040
>>>

Now you try. There are a lot of ways to do this with basic iteration.


#5

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