Created
August 4, 2012 12:30
-
-
Save duoduo3369/3257215 to your computer and use it in GitHub Desktop.
lambda python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or merely:
fibonacci = lambda x: x if x < 2 else fibonacci(x-1) + fibonacci(x-2)
suffices.