100 Adv Coding Exercises
100 Adv Coding Exercises
========================
Exercise 0
Expected result:
3.8.10
import sys
print(sys.version.split()[0])
======
Exercise 1
All natural numbers divisible by 5 or 7 less than 20 are: [0, 5, 7, 10, 14, 15].
The sum of these numbers is: 51. In this exercise, we treat zero as a natural
number.
Find the sum of all numbers that are divisible by 5 or 7 less than 100.
Expected result:
1580
Solution I:
def calculate():
numbers = []
for i in range(100):
if i % 5 == 0 or i % 7 == 0:
numbers.append(i)
total = sum(numbers)
return total
print(calculate())
Solution II:
def calculate():
return sum([i for i in range(100) if i % 5 == 0 or i % 7 == 0])
print(calculate())
========================
Exercise 2
Consider the Fibonacci sequence. It is a sequence of natural numbers defined
recursively as follows:
each next element of the sequence is the sum of the previous two elements
Find the sum of all even elements of the Fibonacci sequence with values less than
1,000,000 (1 million).
Expected result:
1089154
def calculate():
total = 0
a = 0
b = 1
while a < 1000000:
if a % 2 == 0:
total += a
a, b = b, a + b
return total
print(calculate())
=======
Exercise 3
A number that is greater than 1 and is not a prime is called a composite number.
Examples of composite numbers: 4, 6, 8, 9, 10, 12, 14, 15, 16, ...
We can break down a composite number into prime factors. For example:
15 = 3 * 5
36 = 2 * 2 * 3 * 3
48 = 2 * 2 * 2 * 2 * 3
Implement a function that takes a natural number as an argument and returns a list
containing the prime factorization of that number. Present the solution in the form
of a function called calculate().
Example:
[IN]: calculate(48)
[OUT]: [2, 2, 2, 2, 3]
You just need to implement the function. The tests run several test cases to
validate the solution.
def calculate(number):
i = 2
factors = []
while i * i <= number:
if not number % i == 0:
i += 1
else:
number = number // i
factors.append(i)
if number > 1:
factors.append(number)
return factors
=========
Exercise 4
A number that is greater than 1 and is not a prime is called a composite number.
We can break down a composite number into prime factors. For example:
15 = 3 * 5
36 = 2 * 2 * 3 * 3
Using the previous exercise, implement a function that takes a natural number as an
argument and returns the greatest prime factor of that number. Present the solution
in the form of a function called calculate().
Example:
[IN]: calculate(13195)
[OUT]: 29
You just need to implement the function. The tests run several test cases to
validate the solution.
def calculate(number):
i = 2
factors = []
while i * i <= number:
if not number % i == 0:
i += 1
else:
number = number // i
factors.append(i)
if number > 1:
factors.append(number)
return max(factors)
======
Exercise 5
363
2882
29492
Expected result:
90
def calculate():
numbers = []
for i in range(100, 1000):
if str(i) == str(i)[::-1]:
numbers.append(i)
return len(numbers)
print(calculate())
======
Exercise 6
363
2882
29492
Implement a function that returns the largest palindromic number resulting from the
product of two-digit numbers.
Expected result:
9009
Solution I:
def calculate():
numbers = []
for i in range(10, 100):
for j in range(10, 100):
if str(i * j) == str(i * j)[::-1]:
numbers.append(i * j)
return max(numbers)
print(calculate())
Solution II:
def calculate():
result = max([i * j
for i in range(10, 100)
for j in range(10, 100)
if str(i * j) == str(i * j)[::-1]])
return result
print(calculate())
=====================
Exercise 7
Greatest Common Divisor (GCD) of two integers - this is the largest natural number
that divides both of these numbers without a remainder.
For example, for numbers 32 and 48, the greatest common divisor is 16, which we can
write GCD(32, 48) = 16.
Example:
You just need to implement the function. The tests run several test cases to
validate the solution.
A prime number is a natural number greater than 1 that is not a product of two
smaller natural numbers.
Example:
[IN]: is_prime(11)
[OUT]: True
You just need to implement the function. The tests run several test cases to
validate the solution.
Solution 8
Solution I:
def is_prime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
def is_prime(n):
if n < 2:
return False
elif n == 2:
return True
for i in range(2, n):
if n % i == 0:
return False
return True
==========
Exercises 9
A prime number is a natural number greater than 1 that is not a product of two
smaller natural numbers.
The prime number in position one is 2. The prime number in position two is 3. The
prime number in position three is 5. Implement a function that returns a prime
number at position 100.
In the solution, use the function is_prime() from the previous exercise:
def is_prime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
Present the solution in the form of a function called calculate(). In response,
call calculate() function and print the result to the console.
Expected result:
541
def is_prime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
==========
==========
ex 10
Exercise 10
363
2882
29492
For example, the number 99 is a palindromic number and its binary notation 1100011
is also a palindrome. When these conditions are met, the function returns True,
otherwise False.
Example:
[IN]: is_palindrome(99)
[OUT]: True
You just need to implement the function. The tests run several test cases to
validate the solution.
solution
-------
def is_palindrome(number):
if str(number) != str(number)[::-1]:
return False
bin_number = bin(number)[2:]
return bin_number == bin_number[::-1]
==============
Exercise 11
363
2882
29492
Expected result:
def is_palindrome(number):
if str(number) != str(number)[::-1]:
return False
bin_number = bin(number)[2:]
return bin_number == bin_number[::-1]
def calculate():
return [i for i in range(100, 1000) if is_palindrome(i)]
====
Exercise 12
111155522500 -> [('1', 4), ('5', 3), ('2', 2), ('5', 1), ('0', 2)]
The algorithm goes from left to right through each digit and returns a list of two-
element tuples. Each tuple consists of a digit and the number of repetitions of a
given digit until the next, different digit in the number is encountered.
[IN]: compress(111)
[OUT]: [('1', 3)]
[IN]: compress(1000000)
[OUT]: [('1', 1), ('0', 6)]
[IN]: compress(10005000)
[OUT]: [('1', 1), ('0', 3), ('5', 1), ('0', 3)]
Tip: You can use the itertools built-in module and the groupby class in your
solution.
You just need to implement the function. The tests run several test cases to
validate the solution.
def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, len(list(group))))
return result
==============
Exercise 13
The algorithm goes from left to right through the number and returns an object of
type str. Each encountered digit is stored along with the number of times that
digit repeats until another digit is encountered in the number. Each such pair is
separated by the '_' character.
Examples:
[IN]: compress(100000)
[OUT]: '11_05'
[IN]: compress(9993330)
[OUT]: '93_33_01'
[IN]: compress(6540000)
[OUT]: '61_51_41_04'
Tip: You can use the itertools built-in module and the groupby class in your
solution.
You just need to implement the function. The tests run several test cases to
validate the solution.
Solution I:
def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, str(len(list(group)))))
result = [''.join(item) for item in result]
return '_'.join(result)
Solution II:
def compress(number):
result = [''.join((key, str(len(list(group))))) for key, group in
groupby(str(number))]
return '_'.join(result)
=======
Exercise 14
The algorithm goes from left to right through the number and returns an object of
str type. Each encountered digit is stored along with the number of dots - the
number of times the given digit repeats until it encounters the next, different
digit in the number.
Examples:
[IN]: compress(1000040000)
[OUT]: '1.0....4.0....'
[IN]: compress(20000000)
[OUT]: '2.0.......'
[IN]: compress(123456)
[OUT]: '1.2.3.4.5.6.'
Tip: You can use the itertools built-in module and the groupby class in your
solution.
You just need to implement the function. The tests run several test cases to
validate the solution.
Solution I:
def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, len(list(group))))
result = [''.join((i, '.' * j)) for i, j in result]
return ''.join(result)
def compress(number):
result = [''.join((key, '.' * len(list(group)))) for key, group in
groupby(str(number))]
return ''.join(result)
===========
Exercise 15
The algorithm goes from left to right through the number and returns an object of
str type. Each encountered digit is stored along with the number of times that
digit repeats until another digit is encountered in the number. Each such pair is
separated by the '_' character.
def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, str(len(list(group)))))
result = [''.join(item) for item in result]
return '_'.join(result)
Examples:
[IN]: decompress('14_53_22_51_02')
[OUT]: 111155522500
[IN]: decompress('11_03_51_03')
[OUT]: 10005000
You just need to implement the function. The tests run several test cases to
validate the solution.
def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, str(len(list(group)))))
result = [''.join(item) for item in result]
return '_'.join(result)
def decompress(compressed):
result = [(item[0], item[1:]) for item in compressed.split('_')]
result = [i * int(j) for i, j in result]
return int(''.join(result))
======
Exercise 16
Consider the problem below. We have an application in which at some point we get a
matrix in the form of a string (an object of the str type). For example, the
following string:
string = """4 2 7
1 5 4
2 6 8"""
represents a 3x3 matrix. Each row of the matrix is stored on a separate line. Each
element of a row is separated from another element by a space.
It's hard to work with these matrices and perform some additional operations. We
will transform such a matrix into nested lists:
Implement a class named Matrix that takes the matrix as a string in the __init__()
method and sets the value of the instance attribute called matrix as nested lists.
Examples:
You just need to implement the class. The tests run several test cases to validate
the solution.
class Matrix:
"""Simple Matrix class."""
Consider the problem below. We have an application in which at some point we get a
matrix in the form of a string (an object of the str type). For example, the
following string:
string = """4 2 7
1 5 4
2 6 8"""
represents a 3x3 matrix. Each row of the matrix is stored on a separate line. Each
element of a row is separated from another element by a space.
It's hard to work with these matrices and perform some additional operations. We
will transform such a matrix into nested lists:
class Matrix:
"""Simple Matrix class."""
Add an implementation of the __repr__() method to the Matrix class that is a formal
representation of a Matrix object.
Example:
Example:
4 5
8 6
You only need to implement the __repr__() method. The tests run several test cases
to validate the solution.
class Matrix:
"""Simple Matrix class."""
def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)
======
Exercise 18
Consider the problem below. We have an application in which at some point we get a
matrix in the form of a string (an object of the str type). For example, the
following string:
string = """4 2 7
1 5 4
2 6 8"""
represents a 3x3 matrix. Each row of the matrix is stored on a separate line. Each
element of a row is separated from another element by a space.
It's hard to work with these matrices and perform some additional operations. We
will transform such a matrix into nested lists:
class Matrix:
"""Simple Matrix class."""
def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)
Add an implementation of the row() method to the Matrix class that takes the index
as an argument and returns the corresponding row of the matrix.
Example:
Example:
class Matrix:
"""Simple Matrix class."""
def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)
=======
Exercise 19
Consider the problem below. We have an application in which at some point we get a
matrix in the form of a string (an object of the str type). For example, the
following string:
string = """4 2 7
1 5 4
2 6 8"""
represents a 3x3 matrix. Each row of the matrix is stored on a separate line. Each
element of a row is separated from another element by a space.
It's hard to work with these matrices and perform some additional operations. We
will transform such a matrix into nested lists:
class Matrix:
"""Simple Matrix class."""
Add an implementation of the column() method to the Matrix class that takes the
index as an argument and returns the corresponding column of the matrix.
You only need to implement the column() method. The tests run several test cases to
validate the solution.
class Matrix:
"""Simple Matrix class."""
def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)
=====
Exercise 20
Let's consider vectors consisting of only ones and zeros. Let us also assume an
additional convention for representing such a vector. For example, a vector:
u = [0, 1, 1, 0, 1, 0, 1, 0]
'01101010'
For the vectors so defined, we can determine the Hamming distance. The Hamming
distance of vectors u and v is the number of elements where the vectors u and v are
different.
Example:
Example:
You just need to implement the hamming_distance() function. The tests run several
test cases to validate the solution.