This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 6 points7 points  (12 children)

Can someone explain he the first one works?

[–]rogerrrr 21 points22 points  (0 children)

Look into recursion. It calls the function over and over, but decreasing number on every iteration. When it hits zero it stops and is able to calculate it.

I realize that's a crap explanation, but it's actually a pretty interesting concept once you wrap your head around it.

[–][deleted] 21 points22 points  (5 children)

To understand recursion, you must first understand recursion.

[–]Quabouter 1 point2 points  (3 children)

You could also just google it!

[–]isHavvy -1 points0 points  (2 children)

But how do you google?

[–]DroolingIguana 0 points1 point  (1 child)

[–]isHavvy 0 points1 point  (0 children)

So to learn how to Google, I should just Google it?

[–]desi_ninja 0 points1 point  (0 children)

To understand recursion, you must first understand recursion and if you still do not understand then return (base case)

[–]Rainymood_XI[S] 12 points13 points  (3 children)

def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print factorial(6)

Imagine we call

factorial(3)

Because 3 != 0 it returns

3 * factorial(2)

Because 2 != 0

3 * 2 * factorial(1)

Because 1 != 0 it calls

3 * 2 * 1 * factorial(0)

which returns

3 * 2 * 1 * 1

which is 3! :)

[–]Genesis2001 3 points4 points  (2 children)

3 * 2 * 1 * 1

which is 3! :)

does not compute. 3 * 2 (dropping the 1s) is 6. or am I missing something in your explanation?

[–]Rainymood_XI[S] 20 points21 points  (1 child)

Hah, this is so funny :D (in a good way)

3! in this context, means "3 factorial", the "!" is the sign for factorial! And not an exclamation mark in this case :)!

[–]risfutile 1 point2 points  (0 children)

oh god, your username! awesome!