Wednesday, April 24, 2024

📑 Mutable and Immutable Types

📑 Task

1) What will the program print?
2) Is it possible to create a dictionary of objects of another type:
during manipulations with variables or copies
they will behave differently and will not repeat changes of each other?
What type of objects should they be?
x1 = [[]]
x2 = x1
x1 *= 2
d1 = {1: x1}
d2 = {1: x2}
print(x1, x2)
print(d1, d2)
x1[0].append(2)
print(x1, x2)
print(d1, d2)
d2[1] += [[3]]
print(x1, x2)
print(d1, d2)

📑 Answer

1) Changes to copies and originals will affect each other
[[], []] [[], []]
{1: [[], []]} {1: [[], []]}
[[2], [2]] [[2], [2]]
{1: [[2], [2]]} {1: [[2], [2]]}
[[2], [2], [3]] [[2], [2], [3]]
{1: [[2], [2], [3]]} {1: [[2], [2], [3]]}
2) The object type must be immutable, for example integers
x1 = 1
x2 = x1
x1 *= 2
d1 = {1: x1}
d2 = {1: x2}
print(x1, x2)
print(d1, d2)
x1 += 2
print(x1, x2)
print(d1, d2)
d2[1] += 3
print(x1, x2)
print(d1, d2)

📑 Exponentiation

📑 Task

1) Describe this function is short (only main characteristics)
2) Suggest recursive and cyclic counting methods that
can significantly speed up calculations

📑 Answer

1) The function base_power calculates the result
of raising a base number to a specified power using recursion.
It handles base cases where the base is 1 or the power is 0 by returning 1.
During recursion, it multiplies the base by the result
of the function called with the power decremented by 1.
The function efficiently computes exponentiation by recursively
multiplying the base values until it reaches the specified power.
2)

📑 Unpacking Nested Lists

📑 Task

1) What result will be printed?
2) Write a function that extracts all elements of lists and tuples into one list without nesting
Try it for this difficult case list_ = [[1, 2], (3, ), [[[(4, 5)]]], 6, 7]

📑 Answer

1) [1, 3, 5, 2, 4, 6] [[1, 3, 5], [2, 4, 6]]
2)