Thursday, August 1, 2024

📑 In Progress

📑 Task

1)
2)

📑 Answer

1)
2)

Sunday, July 14, 2024

📑 Rounding

📑 Task

1) What will be the result of running the code?
2) What symbol should be removed so that
the second number in the resulting list becomes 2 less?

📑 Answer

1) [28.0, 66.0]
2) '1' should be removed

Saturday, June 22, 2024

📑 Global Variables in Lambda Functions

📑 Task

1) What object does this specific function modify and
what will the code print when the mini program runs?
2) Change this code snippet so that: a) the function can be used to generate Fibonacci sequences
independently, without relying on a global state
b) it returns only the n-st number of the sequence

📑 Answer

1) The function changes the global variable with
the initial value "empty list" by iterative appending
The result of the launch is a printout of a list
(the first ten numbers of the Fibonacci series)
2)

Thursday, June 13, 2024

📑 Custom Dictionaries

📑 Task

1) Describe the properties of the created custom dictionary
2) Define another dictionary in a similar way but with other properties
Your dictionary can have a list as a value only where it's necessary
That is, only where several values correspond to one key
in the definding process

📑 Answer

1) - **Key-Value Mapping**:
The dictionary maps integer keys to their corresponding binary string
representation, padded with leading zeros to a fixed length of 16 bits.
- **Automatic Conversion**:
When setting a new key-value pair using the `__setitem__` method,
the integer key is automatically converted to its binary string
representation before being stored in the dictionary.
- **Inheritance**:
By inheriting from `UserDict`, the `IntBinDict` class inherits
all the methods and properties of the built-in `dict` type,
allowing for seamless integration with existing Python code
that expects a dictionary-like object.
2)

Tuesday, June 4, 2024

📑 Items not Defined in the Dictionary

📑 Task

1) What element removing is fundamentally different from
all others for dictionary in this code fragment?
2) Suggest programs to access elements that do not exist
in the dictionary without causing an error

📑 Answer

1) Deleting "11" is different from all others, since such a key
was not defined in the dictionary
2)

Friday, May 31, 2024

📑 Pairs in Strings

📑 Task

1) What does this program calculate?
2) Suggest a program for easier calculation of this indicator

📑 Answer

1) This program calculates the maximum number of pairs of the same letters
in a given string, taking into account all possible shifts of the string.
2)

Monday, May 27, 2024

📑 Coroutine Math Functions

📑 Task

1) What is the name of the special type of functions
(the second one in the given code fragment)?
Why do we add "None" to the beginning of the list of angle measurements?
2) Modify this function so that it collects values and does not print them out

📑 Answer

1) This is a coroutine function
We must initialize the coroutine and prepare it to accept values
so we are starting with None
2)

Sunday, May 26, 2024

📑 List Methods and Generators

📑 Task

1) What values do the generators calculate in this case?
What will the program print?
2) Give a similar example using generators and list methods,
where it is impossible to use lists with completely different values

📑 Answer

1) The outputs: [21, 'a', 21] and [2, 1, 1, 0, 0, 1, 2, 2, 1]
Both generators calculate their values in the first list
based on information from the second one
2)

Saturday, May 25, 2024

📑 Applying Class Methods

📑 Task

1) What value will "population" be after running the code?
2) Modify the class code so that its examples can transfer any indicators
to each other (energy, objects collected during the task, etc.)

📑 Answer

1) It will be zero again
2)

Thursday, May 23, 2024

📑 Table Formatting

📑 Task

1) Will the code throw an error due to
different lengths of nested components?
2) Suggest a code snippet that will turn nested lists
into tabs with html markup

📑 Answer

1) No, this function provides for filling missing values
with spaces when printing
2)

Tuesday, May 21, 2024

📑 Object Similarity

📑 Task

1) Can you explain difference between the follow objects:
x_same, x_copy, x_equal?
2) Write a function that compares two lists based on the following parameters:
a) is the list length the same,
b) do all unique elements match,
c) whether the composition of the list as a whole is the same,
d) are the elements arranged in the same order,
e) whether they have the same address in memory.
Apply it to the indicated objects

📑 Answer

1) a) x_same and x contain from the same elements,
but they are different and independent objects
b) x_equal refers to the same list object as x,
so they share the same memory address
c) x_copy refers to a new list object created by making
a shallow copy of x, so x_copy is a different object
with the connection to the original list because of
the nested mutable component []
2)

Sunday, May 19, 2024

📑 Count in Two

📑 Task

1) Will the functions count1() and count2() count events independently of each other?
2) How can we define other Python objects that allow us
to count events in programs using the same rule?
For example, classes or generators

📑 Answer

1) Yes, the functions will count independently of each other
depending on the number of calls
2)

Saturday, May 18, 2024

📑 Max Product of Three

📑 Task

1) Find a mistake in the process of recursion the function
for calculating the maximum product of three numbers in the list
2) Suggest a possible decision to build a recursive function

📑 Answer

1) Incorrect recursion logic: if the list becomes longer by one element,
then all the indices of the elements that give the maximum product
could be changed, not only one index
2)

Sunday, May 12, 2024

📑 Referring to the Same Object

📑 Task

1) Will the result of printing the values for the functions f1 and f2
be the same in all cases?
2) Print out the values of the function f2 at x = 1, 2, 3 so
that the result will be the same for all x

📑 Answer

1) When printed in a loop, the functions' values will be equal
For f1 the default list-argument changes
(it was set when the function was defined)
For f2 the same list-variable changes
(it was set as a global variable)
When printed by the generator, the functions' values become different
f1 continues to expand the default list-argument
f2 begins to expand the empty list-variable again
2)

Saturday, May 11, 2024

📑 Neuron Activations

📑 Task

1) Can you describe the goals of creating this type of objects?
2) Try to modify this class so that it becomes more
multifunctional and has several activation methods

📑 Answer

1) This Neuron class aims to provide a foundation for understanding how
individual neurons process input data and produce output in a neural network
2)

Friday, May 10, 2024

📑 Different Behavior of Functions

📑 Task

1) How will using this decorator affect the function?
2) Can you build your own decorator function that will affect the behavior
of user-defined or built-in functions depending on the arguments?

📑 Answer

1) This gives the function different behavior depending on the type of its argument
2)

📑 Countdown Timers

📑 Task

1) Explain the sequence of actions of this program
2) Can you suggest an alternative code for timing only in Python?

📑 Answer

1) This code renders the countdown timer in the output area
of the Jupyter notebook or IPython environment
It based on Javascript and HTML components, stored in Python strings
2)
import time
from datetime import datetime
def timer(maxiter=100):
    for i in range(maxiter):
        time.sleep(1)
        print(f"🕒 {(59 - datetime.now().second):0>2}", 
              flush=True, end='')
        print("\r", flush=True, end='')
timer()

📑 Memorization Decorators

📑 Task

1) What is the decorator used for in the second function definition?
2) Can you write your own decorator for the same goal?
import functools, time
def fibonacci1(n):
    if n < 2: return n
    return fibonacci1(n - 1) + fibonacci1(n - 2)
# a least-recently-used (LRU) cache eviction policy
@functools.lru_cache(maxsize=None)
def fibonacci2(n):
    if n < 2: return n
    return fibonacci2(n - 1) + fibonacci2(n - 2)
code_str = lambda f, n: f"""
start = time.time(); {f(n)}; stop = time.time() 
print(f'{f}: {{stop - start: e}}')"""
for f in [fibonacci1, fibonacci2]:
    exec(code_str(f, 30))

📑 Answer

1) The memoization provided by `functools.lru_cache` prevents redundant calculations
by storing previously computed Fibonacci numbers and
retrieving them from the cache when needed
2) The decorator with custom cache eviction policies and
different data structures for the cache
def cache(func):
    @functools.wraps(func)
    def wrapper_cache(*args, **kwargs):
        cache_key = args + tuple(kwargs.items())
        if cache_key not in wrapper_cache.cache:
            wrapper_cache.cache[cache_key] = func(*args, **kwargs)
        return wrapper_cache.cache[cache_key]
    wrapper_cache.cache = dict()
    return wrapper_cache
@cache
def fibonacci3(n):
    if n < 2: return n
    return fibonacci3(n - 1) + fibonacci3(n - 2)
for f in [fibonacci1, fibonacci2, fibonacci3]:
    exec(code_str(f, 30))

Thursday, May 9, 2024

📑 Sets and Elements

📑 Task

1) What will be the result of running the program?
2) Suggest as many other ways as possible to add and remove this element from the set
How else can a mini- program check if there is an element in a given set?

📑 Answer

1) Outputs: {0, '♗', '♙', 1, 2, 3, '♕', '♔', 4, '♖', '♘'} ♘ and False
2)


Wednesday, May 8, 2024

📑 Selecting the Maximum Values

📑 Task

1) Which built-in function will select from the list [a, b]
the same object as all expressions?
2) Can you continue this list and add some expressions with the same result?

📑 Answer

1) max(a, b)
2)

📑 Read-Write Attributes

📑 Task

1) The 'id' attribute is directly accessible and modifiable by the user
How this type of attributes is usually named?
2) Can you create another class that restricts access to
the id attribute for reading, making it write-only?
It will be great if you do this with additional hashing functionality.

📑 Answer

1) They are named 'read-write attributes' very often
2)

Tuesday, May 7, 2024

📑 Managed Attributes

📑 Task

1) Describe the object stored in variable c1
2) Create class attributes 'area' and 'circumference' and
convert them into properties or managed attributes

📑 Answer

1) The object stored in the variable c1 is an instance of the Circle class
It represents a circle with a radius derived
from the given diameter and a specified unit of measurement
2) Now the Circle class provides the ability to easily calculate
area and circumference for its instances

📑 Decorated Built-in Functions

📑 Task

1) What effect for the built-in function will we see after running this code?
2) Suggest a similar technique for rounding the results of calculations
of built-in mathematical functions, and also
provide a way to revert to the original built-in function

📑 Answer

1) The decorated print function now prints each argument
with a space at the end and flushes the output,
pausing for 1 second after printing each argument
2)

Sunday, May 5, 2024

📑 Ternary Operators

📑 Task

1) What actions will this program perform?
2) Can you write a code snippets with ternary operators inside math calculations?

📑 Answer

1) The program generates a number (-1, 0 or 1) using a special Python module
and uses the ternary operator to call one of three anonymous functions
depending on the pseudo-random selection of the number
2) Ternary operators have lower precedence than arithmetic operators

Thursday, May 2, 2024

📑 Reversed Linked Lists

📑 Task

1) How will the second row printed by the program differ from the 1st and 3rd?
2) Can you write the reverse() method in any other way?

📑 Answer

1) In the 2nd line the linked list is printed in reverse order
This is additionally indicated by a symbol between the list elements
2)

Wednesday, May 1, 2024

📑 Cycle Lists

📑 Task

1) What will the program print in the last line?
2) Modify the program so that the same result is produced by a generator function
with arguments: the original list, the starting character, and the length of the resulting list
Suggest variants of code for returning from the resulting list to the original list

📑 Answer

1) ['♗', '♘', '♙', '♔', '♕', '♖', '♗', '♘', '♙', '♔']
2)

📑 Lists with Periodic Patterns

📑 Task

1) Will the program print three separate lists of elements of different types
(letters, numbers, fruit symbols) at least in one of output rows?
2) How can you fix the third and fourth code lines
to get three separate lists of elements of different kinds?

📑 Answer

1) No
In the first case, lists of the required type will be inside tuples
In the second case, tuples of elements of different types will be formed
2)

📑 Boolean Functions for Non-Boolean Objects

📑 Task

1) What will the program print?
2) Explain the result of summation using a code snippet

📑 Answer

1) [] (Ellipsis,) {} {None}, 2, 3, 1
2) sum() calculates the sum of the boolean values (True = 1, False = 0)

Tuesday, April 30, 2024

📑 Logical Operators and Integers

📑 Task

1) What will the program print on the first and last lines?
2) Can you write functions that do the same actions with integers
and can be used in explanation of the result?

📑 Answer

1) 0 0 2 2 0 2 0 0 - the first line
2 9 9 2 0 11 2 36 - the last line
2)

Monday, April 29, 2024

📑 Difference in the Subset Sums 2

📑 Task

1) These programs divide a set into two subsets so
that the difference in the sums of the subsets is minimal
Can you describe the main principals that programs based?
2) Can you combine their solution methods in one program?


📑 Answer

1) The main principle behind these programs is dynamic programming.
The first program uses a table to store the results of subproblems
to find the minimum subset sum difference.
It iterates over the elements of the input array and
fills the table based on whether including or excluding an element results
in a subset sum closer to half of the total sum.
The second program uses a recursive approach to explore all possible subsets and find the minimum difference between the two subsets.
2)

📑 Difference in the Subset Sums

📑 Task

1) This program divides a set into two subsets so
that the difference in the sums of the subsets is minimal
The variable "table" indicates whether it is possible
to achieve a sum of j using the first i elements
Will all values be equal to 1 in the last row of the printed table?
2) During the iteration process, we actually only use the last two rows of the table
Can you modify the program using this fact?

📑 Answer

1) The last line will be [1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1]
We will not be able to get sums equal to 2 and 5
from the numbers presented in the original list
2)

Sunday, April 28, 2024

📑 Recursive Tables

📑 Task

1) What type of function is this?
2) How can you rewrite it so as not to use recursion?

📑 Answer

1) This is a recursive generator
It can be made infinite by removing the limiter max_count
2)

Saturday, April 27, 2024

📑 Default Arguments

📑 Task

1) What will the program print in the last 2 lines?
2) Why do variables change or not change in this way?
3) What minimal changes can be made to the program so that the values will be increased
and the last 2 lines will be 3 [0, 1, 2, 3] and 0 [0, 1, 2, 3]?

📑 Answer

1) 1 [0, 1, 1, 1] and 0 [0, 1, 1, 1]
2) Variables with mutable and immutable objects
are used as default arguments to a function
3)

📑 Presence in the List

📑 Task

1) What does the program do?
2) Can you write a function based on the same splitting procedure
to sort letters in a word (vowels and consonants)?

📑 Answer

1) This program generates x (a list of 10 random integers between 0 and 9) and
then initializes two empty lists (not_in_x and in_x) to store digits
based on their presence in the list x.
2)

Friday, April 26, 2024

📑 Sending Values to the Generator

📑 Task

1) What will the program print?
2) What types of functions are in the program?
3) How can you fix it so that the number 101 will also be printed?

📑 Answer

1) 111 121 131 141 151 161 171 181 191
2) An anonymous "lambda" function and
a function of the type "infinite generator" are used here
3)

Thursday, April 25, 2024

📑 Substring Counting

📑 Task

1) What result will the program produce?
2) Simplify the program to improve counting speed

📑 Answer

1) The program will return the number 3 by counting
the number of occurrences of the substring in the string
2) In the program it needs to replace recursion with a loop

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)

Tuesday, April 23, 2024

📑 A Ternary Numeral System

📑 Task

1) What result will this program produce?
2) Rewrite this function for the numeral system with the base 3 (ternary)

📑 Answer

1) True
2)

📑 Recursive Infinite Generators

📑 Task

1) What is the last number the program will print?
2) What object appears when this function is applied
3) Can you write a program for an infinite generator of fibonacci numbers
without recursion but limit the number of iterations?

📑 Answer

1) 34
2) It is a recursive infinite generator
3)

📑 A Series of Variables

📑 Task

1) What will the program print for each case?
2) How to change f_string_y in the program so that variables y0, y1, y2 become global

📑 Answer

1) x0=1 x1=2 x2=4 True and y0=1 y1=2 y2=4 False
2)

📑 Function Dictionary

📑 Task

1) What object is created by the first line of the program?
2) Rewrite the function so that the numbers from 0 to 3 are raised to the 2nd power

📑 Answer

1) The result is a function that creates a dictionary of functions
2)

📑 Copying Lists

📑 Task

1) What will the program print?
2) Make a list of identical elements and copy this list
so that the result of the last three lines looks different:
[[1], [], []] [[2], [], []]

📑 Answer

1) 2 lists of empty lists: [[], [], []] [[], [], []]
2 identical lists of elements: [[1, 2], [1, 2], [1, 2]] [[1, 2], [1, 2], [1, 2]]
2)

Monday, April 22, 2024

📑 Continue and Pass

📑 Task

1) Will the code print two identical lines?
2) How can you modify the code to avoid using external variables when
loading a string argument into the function exec()?

📑 Answer

1) The lines will be different:
- in the second case, the program will not perform any actions when i = 0,
- in the first case, it will skip this iteration
2)

📑 The special variable "_"

📑 Task

1) What properties of the “_” character do we observe in code cells?
2) How can you restore the properties of this special variable?





📑 Answer

1) "_" is a special variable that represents the last returned value
and reassigning "_" convert it into an usual variable
2)



Sunday, April 21, 2024

📑 Exploration of the Function locals()

📑 Task

1) What will the program print?
2) How can we change the 3rd line of the program so that
the function takes elements of the same dictionaries as arguments
but the program prints out only keys of these dictionaries?

📑 Answer

1) Two rows: True and ({'a': 1, 'b': 2}, {'b': 3})
2)

📑 Dictionary Comprehensions

📑 Task

1) What two numbers will the program print?
2) Replace the first five lines of the program with a single line
containing a dictionary comprehension

📑 Answer

1) 10 29
The first number is the sum of the keys of the resulting dictionary
The second number is the sum of its values
2)

📑 Boolean Values of Objects

📑 Task

1) What will be printed
2) Explain the result with a code snippet, then remove
one punctuation character so the program result would be 0

📑 Answer

1) 1
2)

📑 Nested Functions for Polynomials

📑 Task

1) What will be the result of the calculations?
2) Can you write this code in a form of an anonymous function?
3) Can you make this function more universal so that
it builds a polynomial of any degree using arguments as coefficients?

📑 Answer

1) $polynomials(1, 1, 1)(0)$ builds the function $f(x) = x^2 + x + 1$
and finds its value $f(x) = 1$ at $x = 0$ twice
So the program will print out $ 1 $
2)

3)

📑 Curly Braces inside F-strings

📑 Task

1) Will the code print out the elements of the interval?
2) What minimal changes can be made to the code to see
the elements of this interval?

📑 Answer

1) The code will only display the command text
{*map(str, numbers)} {*numbers}
2) It needs to add spaces between the curly braces
or replace the inner curly braces with square braces

📑 F-strings and Nested Lists

📑 Task

1) What will the program print?
2) How can you print the elements of the nested list:
the entire list [0, 1, 2] and the character with index 1 of the string 'abc'?

📑 Answer

1) [0, 1, 2] abc - elements of a nested list with indexes 1 and 0
b 0 - fragments of these elements list_[0][1] and list[1][0]
2)

Saturday, April 20, 2024

📑 "Join" Effects for Strings

📑 Task

1) What will be the result of launching the program?
2) How can you change the code so that
the number of integers and letters becomes equal?

📑 Answer

1) a0b1c
The program places integers in order (starting from zero)
between the first 3 letters of the Latin alphabet
2)

📑 Arguments of Named Tuples

📑 Task

1) What will be the result of executing the code?
2) Can you modify this function so that
the argument names of named tuples would be small Latin letters?
And if the number of arguments is more than 26
then the program would issue a warning "Use less than 26 arguments"?

📑 Answer

1) vector() vector(x1=1) vector(x1=1, x2=2)
This function creates named tuples "vector"
with an arbitrary number of arguments x1, x2, etc.
2)

📑 Search for Boolean Values

📑 Task

1) What will be the result of the calculation?
2) Can you suggest a program that will explain the result?

📑 Answer

1) The built-in function isinstance(x, int) classifies the values True and False
as integers and this program counts them in the variable integers_found
So the result will be: integers_found = 6; bools_found = 0
2)

📑 Lambda Multipliers

📑 Task

1) What objects does the program create?
2) What will be the result of running the code?
3) Can you suggest improvements of the program?

📑 Answer

1) The program creates a list of lambda functions
2) The code will print out four identical numbers 12
(the lambda functionsmultiplie the arguments equal to 3 by the same factor m=4)
3) To create lambda functions with different multipliers from 1 to m,
in the loop you need to change the definition of the variable "_"