Skip to content

Instantly share code, notes, and snippets.

@duoduo3369
Created August 4, 2012 12:30
Show Gist options
  • Save duoduo3369/3257215 to your computer and use it in GitHub Desktop.
Save duoduo3369/3257215 to your computer and use it in GitHub Desktop.
lambda python
"""
Factorial
Topic 11: Question 1
A function that calls itself is said to be recursive. The creation of recursive functions is a powerful technique to solve problem that can be broken down into smaller or simpler form. One common use is to find the factorial of a number. The factorial of a number N is simply the number multiplied by the factorial of (N-1). Complete the code given below to calculate and returns the factorial of a numeber.
Examples
>>> factorial(5)
120
>>> factorial(1)
1
>>> factorial(0)
1
"""
factorial = lambda x: x and x * factorial(x - 1) or 1
"""
Power
Topic 11: Question 2
Write a recursive function power(x, y) to calculate the value of x raised to the power of y.
Examples
>>> power(5, 2)
25
>>> power(5, 1)
5
>>> power(5, 0)
1
"""
power = lambda x,y: y and x * power(x,y - 1) or 1
"""
Fibonacci Numbers
Topic 11: Question 3
The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by the following definition:
Write a function fibonacci(number) that takes in a number as argument. The function should calculate and return the fibonacci number for the number passed in.
Examples
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(3)
2
>>> fibonacci(4)
3
>>> fibonacci(5)
5
>>> fibonacci(6)
8
>>> fibonacci(7)
13
"""
fibonacci = lambda x : 1 if x <= 2 else fibonacci(x-1) + fibonacci(x-2)
"""
Greatest Common Divisor
Topic 11: Question 4
The greatest common divisor (gcd) of 2 or more non-zero integers, is the largest positive integer that divides the numbers without a remainder. Write a function to compute the gcd of 2 integers using Euclid's algorithm:
Examples
>>> gcd(84, 18)
6
>>> gcd(112, 42)
14
>>> gcd(5, 4)
1
"""
gcd = lambda a,b: a if b ==0 else not a % b and b or gcd(b , a % b)
@maheshgawali
Copy link

maheshgawali commented May 8, 2018

This is a good collection of lambdas and recursion, thanks for sharing
Please update the one for fibonacci, it gives '1' for fibonacci(0), here is the updated one
fibonacci = lambda x : 0 if x==0 else 1 if 0 < x <= 2 else fibonacci(x-1) + fibonacci(x-2)

@rsha256
Copy link

rsha256 commented Aug 29, 2021

or merely:
fibonacci = lambda x: x if x < 2 else fibonacci(x-1) + fibonacci(x-2)
suffices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment