Functions and recursion - Learn Python 3 - Snakify

Lesson 8.Functions and recursion

Problem «The length of the segment»


Given four real numbers representing cartesian coordinates: \( \left ( x_{1}, y_{1} \right ), \left ( x_{2}, y_{2} \right ) \). Write a function distance(x1, y1, x2, y2) to compute the distance between the points \( \left ( x_{1}, y_{1} \right ) \) and \( \left ( x_{2}, y_{2} \right ) \). Read four real numbers and print the resulting distance calculated by the function.

The formula for distance between two points can be found at Wolfram.

Problem «Negative exponent»


Given a positive real number \( a \) and integer \( n \).

Compute \( a^{n} \). Write a function power(a, n) to calculate the results using the function and print the result of the expression.

Don't use the same function from the standard library.

Problem «Uppercase»


Write a function capitalize(lower_case_word) that takes the lower case word and returns the word with the first letter capitalized. Eg., print(capitalize('word')) should print the word Word.

Then, given a line of lowercase ASCII words (text separated by a single space), print it with the first letter of each word capitalized using the your own function capitalize().

In Python there is a function ord(character), which returns character code in the ASCII chart, and the function chr(code), which returns the character itself from the ASCII code. For example, ord('a') == 97, chr(97) == 'a'.

Problem «Exponentiation»


Given a positive real number \( a \) and a non-negative integer \( n \). Calculate \( a^{n} \) without using loops, ** operator or the built in function math.pow(). Instead, use recursion and the relation \( a^{n} = a \cdot a^{n-1} \). Print the result.

Form the function power(a, n).

Problem «Reverse the sequence»


Given a sequence of integers that end with a \( 0 \). Print the sequence in reverse order.

Don't use lists or other data structures. Use the force of recursion instead.

Problem «Fibonacci numbers»


Given a non-negative integer \( n \), print the \( n \)th Fibonacci number. Do this by writing a function fib(n) which takes the non-negative integer \( n \) and returns the \( n \)th Fibonacci number.

Don't use loops, use the flair of recursion instead. However, you should think about why the recursive method is much slower than using loops.