0% found this document useful (0 votes)
10 views

100 Adv Coding Exercises

coding

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

100 Adv Coding Exercises

coding

Uploaded by

Arya Bhatt
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

100 adv coding exercises

========================

Exercise 0

Print the Python version to the console.

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.

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:

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:

the first element of the sequence is 0

the second element of the sequence is 1

each next element of the sequence is the sum of the previous two elements

The beginning of the Fibonacci sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...

Find the sum of all even elements of the Fibonacci sequence with values less than
1,000,000 (1 million).

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:

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

In number theory, integer factorization is the decomposition of a composite number


into a product of smaller integers. If these factors are further restricted to
prime numbers, the process is called prime factorization.

Examples of prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, ...

Reminder: The number 1 is not a prime number.

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

In number theory, integer factorization is the decomposition of a composite number


into a product of smaller integers. If these factors are further restricted to
prime numbers, the process is called prime factorization.

Examples of prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, ...

Reminder: The number 1 is not a prime number.

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

The largest prime factor for 15 is 5, and for 36 is 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

Consider the palindromic numbers. A palindromic or symmetric number is a number


that does not change when you write its digits in reverse order.

Some examples of palindromic numbers:

363

2882

29492

Implement a function that returns the number of all three-digit palindromic


numbers.

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:
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

Consider the palindromic numbers. A palindromic or symmetric number is a number


that does not change when you write its digits in reverse order.

Some examples of palindromic numbers:

363

2882

29492

Implement a function that returns the largest palindromic number resulting from the
product of two-digit numbers.

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:

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.

Implement a function called greatest_common_divisor() that determines the greatest


common divisor of two numbers.

Example:

[IN]: greatest_common_divisor(32, 48)


[OUT]: 16

You just need to implement the function. The tests run several test cases to
validate the solution.

def greatest_common_divisor(a, b):


while b:
a, b = b, a % b
return a
====
Exercise 8

A prime number is a natural number greater than 1 that is not a product of two
smaller natural numbers.

Examples of prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, ...

Implement a function called is_prime() that takes a natural number as an argument


and checks if it is a prime number. In the case of a prime number, the function
returns True, otherwise False.

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

Solution II (less efficient):

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.

Examples of prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, ...

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

Consider the palindromic numbers. A palindromic or symmetric number is a number


that does not change when you write its digits in reverse order.

Some examples of palindromic numbers:

363

2882

29492

Implement a function called is_palindrome() that checks if the passed number is


palindromic decimal and binary.

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

Consider the palindromic numbers. A palindromic or symmetric number is a number


that does not change when you write its digits in reverse order.

Some examples of palindromic numbers:

363

2882

29492

A function called is_palindrome() is implemented that checks if the number is


palindromic in decimal and binary notation.

Implement a function called calculate() that returns all three-digit palindromic


numbers in both decimal and binary notation. In response, call calculate() function
and print the result to the console.

Expected result:

[313, 585, 717]

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

Consider a simple number compression algorithm that works as follows:

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.

Implement a function called compress() that compresses number as described above.


Examples:

[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.

from itertools import groupby

def compress(number):
result = []
for key, group in groupby(str(number)):
result.append((key, len(list(group))))
return result

==============
Exercise 13

Consider a simple number compression algorithm that works as follows:

111155522500 -> '14_53_22_51_02'

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.

Implement a function called compress() that compresses number as described above.

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:

from itertools import groupby

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:

from itertools import groupby

def compress(number):
result = [''.join((key, str(len(list(group))))) for key, group in
groupby(str(number))]
return '_'.join(result)

=======
Exercise 14

Consider a simple number compression algorithm that works as follows:

111155522500 -> '1....5...2..5.0..'

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.

Implement a function called compress() that compresses number as described above.

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:

from itertools import groupby

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)

Solution II (list comprehension):

from itertools import groupby

def compress(number):
result = [''.join((key, '.' * len(list(group)))) for key, group in
groupby(str(number))]
return ''.join(result)
===========
Exercise 15

Consider a simple number compression algorithm that works as follows:

111155522500 -> '14_53_22_51_02'

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.

A function called compress() is implemented that compresses a number as described


above:
from itertools import groupby

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)

Implement a function called decompress() that decompresses the expression to a


number.

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.

from itertools import groupby

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:

[[4, 2, 7], [1, 5, 4], [2, 6, 8]]

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:

[IN]: m = Matrix('3 4\n5 6')


[IN]: m.matrix
[OUT]: [[3, 4], [5, 6]]

[IN]: m = Matrix('3 4\n5 6\n7 8')


[IN]: m.matrix
[OUT]: [[3, 4], [5, 6], [7, 8]]

You just need to implement the class. The tests run several test cases to validate
the solution.

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]
=====
Exercise 17

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:

[[4, 2, 7], [1, 5, 4], [2, 6, 8]]


Part of a class named Matrix is implemented:

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]

Add an implementation of the __repr__() method to the Matrix class that is a formal
representation of a Matrix object.

Example:

[IN]: m1 = Matrix('4 5\n8 6')


[IN]: m1.__repr__()

'4 5\n8 6'

Example:

[IN]: m1 = Matrix('4 5\n8 6')


[IN]: print(m1.__repr__())

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 __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]

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:

[[4, 2, 7], [1, 5, 4], [2, 6, 8]]

Part of a class named Matrix is implemented:

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]

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:

[IN]: m = Matrix('3 4\n5 6\n7 8')


[IN]: m.row(0)
[OUT]: [3, 4]

Example:

[IN]: m = Matrix('3 4\n5 6\n7 8')


[IN]: m.row(2)
[OUT]: [7, 8]
You only need to implement the row() method. The tests run several test cases to
validate the solution.

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]

def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)

def row(self, index):


return self.matrix[index]

=======
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:

[[4, 2, 7], [1, 5, 4], [2, 6, 8]]

Part of a class named Matrix is implemented:

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]
def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)

def row(self, index):


return self.matrix[index]

Dodaj do klasy Matrix implementację metody column(), która za argument przyjmie


indeks i zwróci odpowiadającą indeksowi kolumnę macierzy.

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.

An example of calling the Matrix.column() method:

[IN]: m = Matrix('3 4\n5 6')


[IN]: m.column(0)
[OUT]: [3, 5]

An example of calling the Matrix.column() method:

[IN]: m = Matrix('3 4\n5 6\n7 8')


[IN]: m.column(1)
[OUT]: [4, 6, 8]

You only need to implement the column() method. The tests run several test cases to
validate the solution.

class Matrix:
"""Simple Matrix class."""

def __init__(self, string):


self.matrix = [
[int(i) for i in row.split()]
for row in string.splitlines()
]

def __repr__(self):
return '\n'.join(
[
(' '.join([str(i) for i in row]))
for row in self.matrix
]
)

def row(self, index):


return self.matrix[index]
def column(self, index):
return [row[index] 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]

we will present as a sequence:

'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: The Hamming distance of the vectors '1100100', '1010000' is equal to 3.

Implement a function called hamming_distance() that returns the Hamming distance of


two vectors. To calculate the Hamming distance, the vectors must be of the same
length. If the vectors are of different lengths raise the ValueError with the
following message:

'Both vectors must be the same length.'

Example:

[IN]: hamming_distance('01101010', '11011011')


[OUT]: 4

Example:

[IN]: hamming_distance('110', '10100')


[OUT]: ValueError: Both vectors must be the same length.

You just need to implement the hamming_distance() function. The tests run several
test cases to validate the solution.

def hamming_distance(u, v):


if len(u) != len(v):
raise ValueError('Both vectors must be the same length.')
distance = 0
for i in range(len(u)):
if u[i] != v[i]:
distance += 1
return distance

You might also like