diff --git a/solutions/sem01/lesson03/task1.py b/solutions/sem01/lesson03/task1.py index f1d8fe26b..7b048e654 100644 --- a/solutions/sem01/lesson03/task1.py +++ b/solutions/sem01/lesson03/task1.py @@ -1,3 +1,3 @@ def flip_bits_in_range(num: int, left_bit: int, right_bit: int) -> int: # ваш код - return num \ No newline at end of file + return num diff --git a/solutions/sem01/lesson03/task2.py b/solutions/sem01/lesson03/task2.py index a3a738c2a..5cf2b6316 100644 --- a/solutions/sem01/lesson03/task2.py +++ b/solutions/sem01/lesson03/task2.py @@ -1,3 +1,3 @@ def get_cube_root(n: float, eps: float) -> float: # ваш код - return n \ No newline at end of file + return n diff --git a/solutions/sem01/lesson04/task1.py b/solutions/sem01/lesson04/task1.py index 47384423a..0135e399b 100644 --- a/solutions/sem01/lesson04/task1.py +++ b/solutions/sem01/lesson04/task1.py @@ -1,3 +1,3 @@ def is_arithmetic_progression(lst: list[list[int]]) -> bool: # ваш код - return False \ No newline at end of file + return False diff --git a/solutions/sem01/lesson04/task2.py b/solutions/sem01/lesson04/task2.py index 4591d0a3e..5d6f8ee8a 100644 --- a/solutions/sem01/lesson04/task2.py +++ b/solutions/sem01/lesson04/task2.py @@ -1,3 +1,3 @@ def merge_intervals(intervals: list[list[int, int]]) -> list[list[int, int]]: # ваш код - return [[0,0]] \ No newline at end of file + return [[0, 0]] diff --git a/solutions/sem01/lesson04/task4.py b/solutions/sem01/lesson04/task4.py index b21bc5a39..2664384d8 100644 --- a/solutions/sem01/lesson04/task4.py +++ b/solutions/sem01/lesson04/task4.py @@ -1,3 +1,3 @@ def move_zeros_to_end(nums: list[int]) -> list[int]: # ваш код - return 0 \ No newline at end of file + return 0 diff --git a/solutions/sem01/lesson04/task5.py b/solutions/sem01/lesson04/task5.py index 02d7742bb..ec6932ee4 100644 --- a/solutions/sem01/lesson04/task5.py +++ b/solutions/sem01/lesson04/task5.py @@ -1,3 +1,3 @@ def find_row_with_most_ones(matrix: list[list[int]]) -> int: # ваш код - return 0 \ No newline at end of file + return 0 diff --git a/solutions/sem01/lesson04/task6.py b/solutions/sem01/lesson04/task6.py index 16df27ca6..d16e77dda 100644 --- a/solutions/sem01/lesson04/task6.py +++ b/solutions/sem01/lesson04/task6.py @@ -1,3 +1,3 @@ -def count_cycles(arr: list[int]) -> int: +def count_cycles(arr: list[int]) -> int: # ваш код - return 0 \ No newline at end of file + return 0 diff --git a/solutions/sem01/lesson05/task1.py b/solutions/sem01/lesson05/task1.py index 9a17211e5..fdf3b5488 100644 --- a/solutions/sem01/lesson05/task1.py +++ b/solutions/sem01/lesson05/task1.py @@ -1,3 +1,3 @@ def is_palindrome(text: str) -> bool: # ваш код - return False \ No newline at end of file + return False diff --git a/solutions/sem01/lesson05/task2.py b/solutions/sem01/lesson05/task2.py index 367503802..c70b40298 100644 --- a/solutions/sem01/lesson05/task2.py +++ b/solutions/sem01/lesson05/task2.py @@ -1,3 +1,3 @@ def are_anagrams(word1: str, word2: str) -> bool: # ваш код - return False \ No newline at end of file + return False diff --git a/solutions/sem01/lesson05/task4.py b/solutions/sem01/lesson05/task4.py index 4c4e9086e..7c2c26f17 100644 --- a/solutions/sem01/lesson05/task4.py +++ b/solutions/sem01/lesson05/task4.py @@ -1,3 +1,3 @@ def unzip(compress_text: str) -> str: # ваш код - return compress_text \ No newline at end of file + return compress_text diff --git a/solutions/sem01/lesson05/task5.py b/solutions/sem01/lesson05/task5.py index 076c5bb6c..da9e6d08c 100644 --- a/solutions/sem01/lesson05/task5.py +++ b/solutions/sem01/lesson05/task5.py @@ -1,3 +1,3 @@ -def reg_validator(reg_expr: str, text: str) -> bool: +def reg_validator(reg_expr: str, text: str) -> bool: # ваш код - return False \ No newline at end of file + return False diff --git a/solutions/sem01/lesson05/task6.py b/solutions/sem01/lesson05/task6.py index 1b914ada7..63207797d 100644 --- a/solutions/sem01/lesson05/task6.py +++ b/solutions/sem01/lesson05/task6.py @@ -1,3 +1,3 @@ def simplify_path(path: str) -> str: # ваш код - return path \ No newline at end of file + return path diff --git a/solutions/sem01/lesson06/task1.py b/solutions/sem01/lesson06/task1.py index 2d1e30e96..353cb3616 100644 --- a/solutions/sem01/lesson06/task1.py +++ b/solutions/sem01/lesson06/task1.py @@ -1,3 +1,3 @@ def int_to_roman(num: int) -> str: # ваш код - return "" \ No newline at end of file + return "" diff --git a/solutions/sem01/lesson06/task2.py b/solutions/sem01/lesson06/task2.py index f535b5a0c..f1034e24e 100644 --- a/solutions/sem01/lesson06/task2.py +++ b/solutions/sem01/lesson06/task2.py @@ -1,3 +1,3 @@ def get_len_of_longest_substring(text: str) -> int: # ваш код - return 0 \ No newline at end of file + return 0 diff --git a/solutions/sem01/lesson06/task3.py b/solutions/sem01/lesson06/task3.py index 7449a1e72..b160d615a 100644 --- a/solutions/sem01/lesson06/task3.py +++ b/solutions/sem01/lesson06/task3.py @@ -2,6 +2,5 @@ def is_there_any_good_subarray( nums: list[int], k: int, ) -> bool: - # ваш код return False diff --git a/solutions/sem01/lesson06/task4.py b/solutions/sem01/lesson06/task4.py index 5b75a110c..95a7098e4 100644 --- a/solutions/sem01/lesson06/task4.py +++ b/solutions/sem01/lesson06/task4.py @@ -1,3 +1,3 @@ def count_unique_words(text: str) -> int: # ваш код - return 0 \ No newline at end of file + return 0 diff --git a/solutions/sem01/lesson08/task1.py b/solutions/sem01/lesson08/task1.py index 4390f6c84..7fa724ef8 100644 --- a/solutions/sem01/lesson08/task1.py +++ b/solutions/sem01/lesson08/task1.py @@ -1,5 +1,6 @@ from typing import Callable + def make_averager(accumulation_period: int) -> Callable[[float], float]: # ваш код - pass \ No newline at end of file + pass diff --git a/solutions/sem01/lesson08/task2.py b/solutions/sem01/lesson08/task2.py index 6e4af8707..cc2ae4303 100644 --- a/solutions/sem01/lesson08/task2.py +++ b/solutions/sem01/lesson08/task2.py @@ -2,9 +2,7 @@ T = TypeVar("T") -def collect_statistic( - statistics: dict[str, list[float, int]] -) -> Callable[[T], T]: - + +def collect_statistic(statistics: dict[str, list[float, int]]) -> Callable[[T], T]: # ваш код - pass \ No newline at end of file + pass diff --git a/solutions/sem02/lesson03/task1.py b/solutions/sem02/lesson03/task1.py index 2c3fc0b58..9fe8943a8 100644 --- a/solutions/sem02/lesson03/task1.py +++ b/solutions/sem02/lesson03/task1.py @@ -8,13 +8,24 @@ class ShapeMismatchError(Exception): def sum_arrays_vectorized( lhs: np.ndarray, rhs: np.ndarray, -) -> np.ndarray: ... +) -> np.ndarray: + if lhs.shape != rhs.shape: + raise ShapeMismatchError + return lhs + rhs -def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray: ... + +def compute_poly_vectorized(abscissa: np.ndarray) -> np.ndarray: + return 3 * abscissa**2 + 2 * abscissa + 1 def get_mutual_l2_distances_vectorized( lhs: np.ndarray, rhs: np.ndarray, -) -> np.ndarray: ... +) -> np.ndarray: + if lhs.shape[1] != rhs.shape[1]: + raise ShapeMismatchError + + diff = lhs[:, np.newaxis, :] - rhs[np.newaxis, :, :] + + return np.sqrt(np.sum(diff**2, axis=-1)) diff --git a/solutions/sem02/lesson03/task2.py b/solutions/sem02/lesson03/task2.py index fc823c1d6..30da3f28c 100644 --- a/solutions/sem02/lesson03/task2.py +++ b/solutions/sem02/lesson03/task2.py @@ -9,11 +9,27 @@ def convert_from_sphere( distances: np.ndarray, azimuth: np.ndarray, inclination: np.ndarray, -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: ... +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + if distances.shape != azimuth.shape or distances.shape != inclination.shape: + raise ShapeMismatchError + + x = distances * np.sin(inclination) * np.cos(azimuth) + y = distances * np.sin(inclination) * np.sin(azimuth) + z = distances * np.cos(inclination) + + return x, y, z def convert_to_sphere( abscissa: np.ndarray, ordinates: np.ndarray, applicates: np.ndarray, -) -> tuple[np.ndarray, np.ndarray, np.ndarray]: ... +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + if abscissa.shape != ordinates.shape or abscissa.shape != applicates.shape: + raise ShapeMismatchError + + distances = np.sqrt(abscissa**2 + ordinates**2 + applicates**2) + azimuth = np.arctan2(ordinates, abscissa) + inclination = np.arctan2(np.sqrt(abscissa**2 + ordinates**2), applicates) + + return distances, azimuth, inclination diff --git a/solutions/sem02/lesson03/task3.py b/solutions/sem02/lesson03/task3.py index 477acd0ce..2bc50c3c9 100644 --- a/solutions/sem02/lesson03/task3.py +++ b/solutions/sem02/lesson03/task3.py @@ -3,4 +3,18 @@ def get_extremum_indices( ordinates: np.ndarray, -) -> tuple[np.ndarray, np.ndarray]: ... +) -> tuple[np.ndarray, np.ndarray]: + if ordinates.size < 3: + raise ValueError + + middle = ordinates[1:-1] + left = ordinates[:-2] + right = ordinates[2:] + + minima_mask = (middle < left) & (middle < right) + maxima_mask = (middle > left) & (middle > right) + + minima_indices = np.where(minima_mask)[0] + 1 + maxima_indices = np.where(maxima_mask)[0] + 1 + + return minima_indices, maxima_indices diff --git a/solutions/sem02/lesson04/task1.py b/solutions/sem02/lesson04/task1.py index 1b5526c1f..bffd75dbd 100644 --- a/solutions/sem02/lesson04/task1.py +++ b/solutions/sem02/lesson04/task1.py @@ -2,16 +2,41 @@ def pad_image(image: np.ndarray, pad_size: int) -> np.ndarray: - # ваш код - return image + if pad_size < 1: + raise ValueError + + height, width = image.shape[:2] + new_shape = (height + 2 * pad_size, width + 2 * pad_size) + image.shape[2:] + + padded = np.zeros(new_shape, dtype=image.dtype) + padded[pad_size : pad_size + height, pad_size : pad_size + width] = image + + return padded def blur_image( image: np.ndarray, kernel_size: int, ) -> np.ndarray: - # ваш код - return image + if kernel_size < 1 or kernel_size % 2 == 0: + raise ValueError + + if kernel_size == 1: + return image.copy() + + pad_size = kernel_size // 2 + padded = pad_image(image, pad_size) + + height, width = image.shape[:2] + accumulator = np.zeros(image.shape, dtype=np.float64) + + for di in range(kernel_size): + for dj in range(kernel_size): + accumulator += padded[di : di + height, dj : dj + width] + + result = accumulator / (kernel_size**2) + + return result.astype(image.dtype) if __name__ == "__main__": diff --git a/solutions/sem02/lesson04/task2.py b/solutions/sem02/lesson04/task2.py index be9a2288f..a73a9b307 100644 --- a/solutions/sem02/lesson04/task2.py +++ b/solutions/sem02/lesson04/task2.py @@ -5,6 +5,22 @@ def get_dominant_color_info( image: np.ndarray[np.uint8], threshold: int = 5, ) -> tuple[np.uint8, float]: - # ваш код + if threshold < 1: + raise ValueError("threshold must be positive") - return 0, 0 + total = image.size + histogram = np.bincount(image.flatten(), minlength=256) + + cumulative = np.concatenate(([0], np.cumsum(histogram))) + + colors = np.arange(256) + left = np.maximum(0, colors - threshold + 1) + right = np.minimum(256, colors + threshold) + + counts = cumulative[right] - cumulative[left] + counts[histogram == 0] = -1 + + dominant_color = np.argmax(counts) + percent = counts[dominant_color] / total * 100 + + return np.uint8(dominant_color), percent diff --git a/solutions/sem02/lesson05/task1.py b/solutions/sem02/lesson05/task1.py index e9c7c3c56..5431d6301 100644 --- a/solutions/sem02/lesson05/task1.py +++ b/solutions/sem02/lesson05/task1.py @@ -9,4 +9,18 @@ def can_satisfy_demand( costs: np.ndarray, resource_amounts: np.ndarray, demand_expected: np.ndarray, -) -> bool: ... +) -> bool: + if costs.ndim != 2: + raise ShapeMismatchError + + m, n = costs.shape + + if resource_amounts.shape != (m,): + raise ShapeMismatchError + + if demand_expected.shape != (n,): + raise ShapeMismatchError + + resources_required = costs @ demand_expected + + return bool(np.all(resources_required <= resource_amounts)) diff --git a/solutions/sem02/lesson05/task2.py b/solutions/sem02/lesson05/task2.py index be1fb9d2b..fc7e71a98 100644 --- a/solutions/sem02/lesson05/task2.py +++ b/solutions/sem02/lesson05/task2.py @@ -8,4 +8,23 @@ class ShapeMismatchError(Exception): def get_projections_components( matrix: np.ndarray, vector: np.ndarray, -) -> tuple[np.ndarray | None, np.ndarray | None]: ... +) -> tuple[np.ndarray | None, np.ndarray | None]: + if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]: + raise ShapeMismatchError + + if matrix.shape[1] != vector.shape[0]: + raise ShapeMismatchError + + n = matrix.shape[0] + + if np.linalg.matrix_rank(matrix) != n: + return None, None + + scalar_products = matrix @ vector + squared_norms = np.sum(matrix**2, axis=1) + coefficients = scalar_products / squared_norms + + projections = coefficients[:, np.newaxis] * matrix + components = vector - projections + + return projections, components diff --git a/solutions/sem02/lesson05/task3.py b/solutions/sem02/lesson05/task3.py index 0c66906cb..9cf085890 100644 --- a/solutions/sem02/lesson05/task3.py +++ b/solutions/sem02/lesson05/task3.py @@ -9,4 +9,25 @@ def adaptive_filter( Vs: np.ndarray, Vj: np.ndarray, diag_A: np.ndarray, -) -> np.ndarray: ... +) -> np.ndarray: + if Vs.ndim != 2 or Vj.ndim != 2 or diag_A.ndim != 1: + raise ShapeMismatchError + + if Vs.shape[0] != Vj.shape[0]: + raise ShapeMismatchError + + if Vj.shape[1] != diag_A.shape[0]: + raise ShapeMismatchError + + m = Vs.shape[0] + k = Vj.shape[1] + + Vj_H = Vj.conj().T + A = np.diag(diag_A) + + inner = np.eye(k) + Vj_H @ Vj @ A + inner_inv = np.linalg.inv(inner) + + R_inv = np.eye(m) - Vj @ inner_inv @ Vj_H + + return R_inv @ Vs diff --git a/solutions/sem02/lesson07/task1.py b/solutions/sem02/lesson07/task1.py index 3a505d89b..8e452a90b 100644 --- a/solutions/sem02/lesson07/task1.py +++ b/solutions/sem02/lesson07/task1.py @@ -1,5 +1,4 @@ from typing import Any - import matplotlib.pyplot as plt import numpy as np @@ -13,16 +12,57 @@ def visualize_diagrams( ordinates: np.ndarray, diagram_type: Any, ) -> None: - # ваш код - pass + if abscissa.shape != ordinates.shape: + raise ShapeMismatchError("Razmery massivov ne sovpadayut") + dopustimye_tipy = ("hist", "box", "violin") + if diagram_type not in dopustimye_tipy: + raise ValueError("Nedopustimyi tip diagrammy") -if __name__ == "__main__": - mean = [2, 3] - cov = [[1, 1], [1, 2]] - space = 0.2 + figura = plt.figure(figsize=(8, 8)) + prosvet = 0.3 + setka = plt.GridSpec(4, 4, wspace=prosvet, hspace=prosvet) + + os_glavnaya = figura.add_subplot(setka[:-1, 1:]) + os_glavnaya.scatter(abscissa, ordinates, color="seagreen", alpha=0.5, s=15) + + if diagram_type == "hist": + os_v = figura.add_subplot(setka[:-1, 0], sharey=os_glavnaya) + os_g = figura.add_subplot(setka[-1, 1:], sharex=os_glavnaya) + + os_g.hist(abscissa, bins=50, color="indianred", alpha=0.6, density=True) + os_v.hist( + ordinates, bins=50, color="indianred", alpha=0.6, density=True, orientation="horizontal" + ) + + os_g.invert_yaxis() + os_v.invert_xaxis() + + elif diagram_type == "violin": + os_v = figura.add_subplot(setka[:-1, 0], sharey=os_glavnaya) + os_g = figura.add_subplot(setka[-1, 1:], sharex=os_glavnaya) - abscissa, ordinates = np.random.multivariate_normal(mean, cov, size=1000).T + os_v.violinplot(ordinates, vert=True, showmedians=True) + os_g.violinplot(abscissa, vert=False, showmedians=True) + + os_g.invert_yaxis() + os_v.invert_xaxis() + + elif diagram_type == "box": + os_v = figura.add_subplot(setka[:-1, 0], sharey=os_glavnaya) + os_g = figura.add_subplot(setka[-1, 1:], sharex=os_glavnaya) + + os_v.boxplot(ordinates, vert=True, patch_artist=True) + os_g.boxplot(abscissa, vert=False, patch_artist=True) + + os_g.invert_yaxis() + os_v.invert_xaxis() - visualize_diagrams(abscissa, ordinates, "hist") plt.show() + + +if __name__ == "__main__": + x = np.random.normal(2, 1, 1000) + y = x + np.random.normal(1, 1, 1000) + + visualize_diagrams(x, y, "hist") diff --git a/solutions/sem02/lesson08/task1.py b/solutions/sem02/lesson08/task1.py index 89f88572f..217f8a7d7 100644 --- a/solutions/sem02/lesson08/task1.py +++ b/solutions/sem02/lesson08/task1.py @@ -1,35 +1,89 @@ from functools import partial - import matplotlib.pyplot as plt import numpy as np - from IPython.display import HTML from matplotlib.animation import FuncAnimation +def _calculate_signal(time_array, modulation, fc): + carrier = np.sin(2 * np.pi * fc * time_array) + + if modulation is not None: + return modulation(time_array) * carrier + else: + return carrier + + +def _update_frame(frame_id, line, axis, modulation, fc, plot_duration, time_step, animation_step): + start_time = frame_id * animation_step + end_time = start_time + plot_duration + + t = np.arange(start_time, end_time, time_step) + y = _calculate_signal(t, modulation, fc) + + line.set_data(t, y) + axis.set_xlim(start_time, end_time) + axis.set_ylim(-2.5, 2.5) + + return (line,) + + def create_modulation_animation( - modulation, - fc, - num_frames, - plot_duration, - time_step=0.001, - animation_step=0.01, - save_path="" + modulation, fc, num_frames, plot_duration, time_step=0.001, animation_step=0.01, save_path="" ) -> FuncAnimation: - # ваш код - return FuncAnimation() + fig, ax = plt.subplots(figsize=(10, 5)) + + fig.patch.set_facecolor( + "#004488" + ) # рассцветку фона и линий нагло украл из инженерных чертежей из мультов, она очень стильная + ax.set_facecolor("#004488") + + ax.set_title("Amplitude Modulation Signal", fontsize=14, fontweight="bold", color="white") + ax.set_xlabel("Time, [s]", color="white") + ax.set_ylabel("Amplitude", color="white") + + ax.grid(True, color="gray", linestyle="--", alpha=0.5) + + ax.tick_params(colors="white") + for spine in ax.spines.values(): + spine.set_edgecolor("white") + + (line,) = ax.plot([], [], lw=2, color="white") + + update_with_args = partial( + _update_frame, + line=line, + axis=ax, + modulation=modulation, + fc=fc, + plot_duration=plot_duration, + time_step=time_step, + animation_step=animation_step, + ) + + anim = FuncAnimation( + fig, update_with_args, frames=num_frames, interval=animation_step * 1000, blit=False + ) + + if save_path != "": + anim.save(save_path, writer="pillow") + else: + pass + + return anim if __name__ == "__main__": + def modulation_function(t): - return np.cos(t * 6) + return np.cos(t * 6) - num_frames = 100 - plot_duration = np.pi / 2 - time_step = 0.001 - animation_step = np.pi / 200 - fc = 50 - save_path_with_modulation = "modulated_signal.gif" + num_frames = 100 + plot_duration = np.pi / 2 + time_step = 0.001 + animation_step = np.pi / 200 + fc = 50 + save_path_with_modulation = "blueprint_signal.gif" animation = create_modulation_animation( modulation=modulation_function, @@ -38,6 +92,7 @@ def modulation_function(t): plot_duration=plot_duration, time_step=time_step, animation_step=animation_step, - save_path=save_path_with_modulation + save_path=save_path_with_modulation, ) - HTML(animation.to_jshtml()) \ No newline at end of file + + HTML(animation.to_jshtml()) diff --git a/solutions/sem02/lesson08/task2.py b/solutions/sem02/lesson08/task2.py index b677c0702..43d11ac93 100644 --- a/solutions/sem02/lesson08/task2.py +++ b/solutions/sem02/lesson08/task2.py @@ -7,28 +7,26 @@ from matplotlib.animation import FuncAnimation - - def animate_wave_algorithm( - maze: np.ndarray, - start: tuple[int, int], - end: tuple[int, int], - save_path: str = "" -) -> FuncAnimation: + maze: np.ndarray, start: tuple[int, int], end: tuple[int, int], save_path: str = "" +) -> FuncAnimation: # ваш код return FuncAnimation() + if __name__ == "__main__": # Пример 1 - maze = np.array([ - [0, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 1, 1, 0], - [1, 1, 0, 1, 0, 1, 0], - [0, 0, 1, 1, 0, 1, 0], - [0, 0, 0, 0, 0, 1, 0], - [1, 1, 1, 1, 1, 1, 0], - [0, 0, 0, 0, 0, 0, 0], - ]) + maze = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [1, 1, 0, 1, 0, 1, 0], + [0, 0, 1, 1, 0, 1, 0], + [0, 0, 0, 0, 0, 1, 0], + [1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + ] + ) start = (2, 0) end = (5, 0) @@ -36,9 +34,9 @@ def animate_wave_algorithm( animation = animate_wave_algorithm(maze, start, end, save_path) HTML(animation.to_jshtml()) - + # Пример 2 - + maze_path = "./data/maze.npy" loaded_maze = np.load(maze_path) @@ -49,5 +47,3 @@ def animate_wave_algorithm( loaded_animation = animate_wave_algorithm(loaded_maze, start, end, loaded_save_path) HTML(loaded_animation.to_jshtml()) - - \ No newline at end of file diff --git a/solutions/sem02/lesson10/task1.ipynb b/solutions/sem02/lesson10/task1.ipynb index 4b4e9e335..a3c1a7217 100644 --- a/solutions/sem02/lesson10/task1.ipynb +++ b/solutions/sem02/lesson10/task1.ipynb @@ -39,9 +39,10 @@ "metadata": {}, "outputs": [], "source": [ + "import numpy as np\n", + "import pandas as pd\n", "import seaborn as sns\n", "\n", - "\n", "titanic_data = sns.load_dataset(\"titanic\")\n", "titanic_data.sample(5)" ] @@ -70,9 +71,7 @@ "id": "cd2f1773", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "propuski = titanic_data.isnull().sum()\npropuski" }, { "cell_type": "markdown", @@ -92,9 +91,7 @@ "id": "7e458447", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "n_strok = titanic_data.shape[0]\nn_stolbtsov = titanic_data.shape[1]\n\nporog_stolbtsov = n_strok / 2\ntitanic_chistiy = titanic_data.dropna(axis=\"columns\", thresh=porog_stolbtsov)\n\nporog_strok = titanic_chistiy.shape[1] / 2\ntitanic_chistiy = titanic_chistiy.dropna(thresh=porog_strok).copy()\n\nprint(f\"размер таблицы(я кстати даже тут зафейлил): {titanic_chistiy.shape}\")\ntitanic_chistiy.isnull().sum()" }, { "cell_type": "markdown", @@ -115,9 +112,7 @@ "id": "f7db5e99", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "vozrast_est = titanic_chistiy[\"age\"].notnull()\n\nmuzhchiny = titanic_chistiy[\"who\"] == \"man\"\nzhenschiny = titanic_chistiy[\"who\"] == \"woman\"\ndeti = titanic_chistiy[\"who\"] == \"child\"\n\nvozrast_muzhchin = titanic_chistiy.loc[vozrast_est & muzhchiny, \"age\"]\nvozrast_zhenschin = titanic_chistiy.loc[vozrast_est & zhenschiny, \"age\"]\nvozrast_detey = titanic_chistiy.loc[vozrast_est & deti, \"age\"]\n\nmediana_muzhchin = round(vozrast_muzhchin.median())\nmediana_zhenschin = round(vozrast_zhenschin.median())\nmediana_detey = round(vozrast_detey.median())\n\nprint(f\"срзнач мужчин: {mediana_muzhchin}\")\nprint(f\"женщин: {mediana_zhenschin}\")\nprint(f\"детей: {mediana_detey}\")\n\nvozrast_pusto = titanic_chistiy[\"age\"].isnull()\n\ntitanic_chistiy.loc[vozrast_pusto & muzhchiny, \"age\"] = mediana_muzhchin\ntitanic_chistiy.loc[vozrast_pusto & zhenschiny, \"age\"] = mediana_zhenschin\ntitanic_chistiy.loc[vozrast_pusto & deti, \"age\"] = mediana_detey\n\nprint(f\"пропуски в столбце age: {titanic_chistiy['age'].isnull().sum()}\")\ntitanic_chistiy.isnull().sum()" }, { "cell_type": "markdown", @@ -135,9 +130,7 @@ "id": "67a0c6bc", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "n_stolbtsov_teper = titanic_chistiy.shape[1]\nmin_znacheniy = n_stolbtsov_teper - 1\ntitanic_chistiy = titanic_chistiy.dropna(thresh=min_znacheniy)\n\nvse_propuski = titanic_chistiy.isnull().sum().sum()\nprint(f\"размер: {titanic_chistiy.shape}\")\nprint(f\"пропуски: {vse_propuski}\")" }, { "cell_type": "markdown", @@ -155,9 +148,7 @@ "id": "6a2d0ae9", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "goroda = titanic_chistiy[\"embark_town\"].value_counts()\n\nglavniy_gorod = goroda.index[0]\n\nprint(f\"самый популярный город: {glavniy_gorod}\")\ngoroda" }, { "cell_type": "markdown", @@ -175,9 +166,7 @@ "id": "11acb4b4", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "vyzhilo = titanic_chistiy[\"survived\"].sum()\nvsego = titanic_chistiy.shape[0]\n\ndolya = vyzhilo / vsego\nprotcent = round(dolya * 100, 2)\n\nprint(f\"сыжившие: {vyzhilo} из {vsego}\")\nprint(f\"процент: {protcent}%\")" }, { "cell_type": "markdown", @@ -195,9 +184,7 @@ "id": "59ec7295", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "vyzhivshiye = titanic_chistiy[titanic_chistiy[\"survived\"] == 1]\n\nvyzhivshiye_po_gorodam = vyzhivshiye[\"embark_town\"].value_counts()\nvyzhivshiye_po_gorodam" }, { "cell_type": "markdown", @@ -215,9 +202,7 @@ "id": "34daca28", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "klassy = titanic_chistiy[\"class\"].unique()\nslovar_protsentov = {}\n\nfor klass in klassy:\n gruppa = titanic_chistiy[titanic_chistiy[\"class\"] == klass]\n\n vsego_v_klasse = gruppa.shape[0]\n vyzhilo_v_klasse = gruppa[\"survived\"].sum()\n\n protcent = round(vyzhilo_v_klasse / vsego_v_klasse * 100, 2)\n slovar_protsentov[klass] = protcent\n\nprotcenty_po_klassam = pd.Series(slovar_protsentov)\nprotcenty_po_klassam" }, { "cell_type": "markdown", @@ -235,9 +220,7 @@ "id": "1fc0d667", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "bogatiye = titanic_chistiy[titanic_chistiy[\"fare\"] >= 100]\n\nvsego_bogatikh = bogatiye.shape[0]\nvyzhilo_bogatikh = bogatiye[\"survived\"].sum()\n\nprotcent_bogatikh = round(vyzhilo_bogatikh / vsego_bogatikh * 100, 2)\nprint(f\"Богатые: {vsego_bogatikh}\")\nprint(f\"выжило: {vyzhilo_bogatikh}\")\nprint(f\"Процент: {protcent_bogatikh}%\")" }, { "cell_type": "markdown", @@ -255,16 +238,14 @@ "id": "480352b6", "metadata": {}, "outputs": [], - "source": [ - "# ваш код" - ] + "source": "rebyata = titanic_chistiy[\"who\"] == \"child\"\nodni = titanic_chistiy[\"alone\"]\n\ndeti_odni = titanic_chistiy[rebyata & odni]\n\nprint(f\"дети в одиночку: {deti_odni.shape[0]}\")" }, { "cell_type": "markdown", "id": "aac62cfd", "metadata": {}, "source": [ - "Какие выводы вы можете сделать о выживших пассажирах Титаника? " + "почему я не был на титанике :((" ] } ], @@ -289,4 +270,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file