Lesson 8.Functions and recursion
Problem «The length of the segment»
Statement
Given four real numbers representing cartesian coordinates: (x1,y1),(x2,y2). Write a functiondistance(x1, y1, x2, y2)
to compute the distance between the points (x1,y1) and (x2,y2). 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»
Statement
Given a positive real number a and integer n.Compute an. 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»
Statement
Write a functioncapitalize(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»
Statement
Given a positive real number a and a non-negative integer n. Calculate an without using loops,**
operator or the built in function math.pow()
. Instead, use recursion and the relation an=a⋅an−1. Print the result. Form the function power(a, n)
.
Problem «Reverse the sequence»
Statement
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»
Statement
Given a non-negative integer n, print the nth Fibonacci number. Do this by writing a functionfib(n)
which takes the non-negative integer n and returns the nth 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.