Python exercises
Introduction
Write words longer than four characters backwards
Write a function that takes a string — an ordinary sentence — and returns the same sentence, but with all words of five letters or more written backwards
Solution
Using list comprehension
def spin_words(sentence): ns = sentence.split(" ") return " ".join([word[::-1] if len(word) > 4 else word for word in ns])
Without list comprehension
def spin_words2(sentence): ns = sentence.split(" ") new_list = [] for word in ns: if len(word) > 4: new_list.append(word[::-1]) else: new_list.append(word) return " ".join(new_list)
Using a lambda function and the function map()
def spin_words3(sentence): ns = sentence.split(" ") return " ".join(map(lambda w: w[::-1] if (len(w) > 4) else w, ns))
Sum of odd numbers in a row
Calculate the sum of the odd numbers in a row of the triangle.
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
Example: the sum in the second row = 3 + 5 = 8.
Solution
At first one can solve the problem “head-on”
def row_sum_odd_numbers(n): solved = False i = 0 value = 1 s = 0 while not solved: i += 1 l = [] for j in range(i): l.append(value) value +=2 print(l) if i == n: for num in l: s += num print("sum is: ", s) return s solved = True if __name__ == "__main__": row_sum_odd_numbers(3)
If you look closely at the triangle, you can see that the sum of the numbers in a row is the row number cubed
def row_sum_odd_numbers(n): return n**3
The next perfect square
Calculate the next perfect square. The function receives a number; if it is a perfect square, the next one must be returned. If not, return -1
Example: 9 -> 16, 121 -> 144
Solution
import math def find_next_square(sq): root = math.sqrt(sq) if root.is_integer(): return (root + 1)**2 else: return -1
City population growth
The initial population, the natural annual growth in percent,
the growth due to people moving in, and the desired population are given.
Calculate how many years it will take for the population to reach the desired value.
Example: 1000, 0, 50, 1100 -> 2 years
Solution
The main thing is not to forget to round down when calculating percentages.
import math def nb_year(p0, percent, aug, p): n = 0 while p0 < p: n += 1 p0 = math.floor(p0 * (1 + percent/100)) + aug print("p0: ",p0) print(p) print(n) return n if __name__ == "__main__": # nb_year(100, 3, 20, 1500) nb_year(1000, 2, 50, 1214)
Article author: Andrei Olegovich