Source Link:
https://codility.com/programmers/lessons/1-iterations/
Some Notes:
In programming, iterating means repeating some part of your program.
1.1. For loops
Example 1:
The factorial of n is n! = 1 · 2 · . . . · n.
Code:
1 factorial = 1
2 for i in range (1, n + 1):
3 factorial *= i
Example 2:
Let’s print a triangle made of asterisks (‘*’) separated by spaces. The triangle should consist of n rows, where n is a given positive integer, and consecutive rows should contain 1, 2, . . . , n asterisks. For example, for n = 4 the triangle should appear as follows:
*
* *
* * *
* * * *
Code:
1 for i in range(1, n + 1):
2 for j in range(i):
3 print ’*’,
4 print
We need to use two loops. (the second loop j <= i)
Example 3:
Let’s print a triangle made of asterisks (‘*’) separated by spaces and consisting of n rows again, but this time upside down, and make it symmetrical. Consecutive rows should contain 2n − 1, 2n − 3, . . . , 3, 1 asterisks and should be indented by 0, 2, 4, . . . , 2(n − 1) spaces. For example, for n = 4 the triangle should appear as follows:
* * * * * * *
* * * * *
* * *
*
Code:
1 for i in range(n, 0, -1):
2 for j in range(n - i):
3 print ’ ’,
4 for j in range(2 * i - 1):
5 print ’*’,
6 print
1.2. While loops
Example 4:
Given a positive integer n, how can we count the number of digits in its decimal representation? One way to do it is convert the integer into a string and count the characters. Here, though, we will use only arithmetical operations instead. We can simply keep dividing the number by ten and count how many steps are needed to obtain 0.
Code:
1 result = 0
2 while n > 0:
3 n = n // 10
4 result += 1
The above skill is important.
Example 5:
The Fibonacci numbers4 form a sequence of integers defined recursively in the following way. The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. The first few elements in this sequence are: 0, 1, 1, 2, 3, 5, 8, 13. Let’s write a program that prints all the Fibonacci numbers, not exceeding a given integer n.
Code:
1 a = 0
2 b = 1
3 while a <= n:
4 print a
5 c = a + b
6 a = b
7 b = c
Subscribe to:
Post Comments (Atom)
Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments
Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
No comments:
Post a Comment