Profile image of CloudNinja
Submitted by CloudNinja
over 12 years

1.5 Recursive Factorial - just one line of code and a single variable: can you do better ;)?

Well, one line except the definition:

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

For the use of the ternary operator in python, also see this.

Putting it all on the same line gives me an error, yet the exercise passes.

I was wondering if CPU-wise is better to use recursive function or instead to use some support variable and a loop: any idea?

Edit: a pro friend of mine told me just now that in Python a recursive statement tends to be heavier as in this case the calls would remain in the stack. Quite a burden for larger numbers.

Answer 514a033fb509068a73000712

3 votes

Permalink

very interesting. Like it

Profile image of Srav
Submitted by Srav
over 12 years

2 comments

Profile image of CloudNinja
Submitted by CloudNinja
over 12 years

Thanks for your kind feed :)

Profile image of cadweazle
Submitted by cadweazle
over 12 years

recursion often is easier to understand and code, the more elegant way, if you will, but in most cases is dangerous if the function calles itself to often due to the possibility of stack overflow…

Answer 514b2a61c9fe0c721d000101

2 votes

Permalink

Again Giacomo, not as elegant as you. Just happy I figured it out without using the hint or anything. Im only on day 8 of any programming at all so im just happy to get it lol.

def factorial(x):
    for i in reversed(range(x)):
        if i == 0:
            return x
        else:
            x *= int(i)
Profile image of cssCoder96392
Submitted by cssCoder96392
over 12 years

Answer 514cbac08f904a789d00033b

1 vote

Permalink

def factorial(num):return reduce(lambda x,y:x*y,[1]+range(1,num+1))

Although this is not the best..but simple oneliner… Version-2

fac = lambda num:[1,0][num>0] or fac(num-1)*num
Profile image of cybercam
Submitted by cybercam
over 12 years

Popular free courses

  • In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
    • Beginner Friendly.
      4 Lessons
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      11 Lessons
  • Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.
    • Beginner Friendly.
      6 Lessons
Explore full catalog