From 223cf3d1c95074c9e571b291df8305039b45382a Mon Sep 17 00:00:00 2001 From: Peter Date: Sun, 18 Oct 2020 23:50:18 +0300 Subject: [PATCH 1/2] lecture 2 --- Practice/Peter_Fedotov/lecture2-1.py | 11 +++++++++++ Practice/Peter_Fedotov/lecture2-2.py | 10 ++++++++++ 2 files changed, 21 insertions(+) create mode 100644 Practice/Peter_Fedotov/lecture2-1.py create mode 100644 Practice/Peter_Fedotov/lecture2-2.py diff --git a/Practice/Peter_Fedotov/lecture2-1.py b/Practice/Peter_Fedotov/lecture2-1.py new file mode 100644 index 00000000..f3410375 --- /dev/null +++ b/Practice/Peter_Fedotov/lecture2-1.py @@ -0,0 +1,11 @@ +def test1 (a, b): + if a > b: + print(f"{a}more, than {b}") + elif b > a: + print(f"{b} more, than {a}") + elif a == b: + print(f"{a} equal {b}") +test1(3, 4) +test1(5, 6) +test1(7, 7) + diff --git a/Practice/Peter_Fedotov/lecture2-2.py b/Practice/Peter_Fedotov/lecture2-2.py new file mode 100644 index 00000000..f28119fd --- /dev/null +++ b/Practice/Peter_Fedotov/lecture2-2.py @@ -0,0 +1,10 @@ +def test2 (a, b): + if a > b: + print(f"{a}") + elif b > a: + print(f"{b}") + elif a == b: + print(f"enter different values") +test2(3, 1) +test2(3, 5) +test2(3, 3) \ No newline at end of file From 268f22dfbac7f16f1ac548bdd37b229ff362522a Mon Sep 17 00:00:00 2001 From: Peter Date: Mon, 19 Oct 2020 00:43:52 +0300 Subject: [PATCH 2/2] lecture 2 --- Practice/E_Shipunova/10.1Client.py | 11 -- Practice/E_Shipunova/10.1Server.py | 42 ------- Practice/E_Shipunova/10.2Client.py | 26 ---- Practice/E_Shipunova/10.2Server.py | 47 ------- Practice/E_Shipunova/10.3.py | 24 ---- Practice/E_Shipunova/2.1.py | 6 - Practice/E_Shipunova/2.2.py | 5 - Practice/E_Shipunova/2.3.py | 95 -------------- Practice/E_Shipunova/4.1.py | 13 -- Practice/E_Shipunova/4.2.py | 24 ---- Practice/E_Shipunova/4.3.py | 21 ---- Practice/E_Shipunova/4.4.py | 70 ----------- Practice/E_Shipunova/4.5.py | 16 --- Practice/E_Shipunova/4.6.py | 49 -------- Practice/E_Shipunova/5.1.py | 14 --- Practice/E_Shipunova/5.2.py | 30 ----- Practice/E_Shipunova/5.3.py | 41 ------ Practice/E_Shipunova/6.3.py | 16 --- Practice/E_Shipunova/6.4.py | 33 ----- Practice/E_Shipunova/7.1.py | 23 ---- Practice/E_Shipunova/7.2.py | 15 --- Practice/E_Shipunova/7.3dump.py | 26 ---- Practice/E_Shipunova/7.3load.py | 17 --- Practice/E_Shipunova/7.4.py | 59 --------- Practice/E_Shipunova/9.1.py | 93 -------------- Practice/E_Shipunova/9.2.py | 39 ------ Practice/E_Shipunova/9.3.py | 52 -------- Practice/E_Shipunova/git.txt | 27 ---- Practice/E_Shipunova/libHuman.py | 11 -- Practice/E_Shipunova/pep8.py | 74 ----------- Practice/E_Shipunova/razminka(gen).py | 11 -- Practice/E_Shipunova/razminka(git).py | 20 --- Practice/E_Shipunova/razminka(iter).py | 28 ----- Practice/E_Shipunova/razminka(zip).py | 12 -- Practice/E_Shipunova/test.txt | 3 - Practice/E_Shipunova/test/f1.txt | 0 Practice/E_Shipunova/test/p1/f2.txt | 0 Practice/E_Shipunova/test/p1/p3/f131.txt | 0 Practice/E_Shipunova/test/p1/p3/f132.txt | 0 Practice/E_Shipunova/user.py | 8 -- Practice/EvgeniySyatoykin/1.py | 7 -- Practice/EvgeniySyatoykin/2.1.py | 7 -- Practice/IvanovA/lec2-zad1.py | 8 -- Practice/IvanovA/lec2-zad2.py | 8 -- Practice/IvanovA/lec4-zad1.py | 9 -- Practice/IvanovA/lec4-zad2.py | 8 -- Practice/IvanovA/lec4-zad3.py | 14 --- Practice/IvanovA/lec4-zad4.py | 12 -- Practice/IvanovA/lec4-zad5.py | 7 -- Practice/IvanovA/lec5-zad1.py | 9 -- Practice/IvanovA/lec5-zad2.py | 19 --- Practice/IvanovA/lec6-zad3.py | 16 --- Practice/IvanovA/lec6-zad4.py | 17 --- Practice/IvanovA/lec7-zad-1.py | 22 ---- Practice/IvanovA/lec7-zad2.py | 6 - Practice/Karpov_A/Lec_6/t6_3.py | 17 --- Practice/Karpov_A/Lec_6/t6_4.py | 18 --- Practice/Karpov_A/pep8.py | 70 ----------- Practice/Karpov_A/t2_1.py | 8 -- Practice/Karpov_A/t2_2.py | 8 -- Practice/Karpov_A/t2_3.py | 58 --------- Practice/Karpov_A/t4_1.py | 12 -- Practice/Karpov_A/t4_2.py | 8 -- Practice/Karpov_A/t4_3.py | 14 --- Practice/Karpov_A/t4_4.py | 13 -- Practice/Karpov_A/t4_5.py | 6 - Practice/Karpov_A/t5_1.py | 10 -- Practice/Karpov_A/t5_2.py | 15 --- Practice/Karpov_A/t5_3.py | 35 ------ Practice/Karpov_A/t6_3.py | 17 --- Practice/Karpov_A/t6_4.py | 18 --- .../Postnikova/practice_10_task_1_client.py | 15 --- .../Postnikova/practice_10_task_1_server.py | 33 ----- .../Postnikova/practice_10_task_2_client.py | 31 ----- .../Postnikova/practice_10_task_2_server.py | 49 -------- Practice/Postnikova/practice_10_task_3.py | 33 ----- Practice/Postnikova/practice_9_task_1.py | 87 ------------- Practice/Postnikova/practice_9_task_2.py | 33 ----- Practice/Postnikova/practice_9_task_3.py | 26 ---- Practice/Postnikova/user.py | 12 -- Practice/README.md | 17 --- .../SNazarov/Control task/destination.txt | 1 - Practice/SNazarov/Control task/sourse.txt | 1 - .../__pycache__/task_5_1.cpython-38.pyc | Bin 662 -> 0 bytes Practice/SNazarov/myfile.txt | 1 - Practice/SNazarov/pep8.py | 69 ---------- Practice/SNazarov/task 4.1.py | 11 -- Practice/SNazarov/task 4.2.py | 11 -- Practice/SNazarov/task 4.3.py | 19 --- Practice/SNazarov/task 4.4.py | 29 ----- Practice/SNazarov/task 4.5.py | 10 -- Practice/SNazarov/task 4.6.py | 30 ----- Practice/SNazarov/task 5.2.py | 17 --- Practice/SNazarov/task 5.3.py | 35 ------ Practice/SNazarov/task2.1.py | 11 -- Practice/SNazarov/task2.2.py | 13 -- Practice/SNazarov/task2.3.py | 96 -------------- Practice/SNazarov/task_5_1.py | 12 -- Practice/SNazarov/task_6_3.py | 33 ----- Practice/SNazarov/task_6_4.py | 27 ---- Practice/SNazarov/task_7_1.py | 22 ---- Practice/SNazarov/task_7_2.py | 17 --- Practice/SNazarov/task_7_3.py | 48 ------- Practice/Salakhetdinova/lab2.py | 14 --- Practice/Salakhetdinova/lab2_2.py | 14 --- Practice/Salakhetdinova/lab4_1.py | 12 -- Practice/Salakhetdinova/lab4_2.py | 9 -- Practice/Salakhetdinova/lab4_3.py | 20 --- Practice/Salakhetdinova/lab4_4.py | 12 -- Practice/Salakhetdinova/lab4_5.py | 9 -- Practice/Salakhetdinova/lab5_1.py | 10 -- Practice/Salakhetdinova/lab5_2.py | 13 -- Practice/Sam_Kilyaev/Lection_2_Task_1.py | 16 --- Practice/Sam_Kilyaev/Lection_2_Task_2.py | 16 --- Practice/Sam_Kilyaev/Lection_2_Task_3.py | 79 ------------ Practice/Sam_Kilyaev/Lection_4_Task_1.py | 13 -- Practice/Sam_Kilyaev/Lection_4_Task_2.py | 11 -- Practice/Sam_Kilyaev/Lection_4_Task_3.py | 17 --- Practice/Sam_Kilyaev/Lection_4_Task_4.py | 16 --- Practice/Sam_Kilyaev/Lection_4_Task_5.py | 12 -- Practice/Sam_Kilyaev/Lection_4_Task_6.py | 44 ------- Practice/Sam_Kilyaev/Lection_5_Task_1.py | 11 -- Practice/Sam_Kilyaev/Lection_5_Task_2.py | 17 --- Practice/Sam_Kilyaev/Lection_5_Task_3.py | 34 ----- Practice/Sam_Kilyaev/Lection_6_Task_3.py | 20 --- Practice/Sam_Kilyaev/Lection_6_Task_4.py | 30 ----- Practice/Sam_Kilyaev/Lection_7_Razminka.py | 40 ------ Practice/Sam_Kilyaev/Lection_7_Task_1.py | 66 ---------- Practice/Sam_Kilyaev/Lection_7_Task_2.py | 24 ---- Practice/Sam_Kilyaev/pep8task.py | 79 ------------ Practice/ViktorGa/L2T1.py | 5 - Practice/ViktorGa/L2T2.py | 5 - Practice/ViktorGa/L4T1.py | 13 -- Practice/ViktorGa/L4T2.py | 8 -- Practice/ViktorGa/L4T3.py | 13 -- Practice/ViktorGa/L4T4.py | 24 ---- Practice/ViktorGa/L4T5.py | 10 -- Practice/ViktorGa/L5T1.py | 6 - Practice/ViktorGa/L5T2.py | 17 --- Practice/ViktorGa/L6T3.py | 15 --- Practice/ViktorGa/L6T4.py | 26 ---- Practice/ViktorGa/L7T1.py | 14 --- Practice/ViktorGa/L7T2.py | 15 --- Practice/ViktorGa/L7T3.py | 50 -------- Practice/ViktorGaL9/L9T1.py | 52 -------- Practice/ViktorGaL9/L9T2.py | 34 ----- .../lec3_practice/\321\201hoose.py" | 19 --- .../lec3_practice/\321\201ompare.py" | 14 --- Practice/amuratshin/lec4_practice/FizzBuzz.py | 9 -- Practice/amuratshin/lec4_practice/dict.py | 9 -- Practice/amuratshin/pep8task.py | 72 ----------- Practice/aulov_r/10lec1_client.py | 8 -- Practice/aulov_r/10lec1_server.py | 16 --- Practice/aulov_r/2lec1.py | 8 -- Practice/aulov_r/2lec2.py | 10 -- Practice/aulov_r/4lec1.py | 9 -- Practice/aulov_r/4lec2.py | 3 - Practice/aulov_r/4lec3.py | 21 ---- Practice/aulov_r/4lec4.py | 17 --- Practice/aulov_r/4lec5.py | 7 -- Practice/aulov_r/5lec1.py | 7 -- Practice/aulov_r/5lec2.py | 17 --- Practice/aulov_r/5lec3.py | 25 ---- Practice/aulov_r/6lec3.py | 18 --- Practice/aulov_r/6lec4.py | 5 - Practice/aulov_r/7lec1.py | 20 --- Practice/aulov_r/7lec2.py | 8 -- Practice/aulov_r/8lec3.py | 28 ----- Practice/aulov_r/8lec5.py | 9 -- Practice/aulov_r/9lec1.py | 38 ------ Practice/aulov_r/pep8.py | 72 ----------- Practice/ekaryagin/lab2.py | 27 ---- Practice/ekaryagin/lab4.py | 118 ------------------ Practice/ekaryagin/lab5.py | 93 -------------- Practice/ekaryagin/pep8task_.py | 69 ---------- .../o_komissarova/for_lec10/task1/Client.py | 25 ---- .../o_komissarova/for_lec10/task1/Server.py | 88 ------------- .../o_komissarova/for_lec10/task2/Client.py | 26 ---- .../o_komissarova/for_lec10/task2/Server.py | 51 -------- Practice/o_komissarova/for_lec10/task3.py | 21 ---- Practice/o_komissarova/for_lec11/task1.py | 44 ------- Practice/o_komissarova/for_lec11/task2.py | 101 --------------- .../o_komissarova/for_lec2/biggest_number.py | 27 ---- Practice/o_komissarova/for_lec2/game.py | 111 ---------------- Practice/o_komissarova/for_lec4/fizz_buzz.py | 17 --- .../o_komissarova/for_lec4/interpolate.py | 10 -- Practice/o_komissarova/for_lec4/matrix.py | 49 -------- .../o_komissarova/for_lec4/number_reader.py | 14 --- Practice/o_komissarova/for_lec4/replace.py | 39 ------ Practice/o_komissarova/for_lec4/sort.py | 17 --- Practice/o_komissarova/for_lec5/man_pupil.py | 24 ---- .../for_lec5/wrap_str_to_file.py | 43 ------- .../o_komissarova/for_lec6/cont_manager.py | 15 --- .../o_komissarova/for_lec6/itertools_task.py | 5 - .../o_komissarova/for_lec7/dir_follower.py | 24 ---- Practice/o_komissarova/for_lec7/human.data | Bin 601 -> 0 bytes Practice/o_komissarova/for_lec7/human.py | 50 -------- .../o_komissarova/for_lec7/subprocess_cat.py | 13 -- Practice/o_komissarova/for_lec7/text.txt | 5 - .../for_lec7/warm_up_find_git.py | 11 -- .../o_komissarova/for_lec7/warm_up_gen.py | 8 -- .../o_komissarova/for_lec7/warm_up_iter.py | 28 ----- .../for_lec7/warm_up_transpose.py | 30 ----- .../for_lec7/workdays_counter.py | 24 ---- Practice/o_komissarova/for_lec8/bonus.py | 45 ------- Practice/o_komissarova/for_lec8/source.txt | 1 - Practice/o_komissarova/for_lec8/task1.py | 8 -- Practice/o_komissarova/for_lec8/task10.py | 79 ------------ Practice/o_komissarova/for_lec8/task2.py | 5 - Practice/o_komissarova/for_lec8/task3.py | 38 ------ Practice/o_komissarova/for_lec8/task4.py | 12 -- Practice/o_komissarova/for_lec8/task5.py | 9 -- Practice/o_komissarova/for_lec8/task6.py | 22 ---- Practice/o_komissarova/for_lec8/task7.py | 10 -- Practice/o_komissarova/for_lec8/task8.py | 30 ----- Practice/o_komissarova/for_lec8/task9.py | 45 ------- Practice/o_komissarova/for_lec9/task1.py | 50 -------- Practice/o_komissarova/for_lec9/task2.py | 30 ----- Practice/o_komissarova/for_lec9/task3.py | 17 --- Practice/o_komissarova/pep8task.py | 86 ------------- Practice/shashalina/lec 4 task3.py | 0 Practice/shashalina/lec4 task1.py | 0 Practice/shashalina/lec4 task2.py | 0 Practice/shashalina/pep8task.py | 69 ---------- Practice/solkin/test1.py | 69 ---------- 225 files changed, 5732 deletions(-) delete mode 100644 Practice/E_Shipunova/10.1Client.py delete mode 100644 Practice/E_Shipunova/10.1Server.py delete mode 100644 Practice/E_Shipunova/10.2Client.py delete mode 100644 Practice/E_Shipunova/10.2Server.py delete mode 100644 Practice/E_Shipunova/10.3.py delete mode 100644 Practice/E_Shipunova/2.1.py delete mode 100644 Practice/E_Shipunova/2.2.py delete mode 100644 Practice/E_Shipunova/2.3.py delete mode 100644 Practice/E_Shipunova/4.1.py delete mode 100644 Practice/E_Shipunova/4.2.py delete mode 100644 Practice/E_Shipunova/4.3.py delete mode 100644 Practice/E_Shipunova/4.4.py delete mode 100644 Practice/E_Shipunova/4.5.py delete mode 100644 Practice/E_Shipunova/4.6.py delete mode 100644 Practice/E_Shipunova/5.1.py delete mode 100644 Practice/E_Shipunova/5.2.py delete mode 100644 Practice/E_Shipunova/5.3.py delete mode 100644 Practice/E_Shipunova/6.3.py delete mode 100644 Practice/E_Shipunova/6.4.py delete mode 100644 Practice/E_Shipunova/7.1.py delete mode 100644 Practice/E_Shipunova/7.2.py delete mode 100644 Practice/E_Shipunova/7.3dump.py delete mode 100644 Practice/E_Shipunova/7.3load.py delete mode 100644 Practice/E_Shipunova/7.4.py delete mode 100644 Practice/E_Shipunova/9.1.py delete mode 100644 Practice/E_Shipunova/9.2.py delete mode 100644 Practice/E_Shipunova/9.3.py delete mode 100644 Practice/E_Shipunova/git.txt delete mode 100644 Practice/E_Shipunova/libHuman.py delete mode 100644 Practice/E_Shipunova/pep8.py delete mode 100644 Practice/E_Shipunova/razminka(gen).py delete mode 100644 Practice/E_Shipunova/razminka(git).py delete mode 100644 Practice/E_Shipunova/razminka(iter).py delete mode 100644 Practice/E_Shipunova/razminka(zip).py delete mode 100644 Practice/E_Shipunova/test.txt delete mode 100644 Practice/E_Shipunova/test/f1.txt delete mode 100644 Practice/E_Shipunova/test/p1/f2.txt delete mode 100644 Practice/E_Shipunova/test/p1/p3/f131.txt delete mode 100644 Practice/E_Shipunova/test/p1/p3/f132.txt delete mode 100644 Practice/E_Shipunova/user.py delete mode 100644 Practice/EvgeniySyatoykin/1.py delete mode 100644 Practice/EvgeniySyatoykin/2.1.py delete mode 100644 Practice/IvanovA/lec2-zad1.py delete mode 100644 Practice/IvanovA/lec2-zad2.py delete mode 100644 Practice/IvanovA/lec4-zad1.py delete mode 100644 Practice/IvanovA/lec4-zad2.py delete mode 100644 Practice/IvanovA/lec4-zad3.py delete mode 100644 Practice/IvanovA/lec4-zad4.py delete mode 100644 Practice/IvanovA/lec4-zad5.py delete mode 100644 Practice/IvanovA/lec5-zad1.py delete mode 100644 Practice/IvanovA/lec5-zad2.py delete mode 100644 Practice/IvanovA/lec6-zad3.py delete mode 100644 Practice/IvanovA/lec6-zad4.py delete mode 100644 Practice/IvanovA/lec7-zad-1.py delete mode 100644 Practice/IvanovA/lec7-zad2.py delete mode 100644 Practice/Karpov_A/Lec_6/t6_3.py delete mode 100644 Practice/Karpov_A/Lec_6/t6_4.py delete mode 100644 Practice/Karpov_A/pep8.py delete mode 100644 Practice/Karpov_A/t2_1.py delete mode 100644 Practice/Karpov_A/t2_2.py delete mode 100644 Practice/Karpov_A/t2_3.py delete mode 100644 Practice/Karpov_A/t4_1.py delete mode 100644 Practice/Karpov_A/t4_2.py delete mode 100644 Practice/Karpov_A/t4_3.py delete mode 100644 Practice/Karpov_A/t4_4.py delete mode 100644 Practice/Karpov_A/t4_5.py delete mode 100644 Practice/Karpov_A/t5_1.py delete mode 100644 Practice/Karpov_A/t5_2.py delete mode 100644 Practice/Karpov_A/t5_3.py delete mode 100644 Practice/Karpov_A/t6_3.py delete mode 100644 Practice/Karpov_A/t6_4.py delete mode 100644 Practice/Postnikova/practice_10_task_1_client.py delete mode 100644 Practice/Postnikova/practice_10_task_1_server.py delete mode 100644 Practice/Postnikova/practice_10_task_2_client.py delete mode 100644 Practice/Postnikova/practice_10_task_2_server.py delete mode 100644 Practice/Postnikova/practice_10_task_3.py delete mode 100644 Practice/Postnikova/practice_9_task_1.py delete mode 100644 Practice/Postnikova/practice_9_task_2.py delete mode 100644 Practice/Postnikova/practice_9_task_3.py delete mode 100644 Practice/Postnikova/user.py delete mode 100644 Practice/README.md delete mode 100644 Practice/SNazarov/Control task/destination.txt delete mode 100644 Practice/SNazarov/Control task/sourse.txt delete mode 100644 Practice/SNazarov/__pycache__/task_5_1.cpython-38.pyc delete mode 100644 Practice/SNazarov/myfile.txt delete mode 100644 Practice/SNazarov/pep8.py delete mode 100644 Practice/SNazarov/task 4.1.py delete mode 100644 Practice/SNazarov/task 4.2.py delete mode 100644 Practice/SNazarov/task 4.3.py delete mode 100644 Practice/SNazarov/task 4.4.py delete mode 100644 Practice/SNazarov/task 4.5.py delete mode 100644 Practice/SNazarov/task 4.6.py delete mode 100644 Practice/SNazarov/task 5.2.py delete mode 100644 Practice/SNazarov/task 5.3.py delete mode 100644 Practice/SNazarov/task2.1.py delete mode 100644 Practice/SNazarov/task2.2.py delete mode 100644 Practice/SNazarov/task2.3.py delete mode 100644 Practice/SNazarov/task_5_1.py delete mode 100644 Practice/SNazarov/task_6_3.py delete mode 100644 Practice/SNazarov/task_6_4.py delete mode 100644 Practice/SNazarov/task_7_1.py delete mode 100644 Practice/SNazarov/task_7_2.py delete mode 100644 Practice/SNazarov/task_7_3.py delete mode 100644 Practice/Salakhetdinova/lab2.py delete mode 100644 Practice/Salakhetdinova/lab2_2.py delete mode 100644 Practice/Salakhetdinova/lab4_1.py delete mode 100644 Practice/Salakhetdinova/lab4_2.py delete mode 100644 Practice/Salakhetdinova/lab4_3.py delete mode 100644 Practice/Salakhetdinova/lab4_4.py delete mode 100644 Practice/Salakhetdinova/lab4_5.py delete mode 100644 Practice/Salakhetdinova/lab5_1.py delete mode 100644 Practice/Salakhetdinova/lab5_2.py delete mode 100644 Practice/Sam_Kilyaev/Lection_2_Task_1.py delete mode 100644 Practice/Sam_Kilyaev/Lection_2_Task_2.py delete mode 100644 Practice/Sam_Kilyaev/Lection_2_Task_3.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_1.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_2.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_3.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_4.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_5.py delete mode 100644 Practice/Sam_Kilyaev/Lection_4_Task_6.py delete mode 100644 Practice/Sam_Kilyaev/Lection_5_Task_1.py delete mode 100644 Practice/Sam_Kilyaev/Lection_5_Task_2.py delete mode 100644 Practice/Sam_Kilyaev/Lection_5_Task_3.py delete mode 100644 Practice/Sam_Kilyaev/Lection_6_Task_3.py delete mode 100644 Practice/Sam_Kilyaev/Lection_6_Task_4.py delete mode 100644 Practice/Sam_Kilyaev/Lection_7_Razminka.py delete mode 100644 Practice/Sam_Kilyaev/Lection_7_Task_1.py delete mode 100644 Practice/Sam_Kilyaev/Lection_7_Task_2.py delete mode 100644 Practice/Sam_Kilyaev/pep8task.py delete mode 100644 Practice/ViktorGa/L2T1.py delete mode 100644 Practice/ViktorGa/L2T2.py delete mode 100644 Practice/ViktorGa/L4T1.py delete mode 100644 Practice/ViktorGa/L4T2.py delete mode 100644 Practice/ViktorGa/L4T3.py delete mode 100644 Practice/ViktorGa/L4T4.py delete mode 100644 Practice/ViktorGa/L4T5.py delete mode 100644 Practice/ViktorGa/L5T1.py delete mode 100644 Practice/ViktorGa/L5T2.py delete mode 100644 Practice/ViktorGa/L6T3.py delete mode 100644 Practice/ViktorGa/L6T4.py delete mode 100644 Practice/ViktorGa/L7T1.py delete mode 100644 Practice/ViktorGa/L7T2.py delete mode 100644 Practice/ViktorGa/L7T3.py delete mode 100644 Practice/ViktorGaL9/L9T1.py delete mode 100644 Practice/ViktorGaL9/L9T2.py delete mode 100644 "Practice/amuratshin/lec3_practice/\321\201hoose.py" delete mode 100644 "Practice/amuratshin/lec3_practice/\321\201ompare.py" delete mode 100644 Practice/amuratshin/lec4_practice/FizzBuzz.py delete mode 100644 Practice/amuratshin/lec4_practice/dict.py delete mode 100644 Practice/amuratshin/pep8task.py delete mode 100644 Practice/aulov_r/10lec1_client.py delete mode 100644 Practice/aulov_r/10lec1_server.py delete mode 100644 Practice/aulov_r/2lec1.py delete mode 100644 Practice/aulov_r/2lec2.py delete mode 100644 Practice/aulov_r/4lec1.py delete mode 100644 Practice/aulov_r/4lec2.py delete mode 100644 Practice/aulov_r/4lec3.py delete mode 100644 Practice/aulov_r/4lec4.py delete mode 100644 Practice/aulov_r/4lec5.py delete mode 100644 Practice/aulov_r/5lec1.py delete mode 100644 Practice/aulov_r/5lec2.py delete mode 100644 Practice/aulov_r/5lec3.py delete mode 100644 Practice/aulov_r/6lec3.py delete mode 100644 Practice/aulov_r/6lec4.py delete mode 100644 Practice/aulov_r/7lec1.py delete mode 100644 Practice/aulov_r/7lec2.py delete mode 100644 Practice/aulov_r/8lec3.py delete mode 100644 Practice/aulov_r/8lec5.py delete mode 100644 Practice/aulov_r/9lec1.py delete mode 100644 Practice/aulov_r/pep8.py delete mode 100644 Practice/ekaryagin/lab2.py delete mode 100644 Practice/ekaryagin/lab4.py delete mode 100644 Practice/ekaryagin/lab5.py delete mode 100644 Practice/ekaryagin/pep8task_.py delete mode 100644 Practice/o_komissarova/for_lec10/task1/Client.py delete mode 100644 Practice/o_komissarova/for_lec10/task1/Server.py delete mode 100644 Practice/o_komissarova/for_lec10/task2/Client.py delete mode 100644 Practice/o_komissarova/for_lec10/task2/Server.py delete mode 100644 Practice/o_komissarova/for_lec10/task3.py delete mode 100644 Practice/o_komissarova/for_lec11/task1.py delete mode 100644 Practice/o_komissarova/for_lec11/task2.py delete mode 100644 Practice/o_komissarova/for_lec2/biggest_number.py delete mode 100644 Practice/o_komissarova/for_lec2/game.py delete mode 100644 Practice/o_komissarova/for_lec4/fizz_buzz.py delete mode 100644 Practice/o_komissarova/for_lec4/interpolate.py delete mode 100644 Practice/o_komissarova/for_lec4/matrix.py delete mode 100644 Practice/o_komissarova/for_lec4/number_reader.py delete mode 100644 Practice/o_komissarova/for_lec4/replace.py delete mode 100644 Practice/o_komissarova/for_lec4/sort.py delete mode 100644 Practice/o_komissarova/for_lec5/man_pupil.py delete mode 100644 Practice/o_komissarova/for_lec5/wrap_str_to_file.py delete mode 100644 Practice/o_komissarova/for_lec6/cont_manager.py delete mode 100644 Practice/o_komissarova/for_lec6/itertools_task.py delete mode 100644 Practice/o_komissarova/for_lec7/dir_follower.py delete mode 100644 Practice/o_komissarova/for_lec7/human.data delete mode 100644 Practice/o_komissarova/for_lec7/human.py delete mode 100644 Practice/o_komissarova/for_lec7/subprocess_cat.py delete mode 100644 Practice/o_komissarova/for_lec7/text.txt delete mode 100644 Practice/o_komissarova/for_lec7/warm_up_find_git.py delete mode 100644 Practice/o_komissarova/for_lec7/warm_up_gen.py delete mode 100644 Practice/o_komissarova/for_lec7/warm_up_iter.py delete mode 100644 Practice/o_komissarova/for_lec7/warm_up_transpose.py delete mode 100644 Practice/o_komissarova/for_lec7/workdays_counter.py delete mode 100644 Practice/o_komissarova/for_lec8/bonus.py delete mode 100644 Practice/o_komissarova/for_lec8/source.txt delete mode 100644 Practice/o_komissarova/for_lec8/task1.py delete mode 100644 Practice/o_komissarova/for_lec8/task10.py delete mode 100644 Practice/o_komissarova/for_lec8/task2.py delete mode 100644 Practice/o_komissarova/for_lec8/task3.py delete mode 100644 Practice/o_komissarova/for_lec8/task4.py delete mode 100644 Practice/o_komissarova/for_lec8/task5.py delete mode 100644 Practice/o_komissarova/for_lec8/task6.py delete mode 100644 Practice/o_komissarova/for_lec8/task7.py delete mode 100644 Practice/o_komissarova/for_lec8/task8.py delete mode 100644 Practice/o_komissarova/for_lec8/task9.py delete mode 100644 Practice/o_komissarova/for_lec9/task1.py delete mode 100644 Practice/o_komissarova/for_lec9/task2.py delete mode 100644 Practice/o_komissarova/for_lec9/task3.py delete mode 100644 Practice/o_komissarova/pep8task.py delete mode 100644 Practice/shashalina/lec 4 task3.py delete mode 100644 Practice/shashalina/lec4 task1.py delete mode 100644 Practice/shashalina/lec4 task2.py delete mode 100644 Practice/shashalina/pep8task.py delete mode 100644 Practice/solkin/test1.py diff --git a/Practice/E_Shipunova/10.1Client.py b/Practice/E_Shipunova/10.1Client.py deleted file mode 100644 index 5cdb829c..00000000 --- a/Practice/E_Shipunova/10.1Client.py +++ /dev/null @@ -1,11 +0,0 @@ -import socket - -host = '127.0.0.1' -port = 12345 - -client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -client.connect((host, port)) -client.send('.$*P$q:*-)%,$!#:$!:>!'.encode()) # for testing incorrect shifr: '.$*PB$q:*-$!:>!'.encode() -print(f'I got "{client.recv(1024).decode()}" from server.') - -client.close() diff --git a/Practice/E_Shipunova/10.1Server.py b/Practice/E_Shipunova/10.1Server.py deleted file mode 100644 index db9c5559..00000000 --- a/Practice/E_Shipunova/10.1Server.py +++ /dev/null @@ -1,42 +0,0 @@ -import socket - -server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # internet, TCP -host = '127.0.0.1' # locale host -port = 12345 -secret = { - 'I': '.', - 'a': '*', - 'm': 'P', - ' ': '$', - 'r': 'q', - 'e': ':', - 'd': '-', - 'i': ')', - 'n': '%', - 'h': '#', - 'g': ',', - 't': '!', - 'x': '>' - } - -server.bind((host, port)) -server.listen(5) - -while True: - conn, addr = server.accept() - shifr = conn.recv(1024).decode() # get shifr from client - print(f'I got "{"".join(shifr)}" from client {addr}.') - - res = [] - inv_secret = {v: k for k, v in secret.items()} # dictionary is invented - for ch in shifr: - try: - res.append(inv_secret[ch]) - except KeyError: - print("It's an incorrect shifr!!!") - conn.send("It's an incorrect shifr!!! I don't know what is this".encode()) - - conn.send((''.join(res)).encode()) - print("The code decrypted successfully.") - conn.close() -server.close() diff --git a/Practice/E_Shipunova/10.2Client.py b/Practice/E_Shipunova/10.2Client.py deleted file mode 100644 index 125645e8..00000000 --- a/Practice/E_Shipunova/10.2Client.py +++ /dev/null @@ -1,26 +0,0 @@ -import socket -import pickle -import random -import time -import user - -class TcpClient: - def __init__(self, host, port): - self.host = host - self.port = port - self._socket = None - - def run(self): - names = ["Noah", "Mason", "Liam", "Alex", "Jack", "Harry", "Oscar", "Jacob"] - position = ["baker", "poet", "butcher", "cook", "doctor", "engineer", "farmer", "pilot"] - - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect((self.host, self.port)) - time.sleep(5) - self._socket.send(pickle.dumps(user.User(random.choice(names), random.randint(0, 99), random.choice(position)))) - self._socket.close() - - -if __name__ == "__main__": - my_client = TcpClient(host = '127.0.0.1', port=5555) - my_client.run() diff --git a/Practice/E_Shipunova/10.2Server.py b/Practice/E_Shipunova/10.2Server.py deleted file mode 100644 index 88f3dade..00000000 --- a/Practice/E_Shipunova/10.2Server.py +++ /dev/null @@ -1,47 +0,0 @@ -import socket -import pickle -import threading -import user - - -class ClientThread(threading.Thread): - - def __init__(self, conn, addr): - super().__init__() - self._connection = conn - self._address = addr - - def run(self): - print(f'Server got connection from client {self._address}. \n {pickle.loads(self._connection.recv(1024))}') - self._connection.close() - - -class TcpServer: - def __init__(self, host, port): - self.host = host - self.port = port - self._socket = None - self._running = False - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self._socket.bind((self.host, self.port)) - self._socket.listen(5) - self._running = True - - while self._running: - conn, addr = self._socket.accept() - ClientThread(conn, addr).start() - - def stop(self): - self._running = False - self._socket.close() - - -if __name__ == "__main__": - srv = TcpServer(host='127.0.0.1', port=5555) - try: - srv.run() - except KeyboardInterrupt: - srv.stop() diff --git a/Practice/E_Shipunova/10.3.py b/Practice/E_Shipunova/10.3.py deleted file mode 100644 index 5628e206..00000000 --- a/Practice/E_Shipunova/10.3.py +++ /dev/null @@ -1,24 +0,0 @@ -from urllib import request -import re - - -def collect_working_links(url): - list_of_links = [] - req = request.Request(url) - response = request.urlopen(req) - web_page = response.read() - search_res = re.findall(r'href="(http(s?)://.*?)"', str(web_page)) - - for each in search_res: - req_of_each = request.Request(each[0]) - response_of_each = request.urlopen(req_of_each) - code_of_link = response_of_each.getcode() - - if code_of_link == 200: # if our link is working - list_of_links.append(each[0]) - - return list_of_links - - -if __name__ == '__main__': - print(collect_working_links('http://google.com')) diff --git a/Practice/E_Shipunova/2.1.py b/Practice/E_Shipunova/2.1.py deleted file mode 100644 index 7f90fc7c..00000000 --- a/Practice/E_Shipunova/2.1.py +++ /dev/null @@ -1,6 +0,0 @@ -def print_max(a, b): - print(a) if a > b else print(b) # or classic version: - #if a > b: - # print(f"Max number={a}") -print_max(77, 99) #else: - # print(f"Max number={b}") diff --git a/Practice/E_Shipunova/2.2.py b/Practice/E_Shipunova/2.2.py deleted file mode 100644 index 87f3c906..00000000 --- a/Practice/E_Shipunova/2.2.py +++ /dev/null @@ -1,5 +0,0 @@ -def return_max(a, b): - return a if a > b else b - - -print(return_max(55, 77)) diff --git a/Practice/E_Shipunova/2.3.py b/Practice/E_Shipunova/2.3.py deleted file mode 100644 index 9a1093c2..00000000 --- a/Practice/E_Shipunova/2.3.py +++ /dev/null @@ -1,95 +0,0 @@ -class Character: - speed = 40 # km/h standard - shots = 5 # standard - collection = [] # list with items - # in this classes item=fast_item.value == 2 or item=slowly_item.value == 0.5(look at the class Item) - # for all methods standard version if item==1, else we used item = collection[index] (value 2 or 0.5) - # when using the item must pass in methods fast_item.value or slowly_item.value - - def __init__(self): - print("I was born.") - print(f"My standard speed = {self.speed} km/h") - print(f"My standard shots = {self.shots}") - print("My collection is empty") - - def run(self, item=1): - speed_run = self.speed*item # for fast or slowly speed - print(f"I'm running, my speed = {speed_run} km/h!") - if item != 1: - self.collection.remove(item) # we used this item - - def shoot(self, item=1): - shots_shoot = self.shots*item # for increase or decrease number of shots - print("I shoot ", int(shots_shoot), "time!") # int( may be float) - if item != 1: - self.collection.remove(item) # we used this item - - def collect(self, item): - print("I took the new item!") - self.collection.append(item) # add item - print("My collection is ", self.collection) - - -class Person(Character): - - def __init__(self): - super() - print("I am Person") - - -class Dracula(Character): - - def __init__(self): - super() - self.speed *= 7 - self.shots *= 3 - self.speed_fly = self.speed*10 - self.blood = 4.5 # liters standard - print(f"I'm flying, my standard speed = {self.speed} km/h of fly") - print(f"Usually I drink = {self.blood} liters' blood") - print("I am Dracula") - - def fly(self, item=1): - self.speed_fly *= item # for fast or slowly speed - print(f"I'm flying, my speed = {self.speed_fly} km/h!") - if item != 1: - self.collection.remove(item) # we used this item - - def drink_blood(self, item=1): - liter_blood = self.blood*item - print(f"I'm drink {liter_blood} liters!") - if item != 1: - self.collection.remove(item) # we used this item - - -class Ichthyander(Character): - - def __init__(self): - super() - self.speed *= 5 - self.shots *= 2 - self.speed_swim=self.speed*3 - print(f"I'm swimming, my standard speed = {self.speed_swim} km/h!") - print("I am Ichthyander") - - def swim(self, item=1): - self.speed_swim *= item # for fast or slowly speed - print(f"I'm swimming, my speed = {self.speed_swim} km/h!") - if item != 1: - self.collection.remove(item) # we used this item - - - -class Item: - value = 1 - - -class FastItem(Item): # fast_item=FastItem() and fast_item.value==2 - def __init__(self): - self.value = 2 - - -class SlowlyItem(Item): # slowly_item=SlowlyItem() and slowly_item.value==0.5 - def __init__(self): - self.value = 0.5 - diff --git a/Practice/E_Shipunova/4.1.py b/Practice/E_Shipunova/4.1.py deleted file mode 100644 index ec6a44f1..00000000 --- a/Practice/E_Shipunova/4.1.py +++ /dev/null @@ -1,13 +0,0 @@ -def fizz_buzz(): - for i in range(1, 101): # for 1-100 - if i % 15 == 0: # the first condition, else have to be: 'if i % 3 == 0 and i % 15 != 0: ...' - print("FizzBuzz") - elif i % 3 == 0: - print("Fizz") - elif i % 5 == 0: - print("Buzz") - else: - print(i) - - -fizz_buzz() diff --git a/Practice/E_Shipunova/4.2.py b/Practice/E_Shipunova/4.2.py deleted file mode 100644 index ae262c1a..00000000 --- a/Practice/E_Shipunova/4.2.py +++ /dev/null @@ -1,24 +0,0 @@ -def every_digit(x: int): - for i in str(x): - print(f"{str(x).index(i)+1} digit is {i}") - - -def v2_every_digit(x: int): - step = 1 # static var - - def rec_get_num(num): - nonlocal step - if num//10 == 0: - return print(f"{step} is digit = {num}") # print the first - - rec_get_num(num//10) - step += 1 - return print(f"{step} is digit = {num % 10}") - - rec_get_num(x) - - -if __name__ == "__main__": - every_digit(76543) - v2_every_digit(12345) - v2_every_digit(7777777) diff --git a/Practice/E_Shipunova/4.3.py b/Practice/E_Shipunova/4.3.py deleted file mode 100644 index 02d5f5eb..00000000 --- a/Practice/E_Shipunova/4.3.py +++ /dev/null @@ -1,21 +0,0 @@ -def selection_sort(*args): - array = list(args) - - for i in array: - min_num = i - index = -1 - index_min = 0 - - for j in array: # for every i - index += 1 - if j < min_num and index > array.index(i): - min_num = j - index_min = index - - if min_num != i: - array[array.index(i)], array[index_min] = min_num, i - - print(array) - - -selection_sort(5, 3, 6, 9, 3, 44, -9) # for testing diff --git a/Practice/E_Shipunova/4.4.py b/Practice/E_Shipunova/4.4.py deleted file mode 100644 index fdb70b8b..00000000 --- a/Practice/E_Shipunova/4.4.py +++ /dev/null @@ -1,70 +0,0 @@ -def v1_tab_or_spaces(line, tab_to_spaces=True): - str_ = list(line) - new_arr = [] - - if tab_to_spaces is True: # for '\t'=4spaces - for char in str_: - if char == '\t': - new_arr.append(" ") - else: - new_arr.append(char) - - print("".join(new_arr)) # or return new_line - - else: # if tab_to_spaces==False for 4spaces='\t' - count_spaces = 0 - flag = 0 # flag==1 - into word - for char in str_: - if char == ' ': - flag = 0 - count_spaces += 1 - if count_spaces == 4: - new_arr.append("\t") - count_spaces = 0 - - else: - if count_spaces != 0: - new_arr.append(' ' * count_spaces) # if 1, 2 or 3 spaces - new_arr.append(char) - flag = 1 - count_spaces = 0 - - else: - new_arr.append(char) - flag = 1 - count_spaces = 0 - - - print("".join(new_arr)) # or return new_line - - -def v2_tab_or_spaces(line, tab_to_spaces=True): - if tab_to_spaces is True: # for '\t'=4spaces - new_arr = line.split('\t') - new_line = ' '.join(new_arr) - print(new_line) # or return - - else: # for 4spaces='\t' - new_arr = line.split(' ') - new_line = '\t'.join(new_arr) - print(new_line) # or return - - -def v3_tab_or_spaces(line, tab_to_spaces=True): - if tab_to_spaces is True: # for '\t'=4spaces - # return line.expandtabs(tabsize=4) - it's the first idea, - # but correctly only the first replacement and... v1 and v2 were made - return line.replace("\t", " ") - - return line.replace(" ", "\t") # for 4spaces='\t' - - -line_tab = "\tOne\tTwo...Three\tFour\t...Five" -v1_tab_or_spaces(line_tab) -v2_tab_or_spaces(line_tab) -print(v3_tab_or_spaces(line_tab)) - -line_with_spaces = " Five Four Three Two One " -v1_tab_or_spaces(line_with_spaces, tab_to_spaces=False) -v2_tab_or_spaces(line_with_spaces, tab_to_spaces=False) -print(v3_tab_or_spaces(line_with_spaces, tab_to_spaces=False)) diff --git a/Practice/E_Shipunova/4.5.py b/Practice/E_Shipunova/4.5.py deleted file mode 100644 index 65cf5097..00000000 --- a/Practice/E_Shipunova/4.5.py +++ /dev/null @@ -1,16 +0,0 @@ -def always_best_review(review): - dict_review = {"долго": "быстро", - "редиска": "замечательный человек", - "низкого качества": "наилучшего качества", - "не ": ""} - - for key, value in dict_review.items(): - review = review.replace(key, value) - - print("Good review is done:") - print(review) - - -bad_review = "Заказ шёл долго. Товар низкого качества не порадовал. Продавец - редиска. Заказывать больше не буду!" -print(bad_review) -always_best_review(bad_review) diff --git a/Practice/E_Shipunova/4.6.py b/Practice/E_Shipunova/4.6.py deleted file mode 100644 index 6969af5d..00000000 --- a/Practice/E_Shipunova/4.6.py +++ /dev/null @@ -1,49 +0,0 @@ -def delete_column(list_of_lists, num_for_delete): - print(list_of_lists) - index = None # for search index of num_for_delete - - for i in list_of_lists: # 1. search index - for j in i: - if j == num_for_delete: - index = i.index(j) - print(index) # take the first index with num_for_delete - break - if index != None: # for exit from - break - - for i in list_of_lists: # 2. delete i[index] - del i[index] - - print(list_of_lists) - - -def v2_delete_column(list_of_lists, num_for_delete): - if len(list_of_lists) == 0: - return None - - columns_for_del = [] # for indexes' columns for delete - count = 0 # for editing an index - - for j in range(len(list_of_lists[0])): # 1. search index for delete - for i in range(len(list_of_lists)): - if list_of_lists[i][j] == num_for_delete: - columns_for_del.append(j) - break - - for index in columns_for_del: # 2. delete i[index] - index -= count - for i in list_of_lists: - del i[index] - count += 1 - - return list_of_lists - - -arr = [[1, 2, 3, 4, 5], - [2, 2, 7, 4, 5], - [1, 2, 3, 7, 5], - [1, 2, 3, 4, 5], - [1, 2, 3, 4, 5] - ] -delete_column(arr, 7) -print(v2_delete_column(arr, 7)) diff --git a/Practice/E_Shipunova/5.1.py b/Practice/E_Shipunova/5.1.py deleted file mode 100644 index 11336a85..00000000 --- a/Practice/E_Shipunova/5.1.py +++ /dev/null @@ -1,14 +0,0 @@ -class Man: - - def __init__(self, name_of_man): - self.name = name_of_man - - @staticmethod # because we don't use attributes of the class - def solve_talk(): - print("I'm not ready yet") - - -if __name__ == "__main__": - man = Man("Isaak") - print(f"{man.name}:", end=" ") - man.solve_talk() diff --git a/Practice/E_Shipunova/5.2.py b/Practice/E_Shipunova/5.2.py deleted file mode 100644 index 552996bf..00000000 --- a/Practice/E_Shipunova/5.2.py +++ /dev/null @@ -1,30 +0,0 @@ -import random -import time - - -class Man: - - def __init__(self, name_of_man): - self.name = name_of_man - - @staticmethod # because we don't use attributes of the class - def solve_talk(): - print("I'm not ready yet") - - -class Pupil(Man): - - def __init__(self, name_of_pupil): - super().__init__(name_of_pupil) - - @staticmethod - def solve_talk(): - print("I think...") - time.sleep(random.randint(3, 6)) - print("I'm not ready yet") - - -if __name__ == "__main__": - pupil = Pupil("Pupil") - print(f"{pupil.name}:", end=" ") - pupil.solve_talk() diff --git a/Practice/E_Shipunova/5.3.py b/Practice/E_Shipunova/5.3.py deleted file mode 100644 index 26df9db8..00000000 --- a/Practice/E_Shipunova/5.3.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -import tempfile - - -class WrapStrToFile: - - def __init__(self): - self.file_path = tempfile.mktemp() - - @property # get file_content - def content(self): - try: - f = open(self.file_path, 'r') - except FileNotFoundError: - return "File doesn't exist" - else: - file_content = f.read() # if the file is open - f.close() # I don't write 'finally', because - # if the file is closed, we can not close it - return file_content - - @content.setter # set file_content - def content(self, value): - f = open(self.file_path, 'w') - f.write(value) - f.close() - - @content.deleter - def content(self): - os.remove(self.file_path) - - -if __name__ == "__main__": - wstf = WrapStrToFile() - print(f"File_path is '{wstf.file_path}'") - print(wstf.content) - wstf.content = "test str" - print(wstf.content) - wstf.content = "test2" - print(wstf.content) - del wstf.content diff --git a/Practice/E_Shipunova/6.3.py b/Practice/E_Shipunova/6.3.py deleted file mode 100644 index 36178c52..00000000 --- a/Practice/E_Shipunova/6.3.py +++ /dev/null @@ -1,16 +0,0 @@ -import time - - -class TimeManager: - def __enter__(self): - self._t = time.clock() # for process time - print(self._t) - print("Code start!") - - def __exit__(self, exc_type, exc_val, exc_tb): - print(f"Code execution took {time.clock()-self._t} sec") - - -if __name__ == "__main__": - with TimeManager(): - [x for x in range(10000000)] diff --git a/Practice/E_Shipunova/6.4.py b/Practice/E_Shipunova/6.4.py deleted file mode 100644 index 68a8d74a..00000000 --- a/Practice/E_Shipunova/6.4.py +++ /dev/null @@ -1,33 +0,0 @@ -from itertools import chain -from itertools import filterfalse -from itertools import combinations - - -def itertools_usage(num: int, *args): - count = 0 # for check count of arrays - - for arg in args: - if type(arg) is list: # check type of arrays for choice of itertools methode - count += 1 - - if count == num: # count of lists == num => use chain() - return list(chain(*args)) - - elif type(num) is int and len(args) == 1 and type(args[0]) is list: # => use filterfalse() - return list(filterfalse(lambda x: len(x) < num, args[0])) - - elif type(num) is int and len(args) == 1 and type(args[0]) is str: # => use combinations() - return list(combinations(args[0], num)) - - return "Incorrect data!" - - -if __name__ == "__main__": - print(itertools_usage(3, [5, 4], [3], [2, 1, 0])) - print(itertools_usage(5, ["hello", "i", "write", "cook", "code", "embankment"])) - print(itertools_usage(4, "password")) - print(itertools_usage(4, 7, "incorrect data")) - try: - itertools_usage() - except TypeError as ex: - print(f"ERROR: {ex}") diff --git a/Practice/E_Shipunova/7.1.py b/Practice/E_Shipunova/7.1.py deleted file mode 100644 index 932f4491..00000000 --- a/Practice/E_Shipunova/7.1.py +++ /dev/null @@ -1,23 +0,0 @@ -import datetime - - -def working_days(first_data, second_data): - delta = second_data - first_data # - object timedelta - first_day = first_data.strftime("%A") # - day of week - - if first_day == "Saturday": - return (delta.days+1) - (delta.days+1)//7*2 - 2 # for start at Saturday ' - 2 day' - elif first_day == "Sunday": - return (delta.days + 1) - (delta.days + 1) // 7 * 2 - 1 # for start at Sunday ' - 1 day' - - return (delta.days+1) - (delta.days+1)//7*2 - - -if __name__ == "__main__": - print(working_days(datetime.datetime(2020, 8, 24), datetime.datetime(2020, 8, 30))) - print(working_days(datetime.datetime(2020, 8, 31), datetime.datetime(2020, 9, 13))) - print(working_days(datetime.datetime(2020, 9, 12), datetime.datetime(2020, 9, 16))) - print(working_days(datetime.datetime(2020, 9, 13), datetime.datetime(2020, 9, 16))) - print(working_days(datetime.datetime(2020, 9, 21), datetime.datetime(2020, 9, 23))) - print(f"We have {working_days(datetime.datetime.now(), datetime.datetime(2020, 12, 31))} working days in 2020") - diff --git a/Practice/E_Shipunova/7.2.py b/Practice/E_Shipunova/7.2.py deleted file mode 100644 index 09d27e6f..00000000 --- a/Practice/E_Shipunova/7.2.py +++ /dev/null @@ -1,15 +0,0 @@ -import subprocess - - -def cat_file(file_name): - process = subprocess.Popen(["type", file_name], shell=True) - process.wait() - result = process.communicate() - - if process.returncode: - for line in result: - print(line) - - -if __name__ == "__main__": - cat_file("test.txt") # this file into the dir, for other file has to be full path diff --git a/Practice/E_Shipunova/7.3dump.py b/Practice/E_Shipunova/7.3dump.py deleted file mode 100644 index dc4270e6..00000000 --- a/Practice/E_Shipunova/7.3dump.py +++ /dev/null @@ -1,26 +0,0 @@ -import pickle -from random import randint as rand -from random import choice -from libHuman import Human - - -def create_human(number): - humans = [] - first_name = ["Noah", "Mason", "Liam", "Alex", "Jack", "Harry", "Oscar", "Jacob"] - last_name = ["Austin", "Birch", "Carey", "Day", "Dean", "Simon", "Gate", "Taft"] - position = ["baker", "poet", "butcher", "cook", "doctor", "engineer", "farmer", "pilot"] - - for i in range(number): - humans.append(Human(choice(first_name), choice(last_name), rand(17, 41), choice(position), made_phone())) - - with open("human.data", "wb") as f: - pickle.dump(humans, f) - - -def made_phone(): # for random phone - phone = [rand(0, 10), rand(0, 10), rand(0, 10), "-", rand(0, 10), rand(0, 10), "-", rand(0, 10), rand(0, 10), rand(0, 10)] - return "".join([str(x) for x in phone]) - - -if __name__ == "__main__": - create_human(3) diff --git a/Practice/E_Shipunova/7.3load.py b/Practice/E_Shipunova/7.3load.py deleted file mode 100644 index 606bf03a..00000000 --- a/Practice/E_Shipunova/7.3load.py +++ /dev/null @@ -1,17 +0,0 @@ -import pickle -from libHuman import Human - - -def print_human(): - i = 0 - with open("human.data", "rb") as f: - humans = pickle.load(f) - for human in humans: - i += 1 - print(f"{i} human is: ") - print(human.first_name, human.last_name) - print(f"He is {human.age} years old. He is a {human.position}. Phone: {human.phone}\n") - - -if __name__ == "__main__": - print_human() diff --git a/Practice/E_Shipunova/7.4.py b/Practice/E_Shipunova/7.4.py deleted file mode 100644 index 93bb7fc6..00000000 --- a/Practice/E_Shipunova/7.4.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -import datetime -from pathlib import Path - - -def del_all(path_to_dir): - ''' - The function creates infinity('while: True') tracking for maximally introduced dir, - while the dir has files and dirs, and deletes dir only it is empty. After the function - goes to less nested level. - For testing were created: dir test(f1.txt and dir p1(f2.txt, dir p2(empty), dir p3(f131.txt, f132.txt)). - :argument is path_to_dir - :return is None - ''' - static_main_dir = path_to_dir # for remember name of our main dir - print(static_main_dir) - - def del_in_dir(path_to_dir): - while True: - for i in os.listdir(path_to_dir): - path_of_item = os.path.join(path_to_dir, i) # for reading - if os.path.isfile(path_of_item): - print(f" ' {i} ' is file") # for testing - time_of_create = datetime.datetime.fromtimestamp(os.path.getctime(path_of_item)) - min_of_live = (datetime.datetime.now() - time_of_create).seconds // 60 # [min] - if min_of_live >= 1: # >= 1 [min] - print(f"delete file {i}") # for testing - os.remove(path_of_item) # delete file - else: # for testing - print(f"{i} is young") - - else: - print(f"' {i} ' is dir") # for testing - #is_empty = not bool(sorted(Path(path_of_item).rglob('*'))) - #if not is_empty: # only if the dir isn't empty - print(f"======> go to into {path_of_item}") # for testing - del_in_dir(path_of_item) # go into this dir - - # after 'go to into dir' - time_of_create = datetime.datetime.fromtimestamp(os.path.getctime(path_of_item)) - min_of_live = (datetime.datetime.now() - time_of_create).seconds // 60 # [min] - if min_of_live >= 2: # >= 2 [min] - print(f"delete dir {i}") # for testing - try: - os.rmdir(os.path.join(path_to_dir, i)) # delete only empty dir, else it trows Exception - except OSError: - print(f"Dir({i}) is not empty! I can not delete it.") - else: # for testing - print(f"dir {i} is young") - - is_empty = not bool(sorted(Path(path_to_dir).rglob('*'))) - if is_empty and path_to_dir != static_main_dir: # if dir is empty and it isn't main dir - break - - del_in_dir(path_to_dir) - - -if __name__ == "__main__": - del_all('./test') diff --git a/Practice/E_Shipunova/9.1.py b/Practice/E_Shipunova/9.1.py deleted file mode 100644 index 352795ef..00000000 --- a/Practice/E_Shipunova/9.1.py +++ /dev/null @@ -1,93 +0,0 @@ -import time -import threading -from multiprocessing import Process - - -def find_primes(end, start=3): - res = [] - for num in range(start, end + 1): - for i in range(2, num): # don't take num, because all num % num == 0 - if num % i == 0: - break - - if i == num - 1: - res.append(num) - - return res - - -if __name__ == "__main__": - - # The first option - sequential execution of threads - start_seq = time.perf_counter() - find_primes(10000) - find_primes(20000, 10001) - find_primes(30000, 20001) - print(f'The sequential execution takes {round(time.perf_counter() - start_seq, 4)} sec by sequential threads.') - - # The second option - parallel execution of threads (1) - start2 = time.perf_counter() - our_args = [[10000], [20000, 10001], [30000, 20001]] - threads = [] - - for i in range(len(our_args)): - thr = threading.Thread(target=find_primes, args=(*our_args[i],)) - start_par = time.perf_counter() - thr.start() - threads.append(thr) - - for thr in threads: - thr.join() - print(f'The parallel execution takes {round(time.perf_counter() - start2, 4)} sec by parallel threads.') - - # The third option - parallel execution of processes (2) - start3 = time.perf_counter() - processes = [] - for i in range(len(our_args)): - p = Process(target=find_primes, args=(*our_args[i],)) - p.start() - processes.append(p) - - for p in processes: - p.join() - print(f'The parallel execution takes {round(time.perf_counter() - start3, 4)} sec by parallel processes.') - -''' -1. Рассмотрим запуск ф-ции в ||-ных потоках (1): - - если "забыть" .start(), а .join() оставить, - то созданные потоки не будут запущены на выполнение, а когда выполнение любого потока дойдет до - строки с .join() - то будет выброшено исключение "RuntimeError: cannot join thread before it is started", - что вполне логично, выполнение программы закончится аварийно; - - если "забыть" .join(), а .start() оставить, - то потоки будут созданы, запущены на выполнение параллельно с работой главного потока, который завершит - свое выполнение в нашем случае раньше, чем "отработают" запущенные потоки. Но это не приведет к "гибели" - дочерних потоков, они корректно "отработают" свои инструкции; - - если "забыть" .join() и .start(), то "отработает" только главный поток, параллельные потоки будут созданы, - но ни запуска, ни завершения выполнено не будет. - -2. Рассмотрим запуск ф-ции в ||-ных процессах (2): - - если "забыть" .start(), а .join() оставить, то созданные процессы не будут запущены на выполнение, а именно - им не будет присвоен атрибут 'wait', что также в строке с .join() приведет к исключению, но уже типа - "AttributeError: 'NoneType' object has no attribute 'wait'", что приведет к аварийному завершению программы; - - если "забыть" .join(), а .start() оставить, получим ситуацию полностью идентичную ситуации с потоками: - процессы будут созданы, запущены на выполнение параллельно с работой главного процесса, который завершит - свое выполнение раньше, чем "отработают" дочернии процессы. Но это не приведет к "гибели" дочерних процессов, - они корректно "отработают" свои инструкции; - - если "забыть" .join() и .start(), вновь полная аналогия с потоками: "отработает" только главный процесс, - параллельные процессы будут созданы, но ни запуска, ни завершения выполнено не будет. - -Выводы (сравнение результатов): - "The sequential execution takes 5.9971 sec by sequential threads. - The parallel execution takes 5.8631 sec by parallel threads. - The parallel execution takes 4.6644 sec by parallel processes." - - Как видно из output, времена выполнения 3-х запусков ф-ции find_primes() в последовательных и параллельных потоках - соизмеримы, и ожидаемого "выйгрыша" от запуска кода в параллельных потоках не получено, что обусловлено наличием - в python GIL - доступ к интерпритатору в единый момент времени имеет лишь 1 поток, что приводит к невозможности, - а соответственно и нецелесообразности использования ||-ных потоков (даже расточительного использования ресурсов за - счет создания для каждого потока своего стека). - - Выполнение 3-х запусков ф-ции find_primes() в параллельных процессах занимает наименьшее время, и соответственно - более предпочтительно для решения подобных задач. - -''' diff --git a/Practice/E_Shipunova/9.2.py b/Practice/E_Shipunova/9.2.py deleted file mode 100644 index 170f16de..00000000 --- a/Practice/E_Shipunova/9.2.py +++ /dev/null @@ -1,39 +0,0 @@ -import re -from multiprocessing import Process - - -def add_any_args(*args): - dic_type = {"int": 0, "str": "", "list": []} # for initialize res - - for i in range(len(args)-1): # check for all arg to match the same type - if type(args[i]) is not type(args[i+1]): - return "Incorrect data!" - - if (type(args[0]) is int) or (type(args[0]) is str) or (type(args[0]) is list): # type inference by the first arg - res = dic_type[re.search("'(\w{3,5})'>$", str(type(args[0]))).group(1)] # initialize res - - for i in range(len(args)): - res += args[i] - print(res) - return res - - return "Incorrect data!" - - -if __name__ == "__main__": - # for testing add_any_args() - #print(add_any_args(1, 2, 3, 4, 5)) - #print(add_any_args("1, ", "2, ", "3, ", "4, ", "5")) - #print(add_any_args([1, 2, 3], [4], [5, 6, 7])) - #print(add_any_args(1, "error")) - #print(add_any_args({"1": 1}, {"2": 2})) - - arguments = [[1, 2, 3, 4, 5], ["1, ", "2, ", "3, ", "4, ", "5"], [[1, 2, 3], [4], [5, 6, 7]]] - processes = [] - for i in range(3): - p = Process(target=add_any_args, args=(arguments[i])) - p.start() - processes.append(p) - - for p in processes: - p.join() diff --git a/Practice/E_Shipunova/9.3.py b/Practice/E_Shipunova/9.3.py deleted file mode 100644 index 6d34ff69..00000000 --- a/Practice/E_Shipunova/9.3.py +++ /dev/null @@ -1,52 +0,0 @@ -import threading - - -class myThread(threading.Thread): - - def __init__(self, data): - threading.Thread.__init__(self) - self.data = data - - def run(self): - only_my_data(self) # our target - - -def only_my_data(self): - print(f'I am {threading.current_thread().name}. I have this data: {self.data}') - - -if __name__ == "__main__": - big_data = [1, 2, "three", [4, 4], "five", 6, "seven"] - threads = [] - for i in range(len(big_data)): - thr = myThread(big_data[i]) - thr.start() # call run() - threads.append(thr) - - for thr in threads: - thr.join() - -# or -''' -import threading -import random - - -def only_my_data(data): - data.number = random.randint(1, 1000) - print(f'I am {threading.current_thread().name}. I have this data: {data.__dict__}') - - -if __name__ == '__main__': - threads = [] - local_data = threading.local() - - for i in range(7): - t = threading.Thread(target=only_my_data, args=(local_data,)) - t.start() - threads.append(t) - - for t in threads: - t.join() - -''' diff --git a/Practice/E_Shipunova/git.txt b/Practice/E_Shipunova/git.txt deleted file mode 100644 index 40ae11cb..00000000 --- a/Practice/E_Shipunova/git.txt +++ /dev/null @@ -1,27 +0,0 @@ -Рабочая папка для слушателей курса. Пожалуйста, создавайте свои подпапки, называя их по своей фамилии (на английском) -и сохраняйте в них результаты выполнения заданий. - -Для работы с репозиторием можно установить git и использовать следующий порядок действий: - -Регистрируетесь на guithub.com и подписываетесь на данный репозиторий нажимая кнопку Watch справа вверху. -На рабочем компьютере выполняете команду "git clone https://github.com/IlyaOrlov/PythonCourse.git", -чтоб скачать репозиторий через https, либо git clone git@github.com:IlyaOrlov/PythonCourse.git - для скачивания через ssh. -Первый вариант попроще и не требует дополнительных усилий. Второй вариант потребует от вас разобраться с настройкой ssh -(https://help.github.com/articles/connecting-to-github-with-ssh/). -По умолчанию вы будете находится на бранче master. Начиная работу над новым заданием, создайте свой бранч, с помощью -следующей команды: "git checkout -b my_branch", где my_branch - название вашего бранча (английскими буквами без пробелов), -которое вы ему придумаете. -Публикуете эту ветку в удаленном репозитории: git push --set-upstream origin my_branch -В папке Practice создаете подпапку (если еще не создали), называете ее по своей фамилии, и добавляете туда скрипт с -выполненным заданием (например, mytest.py), либо делаете всяческие изменения в своих скриптах. -Вносите файл под контроль git с помощью команды "git add" (например, git add mytest.py) -Коммитите изменения (чтобы git присвоил им номер версии): git commit -m "Любой разумный комментарий к сделанным изменениям" -Подтягиваете последние изменения из общего репозитория: git pull origin master -Публикуете свои изменения на своем бранче в удаленном репозитории на сервере: git push -Зайдя на страницу репозитория в гитхабе (https://github.com/IlyaOrlov/PythonCourse), в списке Branch выбираете свой бранч - и нажимаете New pull request, чтоб запросить внесение изменений с вашего бранча в master бранч. -Пункты 1-2 выполняются однократно. Пункты 3-4, 10 - при работе над каждым новым заданием. Пункты 5-9 при каждом изменении, - которое вы собираетесь публиковать. -Если вы предпочитаете командной строке работу с визуальным интерфейсом - можно скачать и установить приложение TortoiseGit -(https://tortoisegit.org/download/) и выполнить пункты 3-9 в нем. Также TortoiseGit - удобная штука для разрешения конфликтов, -которые могут возникнуть после шага 8. \ No newline at end of file diff --git a/Practice/E_Shipunova/libHuman.py b/Practice/E_Shipunova/libHuman.py deleted file mode 100644 index 88b2e18b..00000000 --- a/Practice/E_Shipunova/libHuman.py +++ /dev/null @@ -1,11 +0,0 @@ -class Human: - - def __init__(self, first_name, last_name, age, position, phone): - self.first_name = first_name - self.last_name = last_name - self.age = age - self.position = position - self.phone = phone - - def __iter__(self): - return iter(self) diff --git a/Practice/E_Shipunova/pep8.py b/Practice/E_Shipunova/pep8.py deleted file mode 100644 index 3217a59f..00000000 --- a/Practice/E_Shipunova/pep8.py +++ /dev/null @@ -1,74 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * # this is not the best import option, we don't know what exactly is being imported - # "from time import time" or "import time" and use with name's library - - -class shuffler: # have to be "class Shuffler" - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): # have to be "dir_name" - mp3s = [] - # line № 18-25 move right 4 spaces, because rename() has it - for root, directories, files in os.walk(dirname): # have to be "dir_name" - for file in files: - if file[-3:] == '.mp3': # have to be "if file[-4:]", because '.mp3'.len()=4 - mp3s.append([root, file]) # after this line add empty line - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' # have to be "hash_name" - self.map[hashname] = mp3 - os.rename(path + '/' + mp3), path + '/' + hashname)) # after this line add empty line and delete ')' ')' - - f = open(output, 'r') # may be 'a' for f.write() - f.write(str(self.map)) # we can not write , because 'r' - only reading. - - def restore(self, dirname, restore_path): # have to be "dir_name" - with open(filename, '+') as f: # have to be "file_name" - self.map = ast.literal_eval(f.read()) - mp3s = [] - # line № 35-41 move right 4 spaces, because restore() has it - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': # have to be "if file[-4:]", because '.mp3'.len()=4 - mp3s.append({root, file}) # after this line add empty line - for path, hashname in mp3s: - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) # delete ')' - os.remove(restore_path) - - def generateName(self, seed=time()): # have to be "generate_name" - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') # have to be "sub_command" - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') # have to be "dir_name" - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') # have to be "dir_name" - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - - -def main(): - args = parse_arguments() - Shuffler = shuffler() # have to be "shuffler=Shuffler()" and use the object - if args.subcommand == 'rename': - if args.output: - Shuffler.rename(args.dirname, 'restore.info') # use "shuffler.rename(args.dir_name, 'restore_info')" - else: - Shuffler.rename(args.dirname, args.output) # use "shuffler. ..." and add empty line after this line - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) # use "shuffler. ..." - else: - sys.exit() - - -main() # after this line add empty line \ No newline at end of file diff --git a/Practice/E_Shipunova/razminka(gen).py b/Practice/E_Shipunova/razminka(gen).py deleted file mode 100644 index 43ca177b..00000000 --- a/Practice/E_Shipunova/razminka(gen).py +++ /dev/null @@ -1,11 +0,0 @@ -def file_reader(file_name): - with open(file_name,"r") as f: - for line in f: - yield line - - -if __name__ == "__main__": - generator = file_reader("test.txt") - print(next(generator)) - print(next(generator)) - print(next(generator)) diff --git a/Practice/E_Shipunova/razminka(git).py b/Practice/E_Shipunova/razminka(git).py deleted file mode 100644 index ef498d57..00000000 --- a/Practice/E_Shipunova/razminka(git).py +++ /dev/null @@ -1,20 +0,0 @@ -import re - - -def get_git_commands(file_name): - with open(file_name, "r") as f: - commands = [] - for line in f: - commands += re.findall('(git [a-z]+[^а-яА-Я)\n"]+)', line) - - i = 0 - for command in commands: - correctly_line = re.search('(git .*git) ', command) # but, in the second line I get command with " -" - if correctly_line: - commands[i] = correctly_line.group() - print(commands[i]) - i += 1 - - -if __name__ == "__main__": - get_git_commands("git.txt") diff --git a/Practice/E_Shipunova/razminka(iter).py b/Practice/E_Shipunova/razminka(iter).py deleted file mode 100644 index fd55e0f2..00000000 --- a/Practice/E_Shipunova/razminka(iter).py +++ /dev/null @@ -1,28 +0,0 @@ -class ReaderLine: - - def __init__(self, text, symbol): - self.text, self.symbol, self._index_start = text, symbol, 0 - - def __iter__(self): - return self - - def __next__(self): - if self._index_start < len(self.text): - buf = [] - for i in range(self._index_start, len(self.text)): # start with the new self._index_start - if self.text[i] != self.symbol: - buf.append(self.text[i]) - if i == len(self.text) - 1: # if this is the last symbol and - self._index_start = i + 1 # our buf isn't empty - return "".join(buf) # for return string, because we work with list[] - - elif self.text[i] == self.symbol: - self._index_start = i + 1 # new start index, go to the next symbol - return "".join(buf) # for return string, because we work with list[] - - raise StopIteration - - -if __name__ == "__main__": - for line in ReaderLine("On Two\tThree\t...Seven", "\t"): - print(line) diff --git a/Practice/E_Shipunova/razminka(zip).py b/Practice/E_Shipunova/razminka(zip).py deleted file mode 100644 index 93ecab64..00000000 --- a/Practice/E_Shipunova/razminka(zip).py +++ /dev/null @@ -1,12 +0,0 @@ -def trans_matrix(matrix): - return [list(x) for x in zip(*matrix)] # zip return an iterator of zip-obj - - -if __name__ == "__main__": - m = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] - print(m) - print(trans_matrix(m)) diff --git a/Practice/E_Shipunova/test.txt b/Practice/E_Shipunova/test.txt deleted file mode 100644 index eca067d8..00000000 --- a/Practice/E_Shipunova/test.txt +++ /dev/null @@ -1,3 +0,0 @@ -A function definition is an executable statement. -Its execution binds the function name in the current -local namespace to a function object. \ No newline at end of file diff --git a/Practice/E_Shipunova/test/f1.txt b/Practice/E_Shipunova/test/f1.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/E_Shipunova/test/p1/f2.txt b/Practice/E_Shipunova/test/p1/f2.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/E_Shipunova/test/p1/p3/f131.txt b/Practice/E_Shipunova/test/p1/p3/f131.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/E_Shipunova/test/p1/p3/f132.txt b/Practice/E_Shipunova/test/p1/p3/f132.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/E_Shipunova/user.py b/Practice/E_Shipunova/user.py deleted file mode 100644 index 1881e82e..00000000 --- a/Practice/E_Shipunova/user.py +++ /dev/null @@ -1,8 +0,0 @@ -class User: - def __init__(self, name, age, position): - self.name = name - self.age = age - self.position = position - - def __repr__(self): - return "User: name={}, age={}, position={}.".format(self.name, self.age, self.position) diff --git a/Practice/EvgeniySyatoykin/1.py b/Practice/EvgeniySyatoykin/1.py deleted file mode 100644 index 5d019e8e..00000000 --- a/Practice/EvgeniySyatoykin/1.py +++ /dev/null @@ -1,7 +0,0 @@ - -name = input("Введите имя: ") -print ("Привет", name) - - - - diff --git a/Practice/EvgeniySyatoykin/2.1.py b/Practice/EvgeniySyatoykin/2.1.py deleted file mode 100644 index 135b6f54..00000000 --- a/Practice/EvgeniySyatoykin/2.1.py +++ /dev/null @@ -1,7 +0,0 @@ -def fun(a, b): - - if (a > b): - print(f"max number={a}") - else: - print(f"max number{b}") - diff --git a/Practice/IvanovA/lec2-zad1.py b/Practice/IvanovA/lec2-zad1.py deleted file mode 100644 index 38e6e399..00000000 --- a/Practice/IvanovA/lec2-zad1.py +++ /dev/null @@ -1,8 +0,0 @@ -def function(a, b): - if a >= b: - print(a) - else: - print(b) -num1 = int(input('введите первое число: ')) -num1 = int(input('введите второе число: ')) -function(num1, num1) \ No newline at end of file diff --git a/Practice/IvanovA/lec2-zad2.py b/Practice/IvanovA/lec2-zad2.py deleted file mode 100644 index 26b68ff2..00000000 --- a/Practice/IvanovA/lec2-zad2.py +++ /dev/null @@ -1,8 +0,0 @@ -def function(a, b): - if a >= b: - return a - else: - return b -num1 = int(input('введите первое число: ')) -num2 = int(input('введите второе число: ')) -print(function(num1, num2)) \ No newline at end of file diff --git a/Practice/IvanovA/lec4-zad1.py b/Practice/IvanovA/lec4-zad1.py deleted file mode 100644 index c097079b..00000000 --- a/Practice/IvanovA/lec4-zad1.py +++ /dev/null @@ -1,9 +0,0 @@ -for x in range(0, 101): - if x % 15 == 0: - print('FizzBuzz') - elif x % 3 == 0: - print('Fizz') - elif x % 5 == 0: - print('Buzz') - else: - print(x) \ No newline at end of file diff --git a/Practice/IvanovA/lec4-zad2.py b/Practice/IvanovA/lec4-zad2.py deleted file mode 100644 index 77e66ffb..00000000 --- a/Practice/IvanovA/lec4-zad2.py +++ /dev/null @@ -1,8 +0,0 @@ -while True: - n = input("Введите число: ") - if not n.isdigit(): - print("Ошибка введите ещё раз") - else: - break -for i in range(len(n)): - print("{} число равно {}".format(i+1, n[i])) diff --git a/Practice/IvanovA/lec4-zad3.py b/Practice/IvanovA/lec4-zad3.py deleted file mode 100644 index 741be21d..00000000 --- a/Practice/IvanovA/lec4-zad3.py +++ /dev/null @@ -1,14 +0,0 @@ -arr = [0, 3, 24, 2, 3, 7] -def sortarray(n): - for i in range(len(n) - 1): - m = i - b = i + 1 - while b < len(n): - if n[b] < n[m]: - m = b - b = b + 1 - n[i], n[m] = n[m], n[i] - -print(arr) -sortarray(arr) -print(arr) diff --git a/Practice/IvanovA/lec4-zad4.py b/Practice/IvanovA/lec4-zad4.py deleted file mode 100644 index 131d7240..00000000 --- a/Practice/IvanovA/lec4-zad4.py +++ /dev/null @@ -1,12 +0,0 @@ -def replacingspace(spacetab): - return spacetab.replace(" ", "\t") - -def replacingtab(spacetab): - return spacetab.replace("\t", " ") - - -s = "слово слово слово слоао" -s = replacingspace(s) -print(s) -s = replacingtab(s) -print(s) diff --git a/Practice/IvanovA/lec4-zad5.py b/Practice/IvanovA/lec4-zad5.py deleted file mode 100644 index a4813387..00000000 --- a/Practice/IvanovA/lec4-zad5.py +++ /dev/null @@ -1,7 +0,0 @@ - -text = 'Какое плохое кафе. Обсллуживание не хорошее, Еда не вкусная' -badrepgood = {'плохое': 'хорошее','не хорошее': 'хорошее','не вкусная': 'вкусная'} -print(text) -for i in badrepgood: - text = text.replace(i, badrepgood[i]) -print(text) \ No newline at end of file diff --git a/Practice/IvanovA/lec5-zad1.py b/Practice/IvanovA/lec5-zad1.py deleted file mode 100644 index f0b08707..00000000 --- a/Practice/IvanovA/lec5-zad1.py +++ /dev/null @@ -1,9 +0,0 @@ -class Man: - def __init__(self, name): - self.name = name - def solve_task(self): - print("I'm not ready yet") -n = Man('') -print(n.solve_task()) - - diff --git a/Practice/IvanovA/lec5-zad2.py b/Practice/IvanovA/lec5-zad2.py deleted file mode 100644 index e4bbe1f5..00000000 --- a/Practice/IvanovA/lec5-zad2.py +++ /dev/null @@ -1,19 +0,0 @@ -import time -import random - -class Man: - def __init__(self, name): - self.name = name - def solve_task(self): - print("Hold on!") - -class Pupil(Man): - def solve_task(self): - time.sleep(random.randint(3, 6)) - print("I'm not ready yet") - -n = Man('') -n.solve_task() -p = Pupil('') -p.solve_task() - diff --git a/Practice/IvanovA/lec6-zad3.py b/Practice/IvanovA/lec6-zad3.py deleted file mode 100644 index e2d9c05f..00000000 --- a/Practice/IvanovA/lec6-zad3.py +++ /dev/null @@ -1,16 +0,0 @@ -import time - -class TimeCounter: - - def __enter__(self): - self.start_time = time.perf_counter() - print('Start') - - def __exit__(self, exc_type, exc_val, exc_tb): - self.end_time = time.perf_counter() - self.start_time - print('operating time {}'.format(self.end_time)) - -with TimeCounter(): - lst = [] - for i in range(1, 10000000): - lst.append(i ** 2) diff --git a/Practice/IvanovA/lec6-zad4.py b/Practice/IvanovA/lec6-zad4.py deleted file mode 100644 index 1426b3c4..00000000 --- a/Practice/IvanovA/lec6-zad4.py +++ /dev/null @@ -1,17 +0,0 @@ -import itertools - -def onearr(lst1, lst2, lst3): - arr = list(itertools.chain(lst1, lst2, lst3)) - return arr - -def filtarr(lst): - filter = list(itertools.filterfalse(lambda x: len(x) < 5, lst)) - return filter - -def combination(string, r): - password = list(itertools.combinations(string, r)) - return password - -print(onearr([1, 2, 3], [4, 5], [6, 7])) -print(filtarr(['hello', 'i', 'write', 'cool', 'code'])) -print(combination('password', 4)) \ No newline at end of file diff --git a/Practice/IvanovA/lec7-zad-1.py b/Practice/IvanovA/lec7-zad-1.py deleted file mode 100644 index 9fab1481..00000000 --- a/Practice/IvanovA/lec7-zad-1.py +++ /dev/null @@ -1,22 +0,0 @@ -from _datetime import datetime,date - -date1 = input('Ввведите дату начала в формате гггг мм дд:') -date1 = date1.split(' ') -date1 = date(int(date1[0]), int(date1[1]), int(date1[2])) - -date2 = input('Ввведите дату окончания в формате гггг мм дд:') -date2 = date2.split(' ') -date2 = date(int(date2[0]), int(date2[1]), int(date2[2])) - -difference = ((date2 - date1).days) -weekday = datetime.weekday(date1) -working_day = [] -for i in range(difference + 1): - if weekday < 5: - working_day.append(weekday) - weekday += 1 - elif weekday > 5: - weekday = 0 - else: - weekday += 1 -print('Количесво рабочих денй за период ' + str(len(working_day))) \ No newline at end of file diff --git a/Practice/IvanovA/lec7-zad2.py b/Practice/IvanovA/lec7-zad2.py deleted file mode 100644 index 78baff4a..00000000 --- a/Practice/IvanovA/lec7-zad2.py +++ /dev/null @@ -1,6 +0,0 @@ -import subprocess - -def read_file(filename): - subprocess.run(['type', filename], shell=True) - -read_file(r"D:\text.txt") \ No newline at end of file diff --git a/Practice/Karpov_A/Lec_6/t6_3.py b/Practice/Karpov_A/Lec_6/t6_3.py deleted file mode 100644 index 4ac67432..00000000 --- a/Practice/Karpov_A/Lec_6/t6_3.py +++ /dev/null @@ -1,17 +0,0 @@ -import time - -class Wait: - def __init__(self): - self.begint = 0 - - def __enter__(self): - self.begint = time.time() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - print(f"Around time: {time.time() - self.begint} seconds") - -with Wait(): - arr = [] - for i in range(1, 10000000): - arr.append(i**2) \ No newline at end of file diff --git a/Practice/Karpov_A/Lec_6/t6_4.py b/Practice/Karpov_A/Lec_6/t6_4.py deleted file mode 100644 index 60cf1f1d..00000000 --- a/Practice/Karpov_A/Lec_6/t6_4.py +++ /dev/null @@ -1,18 +0,0 @@ -import itertools - - -def arr(num1, num2, num3): - joint = list(itertools.chain(num1, num2, num3)) - return joint - -def less(lst): - filtered = list(itertools.filterfalse(lambda x: len(x) != 5, lst)) - return filtered - -def key(string, r): - passwords = list(itertools.combinations(string, r)) - return passwords - -print(arr([1, 2, 3], [4, 5], [6, 7])) -print(less(['hello', 'i', 'write', 'cool', 'code'])) -print(key('password', 4)) \ No newline at end of file diff --git a/Practice/Karpov_A/pep8.py b/Practice/Karpov_A/pep8.py deleted file mode 100644 index 69ef47a0..00000000 --- a/Practice/Karpov_A/pep8.py +++ /dev/null @@ -1,70 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from fileinput import filename -from time import * - - -class shuffler: # class Shufler - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): # заменить на dir_name - mp3s = [] # более 4 пробелов, сдвинуть на 2 пробела назад - for root, directories, files in os.walk(dirname): # заменить на dir_name - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' # заменить на hash_name - self.map[hashname] = mp3 # заменить на hash_name - os.rename(path + '/' + mp3), path + '/' + hashname)) # удалить скобки в средине и в конце, и заменить на hash_name - f = open(output, 'r') # удалить 2 пробела - f.write(str(self.map)) # удалить на 2 пробела - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: # удалить 2 пробела. Импорт filename, добавляется from fileinput import filename - self.map = ast.literal_eval(f.read()) - mp3s = [] # добавить на 2 пробела - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: # заменить на hash_name - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) # удалить одну скобку в конце и заменить на hash_name - os.remove(restore_path) # добавить на 4 пробела - - def generateName(self, seed=time()): - return hashlib.md5(str(seed)).hexdigest() # удалить 2 пробела - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() # заменить на shuffler = Shuffler() - if args.subcommand == 'rename': - if args.output: - Shuffler.rename(args.dirname, 'restore.info') # заменить на shuffler.rename(args.dirname, 'restore.info') - else: - Shuffler.rename(args.dirname, args.output) # заменить на shuffler.rename(args.dirname, 'restore.info') - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) # заменить на shuffler.rename(args.dirname, 'restore.info') - else: - sys.exit() - - -main() \ No newline at end of file diff --git a/Practice/Karpov_A/t2_1.py b/Practice/Karpov_A/t2_1.py deleted file mode 100644 index 2132b235..00000000 --- a/Practice/Karpov_A/t2_1.py +++ /dev/null @@ -1,8 +0,0 @@ -def fun (a, b): - if a > b: - print (f"max number={a}") - else: - print (f"max number{b}") - - - diff --git a/Practice/Karpov_A/t2_2.py b/Practice/Karpov_A/t2_2.py deleted file mode 100644 index d22bea79..00000000 --- a/Practice/Karpov_A/t2_2.py +++ /dev/null @@ -1,8 +0,0 @@ -def fun (a, b): - if a > b: - return a - else: - return b - -fun(3, 5) - diff --git a/Practice/Karpov_A/t2_3.py b/Practice/Karpov_A/t2_3.py deleted file mode 100644 index b8f5d1dd..00000000 --- a/Practice/Karpov_A/t2_3.py +++ /dev/null @@ -1,58 +0,0 @@ -class Specif(): - speed = 3 - jump = 4 - shot = 10 - -class Charact(): - x = 0 - y = 0 - def walk(self): - self.x = self.x + 1 - - def show_where_i(self): - print("x:{}, y{}", self.x, self.y) - - def fly(self): - print("I can'fly") - - def shoot(self): - print("I can shoot") - - def jump(self): - print("I can jump") - -class SpecCharact(Charact): - - def fly(self): - self.y = self.y + 1 - -def main(): - - spec = Specif() - charact = Charact() - scharact = SpecCharact() - persons = list() - persons.append(charact) - persons.append(scharact) - - while(1): - print("input number of player") - number = int(input()) - print("input command to player") - command = input() - - if command == "go": - persons[number].go() - elif command == "shoot": - persons[number].shoot() - elif command == "fly": - persons[number].fly() - else: - print("Unknown command: {}".format(command)) - - persons[number].show_where_i() - - if persons[number].x == spec.x: - print("player{} got item", ) - - diff --git a/Practice/Karpov_A/t4_1.py b/Practice/Karpov_A/t4_1.py deleted file mode 100644 index 03d728e9..00000000 --- a/Practice/Karpov_A/t4_1.py +++ /dev/null @@ -1,12 +0,0 @@ -def fb (): - for i in range(1,101): - if i % 15 == 0: - print("FizzBuzz") - elif i % 5 == 0: - print("Buzz") - elif i % 3 == 0: - print("Fizz") - else: - print(i, " don't divided") -fb() - diff --git a/Practice/Karpov_A/t4_2.py b/Practice/Karpov_A/t4_2.py deleted file mode 100644 index adf1ef8d..00000000 --- a/Practice/Karpov_A/t4_2.py +++ /dev/null @@ -1,8 +0,0 @@ - -def numlsit(num): - for i, k in enumerate(num): - i = i + 1 - d = "{} цифра равна {}".format(i, k) - print(d) - -numlsit("18504") \ No newline at end of file diff --git a/Practice/Karpov_A/t4_3.py b/Practice/Karpov_A/t4_3.py deleted file mode 100644 index 928325de..00000000 --- a/Practice/Karpov_A/t4_3.py +++ /dev/null @@ -1,14 +0,0 @@ -def sorting(arr): - for i in range(len(arr) - 1): - min = i - j = i + 1 - while j < len(arr): - if arr[j] < arr[min]: - min = j - j = j + 1 - arr[i], arr[min] = arr[min], arr[i] - print(arr) - - -arr = [0, -5, 34, 2, 3, -59] -sorting(arr) \ No newline at end of file diff --git a/Practice/Karpov_A/t4_4.py b/Practice/Karpov_A/t4_4.py deleted file mode 100644 index 4b842f29..00000000 --- a/Practice/Karpov_A/t4_4.py +++ /dev/null @@ -1,13 +0,0 @@ -def spacesToTab(str): - return str.replace(" ", "\t") - - -def tabToSpaces(str): - return str.replace("\t", " ") - - -s = "5 7 6 3" -s = spacesToTab(s) -print(s) -s = tabToSpaces(s) -print(s) \ No newline at end of file diff --git a/Practice/Karpov_A/t4_5.py b/Practice/Karpov_A/t4_5.py deleted file mode 100644 index 6f55959d..00000000 --- a/Practice/Karpov_A/t4_5.py +++ /dev/null @@ -1,6 +0,0 @@ -a = 'home is better than flat' -b = {'home': 'дом','flat': 'квартира'} -for i in b: - a = a.replace(i, (b[i])) - -print(a) \ No newline at end of file diff --git a/Practice/Karpov_A/t5_1.py b/Practice/Karpov_A/t5_1.py deleted file mode 100644 index 20eea7eb..00000000 --- a/Practice/Karpov_A/t5_1.py +++ /dev/null @@ -1,10 +0,0 @@ -class Man: - def __init__(self, name): - self.name = name - - def solve_task(self): - print("I'm not ready yet") - -man = Man('Tom') -print(f"{man.name}:", end=" ") -man.solve_task() diff --git a/Practice/Karpov_A/t5_2.py b/Practice/Karpov_A/t5_2.py deleted file mode 100644 index fdf6d78b..00000000 --- a/Practice/Karpov_A/t5_2.py +++ /dev/null @@ -1,15 +0,0 @@ -import time -import random -from t5_1 import Man - -class Pupil(Man): - def __init__(self, name): - self.name = name - - def solve_task(self): - time.sleep(random.randint(3,6)) - print("I'm not ready ") - -Tom = Pupil('Tom') -print(f"{Tom.name}:", end=" ") -Tom.solve_task() diff --git a/Practice/Karpov_A/t5_3.py b/Practice/Karpov_A/t5_3.py deleted file mode 100644 index d2750911..00000000 --- a/Practice/Karpov_A/t5_3.py +++ /dev/null @@ -1,35 +0,0 @@ -from tempfile import mktemp -from os import path -from os import remove - -class WrapStrToFile: - - def __init__(self): - self.filepath = mktemp(".txt", "exem") - - @property - def content(self): - try: - with open(self.filepath, "r") as file: - return file.read() - - except IOError as file: - return "Output: File does't exist" - - @content.setter - def content(self, value): - self.value = value - with open(self.filepath, "w") as file: - file.write(self.value) - - @content.deleter - def content(self): - remove(self.filepath) - -wrap = WrapStrToFile() -print(wrap.content) -wrap.content = 'exem one' -print(wrap.content) -wrap.content = 'exem two' -print(wrap.content) -del wrap.content diff --git a/Practice/Karpov_A/t6_3.py b/Practice/Karpov_A/t6_3.py deleted file mode 100644 index 4ac67432..00000000 --- a/Practice/Karpov_A/t6_3.py +++ /dev/null @@ -1,17 +0,0 @@ -import time - -class Wait: - def __init__(self): - self.begint = 0 - - def __enter__(self): - self.begint = time.time() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - print(f"Around time: {time.time() - self.begint} seconds") - -with Wait(): - arr = [] - for i in range(1, 10000000): - arr.append(i**2) \ No newline at end of file diff --git a/Practice/Karpov_A/t6_4.py b/Practice/Karpov_A/t6_4.py deleted file mode 100644 index 60cf1f1d..00000000 --- a/Practice/Karpov_A/t6_4.py +++ /dev/null @@ -1,18 +0,0 @@ -import itertools - - -def arr(num1, num2, num3): - joint = list(itertools.chain(num1, num2, num3)) - return joint - -def less(lst): - filtered = list(itertools.filterfalse(lambda x: len(x) != 5, lst)) - return filtered - -def key(string, r): - passwords = list(itertools.combinations(string, r)) - return passwords - -print(arr([1, 2, 3], [4, 5], [6, 7])) -print(less(['hello', 'i', 'write', 'cool', 'code'])) -print(key('password', 4)) \ No newline at end of file diff --git a/Practice/Postnikova/practice_10_task_1_client.py b/Practice/Postnikova/practice_10_task_1_client.py deleted file mode 100644 index c31d3e6b..00000000 --- a/Practice/Postnikova/practice_10_task_1_client.py +++ /dev/null @@ -1,15 +0,0 @@ -import socket -import random - -s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -what_to_ask_server = ['TCP', 'UDP', 'HTTP', 'HTTPS', 'HTML', 'XML', 'IP', 'URL', 'URI'] - -host = '127.0.0.1' -port = 55555 -s.connect((host, port)) -string_to_send = random.choice(what_to_ask_server) -print('I ask to server what is {}?'.format(string_to_send)) -s.send(string_to_send.encode()) -request_1 = s.recv(1024) -print('Server tell me {}'.format(request_1.decode())) -s.close() diff --git a/Practice/Postnikova/practice_10_task_1_server.py b/Practice/Postnikova/practice_10_task_1_server.py deleted file mode 100644 index ecc70f53..00000000 --- a/Practice/Postnikova/practice_10_task_1_server.py +++ /dev/null @@ -1,33 +0,0 @@ -import socket - -my_dictionary = {'TCP': 'Transmission Control Protocol', 'UDP': 'User Datagram Protocol', - 'HTTP': 'Hypertext Transfer Protocol', - 'HTTPS': 'HyperText Transfer Protocol Secure', 'IP': 'Internet Protocol', - 'URL': 'Uniform Resource Locator', - 'URI': 'Universal Resource Identifier', 'HTML': 'HyperText Markup Language', - 'XML': 'eXtensible Markup Language'} - - -def decrypt(word): - if word not in my_dictionary: - return 'Sorry, there is not such word in dictionary!' - return my_dictionary[word] - - -s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -host = '127.0.0.1' -port = 55555 -s.bind((host, port)) -s.listen(10) - -while True: - connection, address = s.accept() - print('Successful connection from {}'.format(address)) - response = connection.recv(1024) - decoded_response = response.decode() - print('Response is {}'.format(decoded_response)) - string_to_send = decrypt(decoded_response) - print('Reply is {}'.format(string_to_send)) - connection.send(string_to_send.encode()) - connection.close() -s.close() diff --git a/Practice/Postnikova/practice_10_task_2_client.py b/Practice/Postnikova/practice_10_task_2_client.py deleted file mode 100644 index e513e1d2..00000000 --- a/Practice/Postnikova/practice_10_task_2_client.py +++ /dev/null @@ -1,31 +0,0 @@ -import socket -import random -import pickle -import user - - -class TCPClient: - def __init__(self, host, port, name): - self._host = host - self._port = port - self.name = name - self._socket = None - - def run(self, some_user): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect((self._host, self._port)) - self._socket.send(pickle.dumps(some_user)) - print('I have send {}'.format(some_user)) - self._socket.close() - - -def create_user(): - names = ['Фёдор', 'Василиса', 'Марк', 'Марфа', 'Никодим'] - ages = [89, 78, 85, 72, 99] - return user.User(random.choice(names), random.choice(ages)) - - -if __name__ == '__main__': - name = 'Client' - my_client = TCPClient(host='127.0.0.1', port=3333, name=name) - my_client.run(create_user()) diff --git a/Practice/Postnikova/practice_10_task_2_server.py b/Practice/Postnikova/practice_10_task_2_server.py deleted file mode 100644 index 085966f4..00000000 --- a/Practice/Postnikova/practice_10_task_2_server.py +++ /dev/null @@ -1,49 +0,0 @@ -import threading -import socket -import pickle - - -class ClientThread(threading.Thread): - def __init__(self, conn, addr): - super().__init__() - self._connection = conn - self._address = addr - - def run(self): - print('Successful connection from {}'.format(self._address)) - data = pickle.loads(self._connection.recv(1024)) - print('Received {}'.format(data)) - self._connection.close() - print('Closed connection from {}'.format(self._address)) - - -class TCPServer: - def __init__(self, host, port): - self.host = host - self.port = port - self._socket = None - self._running = False - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self._socket.bind((self.host, self.port)) - self._socket.listen(5) - self._running = True - print('Server is started') - while self._running: - conn, addr = self._socket.accept() - ClientThread(conn, addr).start() - - def stop(self): - self._running = False - self._socket.close() - print('Server is stopped') - - -if __name__ == '__main__': - my_server = TCPServer(host='127.0.0.1', port=3333) - try: - my_server.run() - except KeyboardInterrupt: - my_server.stop() diff --git a/Practice/Postnikova/practice_10_task_3.py b/Practice/Postnikova/practice_10_task_3.py deleted file mode 100644 index 990a6287..00000000 --- a/Practice/Postnikova/practice_10_task_3.py +++ /dev/null @@ -1,33 +0,0 @@ -from urllib import request -from bs4 import BeautifulSoup - - -def find_all_links(url): - all_links = [] - req = request.Request(url) - response = request.urlopen(req) - web_page = response.read() - soup = BeautifulSoup(web_page, "html.parser") - for link in soup.find_all('a'): - all_links.append(link.get('href')) - return all_links - - -def check_links(links): - w_link_counter = 0 - n_link_counter = 0 - for link in links: - try: - req = request.Request(link) - except ValueError: - n_link_counter += 1 - continue - response = request.urlopen(req) - if response.getcode() == 200: - print('This is a working link {}'.format(link)) - w_link_counter += 1 - else: - n_link_counter += 1 - print('There are {} working and {} nonworking links'.format(w_link_counter, n_link_counter)) - -check_links(find_all_links('http://google.com')) diff --git a/Practice/Postnikova/practice_9_task_1.py b/Practice/Postnikova/practice_9_task_1.py deleted file mode 100644 index 85652e41..00000000 --- a/Practice/Postnikova/practice_9_task_1.py +++ /dev/null @@ -1,87 +0,0 @@ -import threading -import time -import multiprocessing - - -# Task_1 - -# Threads -def find_primes(end, start=3): - simple_numbers = [] - for i in range(start, end + 1): - for j in range(2, i): - if i % j == 0: - break - else: - simple_numbers.append(i) - print(f"In range from {start} to {end} I have found {len(simple_numbers)} primes") - return simple_numbers - - -all_values = [(10000, 3), (20000, 10001), (30000, 20001)] - - -def find_primes_with_threads(): - print('Start measuring with threads') - start = time.time() - all_threads = [] - for my_range in all_values: - thr = threading.Thread(target=find_primes, args=my_range) - thr.start() - all_threads.append(thr) - - for thr in all_threads: - thr.join() - print('Thread {} is joined'.format(thr)) - thr_result = time.time() - start - print('With threads it takes ' + '{0:.4f} sec'.format(thr_result)) - return thr_result - - -# Process -all_process = [] -if __name__ == "__main__": - thr_result = find_primes_with_threads() - - print('Start measuring in sequence run') - start = time.time() - for my_range in all_values: - find_primes(*my_range) - result_without_thr_and_p = time.time() - start - print('Without threads and processes it takes ' + '{0:.4f} sec'.format(result_without_thr_and_p)) - - print('Start measuring with processes') - start = time.time() - for my_range_1 in all_values: - p = multiprocessing.Process(target=find_primes, args=my_range_1) - p.start() - all_process.append(p) - - for p in all_process: - p.join() - print('Process {} is joined'.format(p)) - p_result = time.time() - start - print('With process it takes ' + '{0:.4f} sec'.format(p_result)) - - """Если забыть выполнить start(), то ни процесс, ни поток просто не запустятся, - при наличии в коде join() далее выдаётся ошибка "RuntimeError: cannot join thread before it is started". - - Если забыть выполнить join() для треда, то работа приложения может завершится раньше, - чем все треды завершат свою работу, а для процесса - основной процесс завершится, - а процессы продолжат свою работу""" - - if thr_result < p_result and thr_result < result_without_thr_and_p: - print(f"Using threads is faster than processes by {p_result - thr_result} sec " - f"and sequential start by {p_result - result_without_thr_and_p} sec") - elif thr_result > p_result and result_without_thr_and_p > p_result: - print(f"Using processes is faster than threads by {thr_result - p_result} sec " - f"and than sequential start by {result_without_thr_and_p - p_result} sec") - elif result_without_thr_and_p < thr_result and result_without_thr_and_p < p_result: - print(f"Using sequential start is faster than threads by {thr_result - result_without_thr_and_p} sec " - f"and than processes by {p_result - result_without_thr_and_p} sec") - -"""Итог: Using processes is faster than threads by 1.7642529010772705 sec and than sequential start by 1.0940639972686768 sec, - таким образом, для вычислений -использование threads не слишком эффективно, поскольку требует дополнительных ресурсов на создание потоков и переключение между потоками, что занимает дополнительное время. -Кроме того, поскольку интерпретатор CPython не является поткобезопасным, в нём используется блокровка Global Interpreter Lock (GIL), которая разрешает в каждый момент времени -выпонлять байт-код только одному потоку, т.е. добиться параллелизма при использовании потоков невозможно. -Следовательно, самый быстрый результат для выполнения существенного объёма вычислений даёт использование процессов.""" \ No newline at end of file diff --git a/Practice/Postnikova/practice_9_task_2.py b/Practice/Postnikova/practice_9_task_2.py deleted file mode 100644 index 70cfb0f6..00000000 --- a/Practice/Postnikova/practice_9_task_2.py +++ /dev/null @@ -1,33 +0,0 @@ -import multiprocessing - -# Task_2 - -def summarize_anythig(*args): - sum_int = 0 - sum_string = '' - sum_list = [] - for index in range(len(args)): - if type(args[index]) is not type(args[index-1]): - print('Sorry, types of all arguments should be the same!') - break - elif isinstance(args[index], int): - sum_int += args[index] - elif isinstance(args[index], str): - sum_string = f'{sum_string} {args[index]}' - elif isinstance(args[index], list): - sum_list += args[index] - return sum_int, sum_string, sum_list - - -all_values = [(1, 2, 3, 88), ['Python', 'is', 'a', 'programming', 'language'], [[1, 2, 3], [5, 8, 9], [22, 77, 12]]] -all_processes = [] - -if __name__ == "__main__": - for my_range in all_values: - p = multiprocessing.Process(target=summarize_anythig, args=my_range) - p.start() - all_processes.append(p) - - for p in all_processes: - p.join() - print('Process {} is joined'.format(p)) \ No newline at end of file diff --git a/Practice/Postnikova/practice_9_task_3.py b/Practice/Postnikova/practice_9_task_3.py deleted file mode 100644 index 38f66efa..00000000 --- a/Practice/Postnikova/practice_9_task_3.py +++ /dev/null @@ -1,26 +0,0 @@ -import threading -import random - -#Task 3 - -thread_local = threading.local() - -def save_private_data(): - my_list = ['threads', 'processes', 'Queue', 'GIL', 'mutex', 'Pipe'] - secret = getattr(thread_local, 'secret', None) - if secret is None: - secret = random.choice(my_list) - thread_local.secret = secret - print(f"Thread {threading.current_thread().name} knows secret about {secret}") - -all_threads = [] - -for i in range(6): - thread_local.initialized = True - thr = threading.Thread(target=save_private_data, args=( )) - thr.start() - all_threads.append(thr) - -for thr in all_threads: - thr.join() - print('Thread {} is joined'.format(thr)) \ No newline at end of file diff --git a/Practice/Postnikova/user.py b/Practice/Postnikova/user.py deleted file mode 100644 index 5dd9b9e9..00000000 --- a/Practice/Postnikova/user.py +++ /dev/null @@ -1,12 +0,0 @@ - -class User: - name = "name" - age = None - - def __init__(self, name, age): - self.name = name - self.age = age - - def __repr__(self): - return f"User(name='{self.name}', age='{self.age}')" - diff --git a/Practice/README.md b/Practice/README.md deleted file mode 100644 index 1ea6827e..00000000 --- a/Practice/README.md +++ /dev/null @@ -1,17 +0,0 @@ -Рабочая папка для слушателей курса. Пожалуйста, создавайте свои подпапки, называя их по своей фамилии (на английском) и сохраняйте в них результаты выполнения заданий. - -Для работы с репозиторием можно установить git и использовать следующий порядок действий: -1. Регистрируетесь на guithub.com и подписываетесь на данный репозиторий нажимая кнопку Watch справа вверху. -2. На рабочем компьютере выполняете команду "git clone https://github.com/IlyaOrlov/PythonCourse.git", чтоб скачать репозиторий через https, либо git clone git@github.com:IlyaOrlov/PythonCourse.git - для скачивания через ssh. Первый вариант попроще и не требует дополнительных усилий. Второй вариант потребует от вас разобраться с настройкой ssh (https://help.github.com/articles/connecting-to-github-with-ssh/). -3. По умолчанию вы будете находится на бранче master. Начиная работу над новым заданием, создайте свой бранч, с помощью следующей команды: -"git checkout -b my_branch", где my_branch - название вашего бранча (английскими буквами без пробелов), которое вы ему придумаете. -4. Публикуете эту ветку в удаленном репозитории: git push --set-upstream origin my_branch -5. В папке Practice создаете подпапку (если еще не создали), называете ее по своей фамилии, и добавляете туда скрипт с выполненным заданием (например, mytest.py), либо делаете всяческие изменения в своих скриптах. -6. Вносите файл под контроль git с помощью команды "git add" (например, git add mytest.py) -7. Коммитите изменения (чтобы git присвоил им номер версии): git commit -m "Любой разумный комментарий к сделанным изменениям" -8. Подтягиваете последние изменения из общего репозитория: git pull origin master -9. Публикуете свои изменения на своем бранче в удаленном репозитории на сервере: git push -10. Зайдя на страницу репозитория в гитхабе (https://github.com/IlyaOrlov/PythonCourse), в списке Branch выбираете свой бранч и нажимаете New pull request, чтоб запросить внесение изменений с вашего бранча в master бранч. - -Пункты 1-2 выполняются однократно. Пункты 3-4, 10 - при работе над каждым новым заданием. Пункты 5-9 при каждом изменении, которое вы собираетесь публиковать. -Если вы предпочитаете командной строке работу с визуальным интерфейсом - можно скачать и установить приложение TortoiseGit (https://tortoisegit.org/download/) и выполнить пункты 3-9 в нем. Также TortoiseGit - удобная штука для разрешения конфликтов, которые могут возникнуть после шага 8. diff --git a/Practice/SNazarov/Control task/destination.txt b/Practice/SNazarov/Control task/destination.txt deleted file mode 100644 index 6769dd60..00000000 --- a/Practice/SNazarov/Control task/destination.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/Practice/SNazarov/Control task/sourse.txt b/Practice/SNazarov/Control task/sourse.txt deleted file mode 100644 index 6769dd60..00000000 --- a/Practice/SNazarov/Control task/sourse.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/Practice/SNazarov/__pycache__/task_5_1.cpython-38.pyc b/Practice/SNazarov/__pycache__/task_5_1.cpython-38.pyc deleted file mode 100644 index 20dd07de3c9a5d923f19811f410691eaa1641fed..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 662 zcmZ{g!A=`75I{ZlCTyd?r5rirhV~Mv2ap<72#Kl{5=2OW%W5UpU7ND)W*uw?DG@ig z@&yP9j{FB-u~)u;Yfj803N43@H1>?gGxKInR##gLW&G5WFL*zb^RGnc?4tT@Jiar{ zG+d)z@st^+`4yyKxPjl|mT7Uvb)*|N9GHRo=z#&#%>heRa?E`v9KBsszk!EgDQK2* z4VquGRA`|iys;AIHfwRHs+XcAsW-jt_~ z5+0eOab};t^|Fz(zxI!_1NGBqN0V@7t35k*-egBk<)O$;Ht4IVa`qw%%KwpD@>6#- zsbeXNst8gFYCfleX&VW<%RmkoSqj;2sBLrt?GA7+1k3x=kDL2HhMmfWjx$P6IujE% zae~Ik6;(*UQJXpR;%J~-x4bPcj3lfk`b&y6qWBx?Ck>*dB}iGfq#Rm3F3E07c|KO< zBI2loi{H1QEjjAtXaG`APce_h{H2b+BJIf9at6H_bdXq>N@L4KSPWI=Rw$o_|8Mm= R{<47DnYSR4wGT0@!z*1uiD&=- diff --git a/Practice/SNazarov/myfile.txt b/Practice/SNazarov/myfile.txt deleted file mode 100644 index 911660e6..00000000 --- a/Practice/SNazarov/myfile.txt +++ /dev/null @@ -1 +0,0 @@ -Hello my friends!!! \ No newline at end of file diff --git a/Practice/SNazarov/pep8.py b/Practice/SNazarov/pep8.py deleted file mode 100644 index 10647d45..00000000 --- a/Practice/SNazarov/pep8.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * - - -class shuffler: # Имена классов должно быть согласно CapWords - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): - mp3s = [] # нет 4 отступов в теле функции rename, не на равне с другиме строками в теле функции - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - os.rename(path + '/' + mp3), path + '/' + hashname)) # лишняя скобка в середине и конце строки. - f = open(output, 'r') # убрать 2 отступов до цикла for - f.write(str(self.map)) # убрать 2 отступов до цикла for - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: # тело with имеет разный индекс отступов в каждой строке. Неверный аргумент(filename). - self.map = ast.literal_eval(f.read()) - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: # тело цикла for имеет разный индекс отступов в каждой строке. - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) # лишня скобка в конце строки ). - os.remove(restore_path) - - def generateName(self, seed=time()): # функция generateName имеет больше 4 отступов. - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() - if args.subcommand == 'rename': - if args.output: - Shuffler.rename(args.dirname, 'restore.info') - else: - Shuffler.rename(args.dirname, args.output) - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() \ No newline at end of file diff --git a/Practice/SNazarov/task 4.1.py b/Practice/SNazarov/task 4.1.py deleted file mode 100644 index 0c3efa6a..00000000 --- a/Practice/SNazarov/task 4.1.py +++ /dev/null @@ -1,11 +0,0 @@ -def numbers(): - for i in range(1, 101): - if i % 15 == 0: - print('Fizz') - elif i % 5 == 0: - print('Buzz') - elif i % 3 == 0: - print('FizzBuzz') - else: - print(i) -numbers() \ No newline at end of file diff --git a/Practice/SNazarov/task 4.2.py b/Practice/SNazarov/task 4.2.py deleted file mode 100644 index 3c4231ff..00000000 --- a/Practice/SNazarov/task 4.2.py +++ /dev/null @@ -1,11 +0,0 @@ -import random - - -N = 5 -def new_line(array): - for i in range(N): - print(f'{i} цифра равна {array[i]}') - -Line = [random.randint(0, 9) for j in range(N)] -print(Line) -new_line(Line) diff --git a/Practice/SNazarov/task 4.3.py b/Practice/SNazarov/task 4.3.py deleted file mode 100644 index a8879081..00000000 --- a/Practice/SNazarov/task 4.3.py +++ /dev/null @@ -1,19 +0,0 @@ -import random - - -N = 10 -def sorting(array): - - for i in range(len(array) - 1): - min = i - next_min = i + 1 - while next_min < len(array): - if array[next_min] < array[min]: - min = next_min - next_min += 1 - array[i], array[min] = array[min], array[i] - -Line = [random.randint(0, 9) for j in range(N)] -print(Line) -sorting(Line) -print(Line) diff --git a/Practice/SNazarov/task 4.4.py b/Practice/SNazarov/task 4.4.py deleted file mode 100644 index 7f167f9a..00000000 --- a/Practice/SNazarov/task 4.4.py +++ /dev/null @@ -1,29 +0,0 @@ -def tab_space(line, flag): - if flag is True: - array = line.split('\t') - newLine = ' '.join(array) - print(newLine) - else: - array = line.split(' ') - newLine = '\t'.join(array) - print(newLine) - -tab = "Жил\tбыл\tпес!" -space = "Жил был пес!" -bool = True -print(tab) -tab_space(tab, bool) -bool = False -print(space) -tab_space(space, bool) - -def file_spece_or_tab(line): - array = line.split(' ') - newLine = '\t'.join(array) - print(newLine) - -file = open('myfile.txt', 'r') -line = file.read() -file.close() - -file_spece_or_tab(line) \ No newline at end of file diff --git a/Practice/SNazarov/task 4.5.py b/Practice/SNazarov/task 4.5.py deleted file mode 100644 index 73d1750b..00000000 --- a/Practice/SNazarov/task 4.5.py +++ /dev/null @@ -1,10 +0,0 @@ -def templates(newLine): - dict = {'снег':'дождь', 'не':'очень'} - - for k, v in dict.items(): - newLine = newLine.replace(k, v) - print(newLine) - -line = 'Сегоня идет снег. Я не люблю это время.' -print(line) -templates(line) \ No newline at end of file diff --git a/Practice/SNazarov/task 4.6.py b/Practice/SNazarov/task 4.6.py deleted file mode 100644 index 102bd591..00000000 --- a/Practice/SNazarov/task 4.6.py +++ /dev/null @@ -1,30 +0,0 @@ -def matrix(list, num, list_len): - index = 0 - count = 0 - - while count != list_len: - count = 0 - - for i in list: - try: - index = i.index(num) - - except ValueError: - count += 1 - - if count == list_len: - break - - for j in list: - del j[index] - - print(list) - -num = 9 -list = [[1, 2, 3, 4, 5], - [9, 9, 3, 4, 5], - [1, 2, 3, 4, 5], - [1, 2, 3, 4, 5], - [1, 2, 3, 9, 5]] -list_len = (len(list)) -matrix(list, num, list_len) diff --git a/Practice/SNazarov/task 5.2.py b/Practice/SNazarov/task 5.2.py deleted file mode 100644 index 4fde8ba6..00000000 --- a/Practice/SNazarov/task 5.2.py +++ /dev/null @@ -1,17 +0,0 @@ -import random -import time -from task_5_1 import Man - - -class Pupil(Man): - def __init__(self, first_name): - super().__init__(first_name) - - def solve_task(self): - print('Mmmm....!!') - time.sleep(random.randint(3, 6)) - print("'I`m not ready either'") - -man2 = Pupil("Halk") -print(f"{man2.first_name}:", end = " ") -man2.solve_task() diff --git a/Practice/SNazarov/task 5.3.py b/Practice/SNazarov/task 5.3.py deleted file mode 100644 index d1cb3343..00000000 --- a/Practice/SNazarov/task 5.3.py +++ /dev/null @@ -1,35 +0,0 @@ -import tempfile -import os - - -class WrapStrToFile: - def __init__(self): - self.filepath = tempfile.mktemp() - - @property - def content(self): - try: - with open(self.filepath, "r") as f: - return f.read() - - except FileNotFoundError: - return "File does not exist!" - - @content.setter - def content(self, value): - with open(self.filepath, "w") as f: - f.write(value) - - @content.deleter - def content(self): - os.remove(self.filepath) - -wstf = WrapStrToFile() -print(wstf.content) -wstf.content = 'test srt' -print(wstf.content) -wstf.content = 'text 2' -print(wstf.content) -del wstf.content -print(wstf.filepath) - diff --git a/Practice/SNazarov/task2.1.py b/Practice/SNazarov/task2.1.py deleted file mode 100644 index 49cbed45..00000000 --- a/Practice/SNazarov/task2.1.py +++ /dev/null @@ -1,11 +0,0 @@ -def numbers(a, b): - if a > b: - print(f"First number is bigger: {a}") - else: - print(f"Second number is bigger: {b}") - -print("Enter two nubmers, please!") -first = int(input("Enter first number: ")) -second = int(input("Enter second number: ")) - -numbers(first, second) diff --git a/Practice/SNazarov/task2.2.py b/Practice/SNazarov/task2.2.py deleted file mode 100644 index 9933e0b4..00000000 --- a/Practice/SNazarov/task2.2.py +++ /dev/null @@ -1,13 +0,0 @@ -def numbers(a, b): - if a > b: - return a - else: - return b - -print("Enter two nubmers, please!") -first = int(input("Enter first number: ")) -second = int(input("Enter second number: ")) -result = numbers(first, second) -print(f"This number is bigger: {result}") - -numbers(first, second) diff --git a/Practice/SNazarov/task2.3.py b/Practice/SNazarov/task2.3.py deleted file mode 100644 index 059ae6ff..00000000 --- a/Practice/SNazarov/task2.3.py +++ /dev/null @@ -1,96 +0,0 @@ -import random - - -class RunAction: - def run(self): - print("I`m running!") - -class FastRunAction(RunAction): - def run(self): - print("I`m running very fast!!!") - -class SlowRunAction(RunAction): - def run(self): - print("I`m running slower!!!") - -class Warriors: - run_action = RunAction() - x = 0 - - def run(self): - self.run_action.run() - self.x += 1 - - def runFast(self): - self.run_action.run() - self.x += 2 - - def runSlow(self): - self.run_action.run() - self.x -= 2 - - def set_action(self, new_action): - self.run_action = new_action - - def draw(self): - print(f"I`m warrior at - {self.x}") - - def shoot(self): - print("BA-baHhhh!!!!") - -def leftUp(warrior): - print("I pick up something!") - i = random.randint(0, 1) - if i == 1: - print("you found thing! It is + 2 speed!!!") - warrior.set_action(FastRunAction()) - warrior.run = warrior.runFast - - else: - print("you found thing! It is - 2 speed!!!") - warrior.set_action(SlowRunAction()) - warrior.run = warrior.runSlow - -class CaptainVdv(Warriors): - def draw(self): - print(f"I`m CaptainVdv at - {self.x}") - - def fly(self): - self.x += 2 - -class MajorInfantry(Warriors): - def draw(self): - print(f"I`m MajorInfantry at - {self.x}") - -class ColonelAviation(Warriors): - def draw(self): - print(f"I`m ColonelAviation at - {self.x}") - -warrior = [CaptainVdv(), ColonelAviation(), MajorInfantry()] - -for warr in warrior: - warr.draw() -while True: - pers = int(input("Choose your warrior: | 0.CaptainVdv | 1.ColonelAviation | 2.MajorInfantry |: ")) - if pers != 0 and pers != 1 and pers != 2: - print("Wrong choise!!!") - continue - choose = input("What a warrior has to do? Select, please!: | 1.Run | 2.Shoot | 3.Fly | 4.Pick up an item | 5.Exit |: ") - if choose == '1': - warrior[pers].run() - elif choose == '2': - warrior[pers].shoot() - elif choose == '3': - if pers == 0: - warrior[pers].fly() - else: - print("This warrior can`t fly!!!") - elif choose == '4': - leftUp(warrior[pers]) - elif choose == '5': - break - else: - print("Wrong choise!!!") - continue - for warr in warrior: - warr.draw() \ No newline at end of file diff --git a/Practice/SNazarov/task_5_1.py b/Practice/SNazarov/task_5_1.py deleted file mode 100644 index af00ff2b..00000000 --- a/Practice/SNazarov/task_5_1.py +++ /dev/null @@ -1,12 +0,0 @@ -class Man: - - def __init__(self, first_name): - self.first_name = first_name - - def solve_task(self): - print("'I`m not ready yet'") - - -man = Man("Deadpool") -print(f"{man.first_name}:", end = " ") -man.solve_task() diff --git a/Practice/SNazarov/task_6_3.py b/Practice/SNazarov/task_6_3.py deleted file mode 100644 index a77cb4cf..00000000 --- a/Practice/SNazarov/task_6_3.py +++ /dev/null @@ -1,33 +0,0 @@ -import time - - -class MyManager: - - def __enter__(self): - - self.start = time.process_time() - print(f'Start - {self.start} sec') - - def __exit__(self, exc_type, exc_val, exc_tb): - print(f'Code completed - {time.process_time() - self.start} sec') - -arr = [] - -def numbers(num): - - global arr - for i in range(num): - if i % 15 == 0: - arr.append('Fizz') - elif i % 5 == 0: - arr.append('Buzz') - elif i % 3 == 0: - arr.append('FizzBuzz') - else: - arr.append(i) - - return arr - -with MyManager(): - numbers(10000000) - diff --git a/Practice/SNazarov/task_6_4.py b/Practice/SNazarov/task_6_4.py deleted file mode 100644 index 2d5573d0..00000000 --- a/Practice/SNazarov/task_6_4.py +++ /dev/null @@ -1,27 +0,0 @@ -import itertools - - -def sum_chain(arr): - return list(itertools.chain.from_iterable(arr)) - - -def pass_comb(data): - global lst - for result in itertools.combinations(data, 4): - lst.append(result) - return lst - - -def filter_false(data): - return list(itertools.filterfalse(lambda x: len(x) < 5, data)) - - -if __name__ == "__main__": - value = ([1, 2, 3], [4, 5], [6, 7]) - print(sum_chain(value)) - st = 'password' - lst = [] - print(pass_comb(st)) - text = ['hello', 'i', 'write', 'cool', 'code'] - print(filter_false(text)) - diff --git a/Practice/SNazarov/task_7_1.py b/Practice/SNazarov/task_7_1.py deleted file mode 100644 index 9abb5bd3..00000000 --- a/Practice/SNazarov/task_7_1.py +++ /dev/null @@ -1,22 +0,0 @@ -import datetime - - - -def day_works(new_date, next_date): - - delta = new_date - next_date - date = new_date - working_days = 0 - - for i in range(int(delta.days) + 1): - if date.weekday() < 5: - working_days += 1 - date += datetime.timedelta(days=1) - - return working_days - -if __name__ == "__main__": - - first_date = datetime.datetime(2020, 9, 16) - second_date = datetime.datetime(2020, 9, 1) - print(day_works(first_date, second_date)) \ No newline at end of file diff --git a/Practice/SNazarov/task_7_2.py b/Practice/SNazarov/task_7_2.py deleted file mode 100644 index 6ea2f0fd..00000000 --- a/Practice/SNazarov/task_7_2.py +++ /dev/null @@ -1,17 +0,0 @@ -import subprocess - - -def read_file(new_file): - - process = subprocess.Popen(['type', new_file], shell=True) - process.wait() - result = process.communicate() - if process.returncode: - return result[1] - - return result[0] - - -if __name__ == '__main__': - file = 'myfile.txt' - print(read_file(file)) diff --git a/Practice/SNazarov/task_7_3.py b/Practice/SNazarov/task_7_3.py deleted file mode 100644 index 2149af85..00000000 --- a/Practice/SNazarov/task_7_3.py +++ /dev/null @@ -1,48 +0,0 @@ -import random -import pickle - - -class Human: - - def __init__(self, first_name, last_name, age, auto, profession): - self.first_name = first_name - self.last_name = last_name - self.age = age - self.auto = auto - self.profession = profession - - def __getstate__(self): - return self.__dict__ - - -def write_human(number): - arr = [] - f_name = ['Andrey', 'Sergey', 'Roma', 'Yura', 'Oleg', 'Dmitriy', 'Ilya'] - l_name = ['Ivanov', 'Petrov', 'Sidorov', 'Kotov', 'Gorin', 'Socolov', 'Delov'] - auto = ['BMW', 'Audi', 'Nissan', 'Mercedes', 'Honda', 'Toyota', 'Lexus'] - profession = ['engineer', 'pilot', 'farmer', 'lawyer', 'businessman', 'actor', 'waiter'] - - for i in range(number): - first, last, car, prof, = random.choice(f_name), random.choice(l_name), \ - random.choice(auto), random.choice(profession) - arr.append(Human(first, last, random.randint(18, 55), car, prof)) - f_name.remove(first) - l_name.remove(last) - auto.remove(car) - profession.remove(prof) - - with open("human.data", "wb") as f: - pickle.dump(arr, f) - - -def open_human(): - with open("human.data", "rb") as f: - data = pickle.load(f) - for read in data: - print(f'This is {read.first_name} {read.last_name}, he is {read.age} years old. ' - f'He has a {read.auto} car and his profession is a {read.profession}.') - - -if __name__ == '__main__': - write_human(7) - open_human() diff --git a/Practice/Salakhetdinova/lab2.py b/Practice/Salakhetdinova/lab2.py deleted file mode 100644 index d30ead9a..00000000 --- a/Practice/Salakhetdinova/lab2.py +++ /dev/null @@ -1,14 +0,0 @@ -import random - -a = int(random.randint(1, 50)) -b = int(random.randint(1, 50)) - -def more(a, b): - if a > b: - print(f"{a} more {b}") - elif b > a: - print(f"{b} more {a}") - elif b == a: - print(f"{a} equal {b}") - -more(a, b) \ No newline at end of file diff --git a/Practice/Salakhetdinova/lab2_2.py b/Practice/Salakhetdinova/lab2_2.py deleted file mode 100644 index 45fc40dc..00000000 --- a/Practice/Salakhetdinova/lab2_2.py +++ /dev/null @@ -1,14 +0,0 @@ -import random - -a = int(random.randint(1, 50)) -b = int(random.randint(1, 50)) - -def more(a, b): - if a > b: - return a - elif b > a: - return b - elif b == a: - return None - -print(more(a, b)) \ No newline at end of file diff --git a/Practice/Salakhetdinova/lab4_1.py b/Practice/Salakhetdinova/lab4_1.py deleted file mode 100644 index 9416baf4..00000000 --- a/Practice/Salakhetdinova/lab4_1.py +++ /dev/null @@ -1,12 +0,0 @@ -def fizzBuzz(): - for i in range(1, 101): - if i % 15 == 0: - print("FizzBuzz") - elif i % 3 == 0: - print("Fizz") - elif i % 5 == 0: - print("Buzz") - else: - print(i) - -fizzBuzz() \ No newline at end of file diff --git a/Practice/Salakhetdinova/lab4_2.py b/Practice/Salakhetdinova/lab4_2.py deleted file mode 100644 index 63fc3214..00000000 --- a/Practice/Salakhetdinova/lab4_2.py +++ /dev/null @@ -1,9 +0,0 @@ -number = input("enter a five-digit number: ") - -def reoutput(n): - count = 1 - for i in n: - print(f"{count} number is {i}") - count = count + 1 - -reoutput(number) \ No newline at end of file diff --git a/Practice/Salakhetdinova/lab4_3.py b/Practice/Salakhetdinova/lab4_3.py deleted file mode 100644 index 048de98f..00000000 --- a/Practice/Salakhetdinova/lab4_3.py +++ /dev/null @@ -1,20 +0,0 @@ -import random - -def sort(arr): - for i in range(len(arr)): - min_value = i - for j in range(i + 1, len(arr)): - if arr[j] < arr[min_value]: - min_value = j - temp = arr[i] - arr[i] = arr[min_value] - arr[min_value] = temp - - - -arr = [] -for i in range(1, 7): - arr.append(random.randint(1, 50)) -print(arr) -sort(arr) -print(arr) diff --git a/Practice/Salakhetdinova/lab4_4.py b/Practice/Salakhetdinova/lab4_4.py deleted file mode 100644 index 9103d94a..00000000 --- a/Practice/Salakhetdinova/lab4_4.py +++ /dev/null @@ -1,12 +0,0 @@ -def replace(source, action): - if action == "tab": - return source.replace(" ", "\t") - elif action == "space": - return source.replace("\t", " ") - else: - return False - -string = input("Enter your string: ") -action = input("Enter \n tab: replace tabs with spaces \n space: replace spaces with tabs ") -print(replace(string, action)) - diff --git a/Practice/Salakhetdinova/lab4_5.py b/Practice/Salakhetdinova/lab4_5.py deleted file mode 100644 index 462b1f24..00000000 --- a/Practice/Salakhetdinova/lab4_5.py +++ /dev/null @@ -1,9 +0,0 @@ -def interpolate(string, dictionary): - for key in dictionary: - string = string.replace(key, dictionary[key]) - return string - -string = "Люди только чай пьют, а в их душах совершается трагедия" -dictionary = {'чай': 'кофе', 'трагедия': 'комедия'} -print(string) -print(interpolate(string, dictionary)) diff --git a/Practice/Salakhetdinova/lab5_1.py b/Practice/Salakhetdinova/lab5_1.py deleted file mode 100644 index d3e4b95b..00000000 --- a/Practice/Salakhetdinova/lab5_1.py +++ /dev/null @@ -1,10 +0,0 @@ -class Man: - - def __init__(self, name): - self.name = name - - def solve_task(self): - print("I'm not ready yet") - -man1 = Man("Masha") -man1.solve_task() \ No newline at end of file diff --git a/Practice/Salakhetdinova/lab5_2.py b/Practice/Salakhetdinova/lab5_2.py deleted file mode 100644 index 59fc4fc8..00000000 --- a/Practice/Salakhetdinova/lab5_2.py +++ /dev/null @@ -1,13 +0,0 @@ -import time -import random -from lab5_1 import Man - -class Pupil(Man): - - def solve_task(self): - time.sleep(random.randint(3, 7)) - print("I'm ready now?") - -man1 = Pupil("Masha") -man1.solve_task() -print(man1.name) diff --git a/Practice/Sam_Kilyaev/Lection_2_Task_1.py b/Practice/Sam_Kilyaev/Lection_2_Task_1.py deleted file mode 100644 index 438958eb..00000000 --- a/Practice/Sam_Kilyaev/Lection_2_Task_1.py +++ /dev/null @@ -1,16 +0,0 @@ -import random - -a = int(random.randint(1, 100)) -b = int(random.randint(1, 100)) - - -def more(a, b): - if a > b: - print(f"{a} more, than {b}") - elif b > a: - print(f"{b} more, than {a}") - elif b == a: - print(f"{a} equal {b}") - - -more(a, b) diff --git a/Practice/Sam_Kilyaev/Lection_2_Task_2.py b/Practice/Sam_Kilyaev/Lection_2_Task_2.py deleted file mode 100644 index eb2e411f..00000000 --- a/Practice/Sam_Kilyaev/Lection_2_Task_2.py +++ /dev/null @@ -1,16 +0,0 @@ -import random - -a = int(random.randint(1, 100)) -b = int(random.randint(1, 100)) - - -def more(a, b): - if a > b: - return a - elif b > a: - return b - elif b == a: - return None - - -print(more(a, b)) diff --git a/Practice/Sam_Kilyaev/Lection_2_Task_3.py b/Practice/Sam_Kilyaev/Lection_2_Task_3.py deleted file mode 100644 index 282d8a65..00000000 --- a/Practice/Sam_Kilyaev/Lection_2_Task_3.py +++ /dev/null @@ -1,79 +0,0 @@ -import random - - -class Run: - def run(self): - print("I`m running!") - - -class FastRun(Run): - def run(self): - print("I`m running very fast!") - - -class SlowRun(Run): - def run(self): - print("I`m frozen") - - -class Samurais: - action = Run() - x = 0 - y = 0 - - def run(self): - self.action.run() - self.x += 1 - self.y += 1 - - def runFast(self): - self.action.run() - self.x += 3 - self.y += 3 - - def runSlow(self): - self.action.run() - self.x -= 2 - self.y -= 2 - - def set_action(self, new_action): - self.action = new_action - - def draw(self): - print(f"I`m Samurai at - {self.x} : {self.y}") - - def shooting(self): - print("I open fire from my samurai's gun") - - -def pick_up(thing): - print("I pick up somewhat!") - i = random.randint(0, 1) - if i == 1: - print("I'm Flash") - thing.set_action(FastRun()) - thing.run = thing.runFast - - else: - print("I can not move faster!") - thing.set_action(SlowRun()) - thing.run = thing.runSlow - - -class Oni(Samurais): - def draw(self): - print(f"I`m Oni at - {self.x}:{self.y}") - - def fly(self): - self.x += 10 - self.y += 10 - - -class Nindja(Samurais): - def draw(self): - print(f"I`m Nindja at - {self.x}:{self.y}") - - -class KianeRivz(Samurais): - def draw(self): - print(f"I`m Kianu Rivz at - {self.x}:{self.y}") diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_1.py b/Practice/Sam_Kilyaev/Lection_4_Task_1.py deleted file mode 100644 index 9bad4b21..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_1.py +++ /dev/null @@ -1,13 +0,0 @@ -def fizz_buzz(): - for i in range(1, 101): - if i % 15 == 0: - print("FizzBuzz") - elif i % 3 == 0: - print("Fizz") - elif i % 5 == 0: - print("Buzz") - else: - print(i) - - -fizz_buzz() diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_2.py b/Practice/Sam_Kilyaev/Lection_4_Task_2.py deleted file mode 100644 index 10ab3ad1..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_2.py +++ /dev/null @@ -1,11 +0,0 @@ -fives_number = input("Write your number: ") - - -def reoutput(number): - count = 1 - for i in number: - print(f"{count} number is {i}") - count = count + 1 - - -reoutput(fives_number) diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_3.py b/Practice/Sam_Kilyaev/Lection_4_Task_3.py deleted file mode 100644 index daf74eb8..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_3.py +++ /dev/null @@ -1,17 +0,0 @@ -import random - - -def choise_sort(arr): - for i in range(len(arr)): - min_value = i - for j in range(i + 1, len(arr)): - if arr[j] < arr[min_value]: - min_value = j - arr[i], arr[min_value] = arr[min_value], arr[i] - - -arr = [] -for i in range(1, 26): - arr.append(random.randint(1, 100)) -choise_sort(arr) -print(arr) diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_4.py b/Practice/Sam_Kilyaev/Lection_4_Task_4.py deleted file mode 100644 index 58009d5a..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_4.py +++ /dev/null @@ -1,16 +0,0 @@ -import re - -your_string = input("Write your string: ") -your_want = input("1:Replace tabs with spaces 2:Replace spaces with tabs - ") - - -def replace(string, want): - if want == "1": - result = re.sub('\t', ' ', string) - print(result) - elif want == "2": - result = re.sub(' {4}', '\t', string) - print(result) - - -replace(your_string, your_want) diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_5.py b/Practice/Sam_Kilyaev/Lection_4_Task_5.py deleted file mode 100644 index 3f44d3b4..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_5.py +++ /dev/null @@ -1,12 +0,0 @@ -string = input("Wrote your string: ") -dictionary = {"Ivan": "Gandalf", "Sergey": "Aragorn", - "Nikolay": "Golum", "Vladimir": "Sauron", - "Dmitriy": "Frodo", "Maksim": "Teodan"} - - -def replace_name(string, dictionary): - for key, value in dictionary.items(): - string = string.replace(key, value) - - -print(replace_name(string)) diff --git a/Practice/Sam_Kilyaev/Lection_4_Task_6.py b/Practice/Sam_Kilyaev/Lection_4_Task_6.py deleted file mode 100644 index fadd26dd..00000000 --- a/Practice/Sam_Kilyaev/Lection_4_Task_6.py +++ /dev/null @@ -1,44 +0,0 @@ -import random - -len_of_matrix = int(input("Write len of matrix: ")) -high_of_matrix = int(input("Write high of matrix: ")) -your_number = int(input("Write number: ")) - - -def make_matrix(len_of_matrix=3, high_of_matrix=5): - A = [[0] * len_of_matrix for i in range(high_of_matrix)] - - for i in range(high_of_matrix): - for j in range(len_of_matrix): - A[i][j] = random.randint(0, 10) - - for i in A: - print(f"{i}", end='') - print() - return A - - -def find_num_for_delete(matrix, num_delete): - for i in matrix: - for j in i: - if j == num_delete: - delete_column(i, j, matrix, num_delete) - - -def delete_column(i, j, matrix, num_delete): - index = i.index(j) - for a in matrix: - del a[index] - find_num_for_delete(matrix, num_delete) - - -def print_matrix(matrix): - for i in matrix: - print(f"{i}", end='') - print() - - -arr = make_matrix(len_of_matrix, high_of_matrix) -matrix_test = [[1, 2, 2], [3, 4, 5]] -find_num_for_delete(matrix_test, 2) -print_matrix(matrix_test) diff --git a/Practice/Sam_Kilyaev/Lection_5_Task_1.py b/Practice/Sam_Kilyaev/Lection_5_Task_1.py deleted file mode 100644 index 107cb1f2..00000000 --- a/Practice/Sam_Kilyaev/Lection_5_Task_1.py +++ /dev/null @@ -1,11 +0,0 @@ -class Man: - def __init__(self, name): - self.name = name - - def solve_task(self): - print("I'm not ready yet") - - -Human = Man("Peter") -Human.solve_task() -print(Human.name) diff --git a/Practice/Sam_Kilyaev/Lection_5_Task_2.py b/Practice/Sam_Kilyaev/Lection_5_Task_2.py deleted file mode 100644 index f2ea2503..00000000 --- a/Practice/Sam_Kilyaev/Lection_5_Task_2.py +++ /dev/null @@ -1,17 +0,0 @@ -import time -import random -from Lection_5_Task_1 import Man - - -class Pupil(Man): - def __init__(self, name): - super(Pupil, self).__init__(name) - - def solve_task(self): - time.sleep(random.randint(3, 7)) - print("I'm ready now?") - - -Jak = Pupil("Vopel") -Jak.solve_task() -print(Jak.name) diff --git a/Practice/Sam_Kilyaev/Lection_5_Task_3.py b/Practice/Sam_Kilyaev/Lection_5_Task_3.py deleted file mode 100644 index 6c486346..00000000 --- a/Practice/Sam_Kilyaev/Lection_5_Task_3.py +++ /dev/null @@ -1,34 +0,0 @@ -import tempfile -import os - - -class WrapStrToFile: - def __init__(self): - self.filepath = tempfile.mktemp() - - @property - def content(self): - try: - with open(self.filepath, "r") as self.fp: - return self.fp.read() - - except OSError: - return "File not found" - - @content.setter - def content(self, value): - self.value = value - with open(self.filepath, "w") as self.fp: - self.fp.write(self.value) - - @content.deleter - def content(self): - os.remove(self.filepath) - - -A = WrapStrToFile() -print(A.content) -A.content = 'Hello World' -print(A.content) -del A.content -print(A.content) diff --git a/Practice/Sam_Kilyaev/Lection_6_Task_3.py b/Practice/Sam_Kilyaev/Lection_6_Task_3.py deleted file mode 100644 index da66ee0f..00000000 --- a/Practice/Sam_Kilyaev/Lection_6_Task_3.py +++ /dev/null @@ -1,20 +0,0 @@ -import time - - -def test_func(a, b): - return a + b - - -class MyManager: - def __enter__(self): - self.start_time = time.clock() - print("Starting code inside manager") - - def __exit__(self, exc_type, exc_val, exc_tb): - self.end_time = time.clock() - self.result = self.end_time - self.start_time - print(f"Ending code inside manager. Runtime - {self.result}") - - -with MyManager(): - print(test_func(4759465804756475649736076740367485746985, 50000000000)) diff --git a/Practice/Sam_Kilyaev/Lection_6_Task_4.py b/Practice/Sam_Kilyaev/Lection_6_Task_4.py deleted file mode 100644 index 3200a2ae..00000000 --- a/Practice/Sam_Kilyaev/Lection_6_Task_4.py +++ /dev/null @@ -1,30 +0,0 @@ -import itertools - - -def options(psswd, long): - result = itertools.combinations(psswd, long) - output = [] - for i in result: - output.append(next(result)) - return output - - -psswd = 'password' -long = 4 -print(options(psswd, long)) - - -def three_massiv_to_one(*args): - my_list = list(itertools.chain(*args)) - return my_list - - -print(three_massiv_to_one([1, 2, 3], [5, 7, 6], [8, 9, 0])) - - -def massiv_5(massiv): - my_list = list(itertools.filterfalse(lambda i: len(i) < 5, massiv)) - return my_list - - -print(massiv_5(['hello', 'one', 'write'])) diff --git a/Practice/Sam_Kilyaev/Lection_7_Razminka.py b/Practice/Sam_Kilyaev/Lection_7_Razminka.py deleted file mode 100644 index aacd36a4..00000000 --- a/Practice/Sam_Kilyaev/Lection_7_Razminka.py +++ /dev/null @@ -1,40 +0,0 @@ -def reader(file): - with open(file, 'r') as my_file: - for i in my_file.readlines(): - yield i - - -l = reader('test.txt') -print(next(l)) -print(next(l)) - - -# § - символ параграфа - -class IterParagraf: - def __init__(self, text, symbol): - self.text = text - self.symbol = symbol - - def __iter__(self): - self.i = 0 - return self - - def __next__(self): - self.results = "" - while self.i != len(self.text) - 1: - self.results += self.text[self.i] - self.i += 1 - if self.text[self.i] == self.symbol: - self.i += 1 - return self.results - elif self.i == len(self.text) - 1: - self.results += self.text[self.i] - return self.results - else: - raise StopIteration - - -MyIterator = IterParagraf("We§can§do§it§this", "§") -for x in MyIterator: - print(x) \ No newline at end of file diff --git a/Practice/Sam_Kilyaev/Lection_7_Task_1.py b/Practice/Sam_Kilyaev/Lection_7_Task_1.py deleted file mode 100644 index e24f4458..00000000 --- a/Practice/Sam_Kilyaev/Lection_7_Task_1.py +++ /dev/null @@ -1,66 +0,0 @@ -import datetime -import sys - -first_date = '' -second_date = '' - - -def work_day(year1, mounth1, day1, year2, mounth2, day2): - d1 = datetime.date(year1, mounth1, day1) - d2 = datetime.date(year2, mounth2, day2) - daygenerator = (d1 + datetime.timedelta(x + 1) for x in range((d2 - d1).days)) - return sum(1 for day in daygenerator if day.weekday() < 5) - - -def reformat_dates(first_date, second_date): - count = 0 - a = first_date.split('.') - print(a) - b = second_date.split('.') - print(b) - year1 = '' - mounth1 = '' - day1 = '' - year2 = '' - mounth2 = '' - day2 = '' - for i in a: - count += 1 - print(i) - if count == 1: - year1 = int(i) - print(year1) - elif count == 2: - mounth1 = int(i) - print(mounth1) - elif count == 3: - day1 = int(i) - print(day1) - count = 0 - for j in b: - print(j) - count += 1 - if count == 1: - year2 = int(j) - elif count == 2: - mounth2 = int(j) - elif count == 3: - day2 = int(j) - print(year1, mounth1, day1, year2, mounth2, day2) - return work_day(year1, mounth1, day1, year2, mounth2, day2) - - -# Запуск программы через: Lection_7_Task_1.py [param1/2019.12.5] [param2/2019.12.30] -if __name__ == '__main__': - count = 0 - for param in sys.argv: - if count == 1: - first_date = param # 2019.12.5 - elif count == 2: - second_date = param # 2019.12.30 - elif count >= 3: - print('Extra Date') - count += 1 - -result = reformat_dates(first_date, second_date) -print(f'Work day between {first_date} and {second_date} is {result}') diff --git a/Practice/Sam_Kilyaev/Lection_7_Task_2.py b/Practice/Sam_Kilyaev/Lection_7_Task_2.py deleted file mode 100644 index 3bec6dce..00000000 --- a/Practice/Sam_Kilyaev/Lection_7_Task_2.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys -import subprocess - -file = '' - - -def read_type(file): - proc = subprocess.Popen(['type', file], shell=True) - proc.wait() - result = proc.communicate() - if proc.returncode: - print(result[1]) - return 'result', result[0] - - -if __name__ == '__main__': - count = 0 - for param in sys.argv: - if count == 1: - file = param - elif count >= 2: - print('Extra file') - count += 1 -read_type(file) diff --git a/Practice/Sam_Kilyaev/pep8task.py b/Practice/Sam_Kilyaev/pep8task.py deleted file mode 100644 index 1af7ee7c..00000000 --- a/Practice/Sam_Kilyaev/pep8task.py +++ /dev/null @@ -1,79 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * #Лучше использовать import time, или from time import конкретная функция - - -#class shuffler: Нужно использовать CapWords -class Shuffler - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): - #mp3s = [] Отступы - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - #os.rename(path + '/' + mp3), path + '/' + hashname)) Лишняя скобка в середине - os.rename(path + '/' + mp3, path + '/' + hashname) - #f = open(output, 'r') Лишние отступы - #f.write(str(self.map)) - f = open(output, 'r') - f.write(str(self.map)) - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: #Разные отступы в with, исправленный вариант - self.map = ast.literal_eval(f.read()) - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: #Разные отступы в цикле, исправленный вариант - #os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) Лишняя скобка - os.rename(path + '/' + hashname, path + '/' + self.map[hashname]) - os.remove(restore_path) - - def generateName(self, seed=time()): - #return hashlib.md5(str(seed)).hexdigest() Лишние отступы - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - #Везде одинарные кавычки, а в строке ниже двойные, не ошибка, но лучше использовать один тип везде - #restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser = subparsers.add_parser('restore', help='command_a help') - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() #Название класса с маленькой буквы - Shuffler = Shuffler() - if args.subcommand == 'rename': - if args.output: #Лишние отступы в if/else, исправленный вариант - Shuffler.rename(args.dirname, 'restore.info') # - else: - Shuffler.rename(args.dirname, args.output) # - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() diff --git a/Practice/ViktorGa/L2T1.py b/Practice/ViktorGa/L2T1.py deleted file mode 100644 index 6c118df1..00000000 --- a/Practice/ViktorGa/L2T1.py +++ /dev/null @@ -1,5 +0,0 @@ -def print_max(a, b): - print(a) if a > b else print(b) - - -print_max(6, 9) diff --git a/Practice/ViktorGa/L2T2.py b/Practice/ViktorGa/L2T2.py deleted file mode 100644 index 89516033..00000000 --- a/Practice/ViktorGa/L2T2.py +++ /dev/null @@ -1,5 +0,0 @@ -def return_max(a, b): - return a if a > b else b - - -print(return_max(6, 9)) diff --git a/Practice/ViktorGa/L4T1.py b/Practice/ViktorGa/L4T1.py deleted file mode 100644 index 4fe692df..00000000 --- a/Practice/ViktorGa/L4T1.py +++ /dev/null @@ -1,13 +0,0 @@ -def fizz_buzz(): - for i in range(1, 100): - if i % 15 == 0: - print("FizzBuzz") - elif i % 5 == 0: - print("Buzz") - elif i % 3 == 0: - print("Fizz") - else: - print(i) - - -fizz_buzz() diff --git a/Practice/ViktorGa/L4T2.py b/Practice/ViktorGa/L4T2.py deleted file mode 100644 index 3ba8a678..00000000 --- a/Practice/ViktorGa/L4T2.py +++ /dev/null @@ -1,8 +0,0 @@ -def read_number(number): - numbers = str(number) - for num, val in enumerate(numbers, 1): - print(str(num) + ' цифра = ' + str(val)) - return True - - -read_number(10819) \ No newline at end of file diff --git a/Practice/ViktorGa/L4T3.py b/Practice/ViktorGa/L4T3.py deleted file mode 100644 index 5ba95241..00000000 --- a/Practice/ViktorGa/L4T3.py +++ /dev/null @@ -1,13 +0,0 @@ -def sort(array): - for i in range(0, len(array) - 1): - pos_for_change = i - minimum = i - for j in range(i + 1, len(array)): - if array[j] < array[minimum]: - minimum = j - array[pos_for_change], array[minimum] = array[minimum], array[pos_for_change] - - -arr = [0, 3, 24, 2, 3, 7] -sort(arr) -print(arr) diff --git a/Practice/ViktorGa/L4T4.py b/Practice/ViktorGa/L4T4.py deleted file mode 100644 index 330613ab..00000000 --- a/Practice/ViktorGa/L4T4.py +++ /dev/null @@ -1,24 +0,0 @@ -def replace(source, action): - if source[-4] == '.' or source[-5] == '.': - f = open(source, 'r') - stroka = f.read() - f.close() - f = open(source, 'w') - if action == "tab": - f.write(stroka.replace(' ', '\t')) - elif action == "space": - f.write(stroka.replace('\t', ' ')) - else: - return False - f.close() - return True - else: # string - if action == "tab": - return source.replace(' ', '\t') - elif action == "space": - return source.replace('\t', ' ') - else: - return None - - -print(replace("example.txt", "tab")) diff --git a/Practice/ViktorGa/L4T5.py b/Practice/ViktorGa/L4T5.py deleted file mode 100644 index 749fc03b..00000000 --- a/Practice/ViktorGa/L4T5.py +++ /dev/null @@ -1,10 +0,0 @@ -def interpolate(string, dictionary): - for key in dictionary: - if key in string: - string = string.replace(key, dictionary[key]) - return string - - -dictionar = {'python': 'это самое', 'успел': 'опаздал', 'я': 'я опять'} -stroka = 'и вот я успел сделать python' -print(interpolate(stroka, dictionar)) diff --git a/Practice/ViktorGa/L5T1.py b/Practice/ViktorGa/L5T1.py deleted file mode 100644 index e0c9d1b3..00000000 --- a/Practice/ViktorGa/L5T1.py +++ /dev/null @@ -1,6 +0,0 @@ -class Man: - def __init__(self, name): - self._name = name - def solve_task(self): - - print("I'm not ready yet") \ No newline at end of file diff --git a/Practice/ViktorGa/L5T2.py b/Practice/ViktorGa/L5T2.py deleted file mode 100644 index bbb6448c..00000000 --- a/Practice/ViktorGa/L5T2.py +++ /dev/null @@ -1,17 +0,0 @@ -from random import randint -from time import sleep -from L5T1 import Man - - -class Pupil(Man): - def solve_task(self): - print("thinking...") - time = randint(3, 6) - sleep(time) - print("I'm ready") - - -man = Man("karlson") -man.solve_task() -pupil = Pupil("malysh") -pupil.solve_task() diff --git a/Practice/ViktorGa/L6T3.py b/Practice/ViktorGa/L6T3.py deleted file mode 100644 index ecc55003..00000000 --- a/Practice/ViktorGa/L6T3.py +++ /dev/null @@ -1,15 +0,0 @@ -import time - - -class ContManager: - def __enter__(self): - self._start = time.time() - - def __exit__(self, exc_type, exc_val, exc_tb): - print('time: {}'.format(time.time() - self._start)) - - -with ContManager(): - print("start pro") - time.sleep(3) - print("finish pro") \ No newline at end of file diff --git a/Practice/ViktorGa/L6T4.py b/Practice/ViktorGa/L6T4.py deleted file mode 100644 index deead3cf..00000000 --- a/Practice/ViktorGa/L6T4.py +++ /dev/null @@ -1,26 +0,0 @@ -from itertools import chain -from itertools import filterfalse -from itertools import combinations - - -def merge_array(arr): - result = list(chain.from_iterable(arr)) - return result - -def filter_array(arr): - result = list(filterfalse(lambda x: len(x)<5,arr)) - return result - -def combinate_text(text): - result =list(combinations(text,len(text)-4)) - return result - - -a = ([1,2,3],[4,5],[6,7]) -print(merge_array(a)) - -a = ['hello','i','write','cool','code'] -print(filter_array(a)) - -a = 'password' -print(combinate_text(a)) \ No newline at end of file diff --git a/Practice/ViktorGa/L7T1.py b/Practice/ViktorGa/L7T1.py deleted file mode 100644 index 22498f2c..00000000 --- a/Practice/ViktorGa/L7T1.py +++ /dev/null @@ -1,14 +0,0 @@ -import datetime - - -def working_days(first_data, second_data): - count = 0 - current_day = first_data - while current_day <= second_data: - if current_day.weekday() < 5: - count += 1 - current_day = current_day + datetime.timedelta(days=1) - return count - - -print(working_days(datetime.datetime(2020, 10, 2), datetime.datetime(2020, 10, 10))) diff --git a/Practice/ViktorGa/L7T2.py b/Practice/ViktorGa/L7T2.py deleted file mode 100644 index 6c5bfae7..00000000 --- a/Practice/ViktorGa/L7T2.py +++ /dev/null @@ -1,15 +0,0 @@ -import subprocess - - -def cat_file(file_name): - process = subprocess.Popen(["type", file_name], shell=True) - process.wait() - result = process.communicate() - - if process.returncode: - for line in result: - print(line) - - -if __name__ == "__main__": - cat_file("C:\Users\Виктор\PycharmProjects\L7T2\example.txt") \ No newline at end of file diff --git a/Practice/ViktorGa/L7T3.py b/Practice/ViktorGa/L7T3.py deleted file mode 100644 index 46dbbd3f..00000000 --- a/Practice/ViktorGa/L7T3.py +++ /dev/null @@ -1,50 +0,0 @@ -import random, pickle - - -class Human: - def __init__(self, name, surname, age, iq, place): - self.name = name - self.surname = surname - self.age = age - self.iq = iq - self.place = place - - def __str__(self): - return "This is {} {}, age - {}, iq - {}, place - {}". \ - format(self.name, self.surname, self.age, self.iq, self.place) - - -def create_people(people_number): - if people_number <= 0: - return None - names = ['Vova', 'Vika', 'Vera', 'Vlad', 'Vita'] - surnames = ['Dundic', 'Semih', 'Ernst', 'Pozner', 'Monday'] #surname Monday is real - place = ['Pervomaysk', 'Big Murasino', 'Vad', 'Shatki', 'Red Baki'] - people = [] - - for i in range(people_number): - human = Human(random.choice(names), random.choice(surnames), random.randint(18, 100), - random.randint(70, 140), random.choice(place)) - people.append(human) - serialize_people(people) - return people - - -def serialize_people(people): - with open('human.data', 'wb') as f: - for human in people: - pickle.dump(human, f, protocol=pickle.HIGHEST_PROTOCOL) - - -def deserialize_people(file_name, number): - with open(file_name, 'rb') as f: - people = [] - for i in range(number): - people.append(pickle.load(f)) - return people - - -create_people(5) -people = deserialize_people('human.data', 5) -for human in people: - print(human) \ No newline at end of file diff --git a/Practice/ViktorGaL9/L9T1.py b/Practice/ViktorGaL9/L9T1.py deleted file mode 100644 index 403096a3..00000000 --- a/Practice/ViktorGaL9/L9T1.py +++ /dev/null @@ -1,52 +0,0 @@ -import multiprocessing -import threading -import time - - -def find_primes(start, end): - lst = [] - for i in range(start, end + 1): - for j in range(2, i): - if i % j == 0: - break - else: - lst.append(i) - print(len(lst)) - return lst - - -if __name__ == "__main__": - - start_time = time.time() - find_primes(3, 10000) - find_primes(10001, 20000) - find_primes(20001, 30000) - work_time = time.time() - start_time - print(work_time) - - start_time = time.time() - threads = [threading.Thread(target=find_primes, args=(3, 10000)), - threading.Thread(target=find_primes, args=(10001, 20000)), - threading.Thread(target=find_primes, args=(20001, 30000))] - for thread in threads: - thread.start() - for thread in threads: - thread.join() - work_time = time.time() - start_time - print(work_time) -#Если не сделать thread.start(), то не запустятяся потоки, выдает ошибку. -#Если не сделать thread.join(), то он неправильно посчитает время, т.к. уже не ждет завершения. - - start_time = time.time() - processes = [multiprocessing.Process(target=find_primes, args=(3, 10000)), - multiprocessing.Process(target=find_primes, args=(10001, 20000)), - multiprocessing.Process(target=find_primes, args=(20001, 30000))] - for process in processes: - process.start() - for process in processes: - process.join() - work_time = time.time() - start_time - print(work_time) -#Если не сделать process.start(), то выдаст ошибку с атрибутом wait, не запустится. -#Если не сделать process.join(), то неправильно считает время, не дожидается завершения. -#Итого: последовательно 7.465 с, паралл. поток 6.484 с, паралл. проц 5.122 - процесс самый быстрый diff --git a/Practice/ViktorGaL9/L9T2.py b/Practice/ViktorGaL9/L9T2.py deleted file mode 100644 index ec557c5d..00000000 --- a/Practice/ViktorGaL9/L9T2.py +++ /dev/null @@ -1,34 +0,0 @@ -import multiprocessing - -def sum_mixer(*args): - for i in range(len(args)): - if not isinstance(args[i], type(args[0])): - raise TypeError - if isinstance(args[0], list): - new_list = [] - for i in range(len(args)): - new_list += args[i] - print(len(new_list)) - return new_list - elif isinstance(args[0], int): - print(sum(args)) - return sum(args) - elif isinstance(args[0], str): - new_str = "" - for i in range(len(args)): - new_str += args[i] - print(str(new_str)) - return new_str - else: - return 1 - - -if __name__ == "__main__": - - processes = [multiprocessing.Process(target=sum_mixer, args=([0, 2, 9])), - multiprocessing.Process(target=sum_mixer, args=(1, 0, 00, 2, 1)), - multiprocessing.Process(target=sum_mixer, args=("py", "th", "on"))] - for process in processes: - process.start() - for process in processes: - process.join() diff --git "a/Practice/amuratshin/lec3_practice/\321\201hoose.py" "b/Practice/amuratshin/lec3_practice/\321\201hoose.py" deleted file mode 100644 index 6fce2240..00000000 --- "a/Practice/amuratshin/lec3_practice/\321\201hoose.py" +++ /dev/null @@ -1,19 +0,0 @@ -#программа должна загадывать число, пользователь должен угадывать -import random - - -def choose(): - number = random.randint(1, 10) - while True: - guess = int(input("Введите целое число: ")) - if guess == number: - print("Поздравляю, вы угадали") - break - elif guess < number: - print("Нет, загаданное число немного больше этого") - else: - print("Нет, загаданное число немного меньше этого") - print("Завершено") - - -choose() diff --git "a/Practice/amuratshin/lec3_practice/\321\201ompare.py" "b/Practice/amuratshin/lec3_practice/\321\201ompare.py" deleted file mode 100644 index 6574125f..00000000 --- "a/Practice/amuratshin/lec3_practice/\321\201ompare.py" +++ /dev/null @@ -1,14 +0,0 @@ - -numFirst = int(input('Введите первое число:')) -numSecond = int(input('Введите второе число:')) - -def intMoreThan(numFirst, numSecond): - """ функция сравнивает два числа""" - if numFirst < numSecond: - print(numSecond) - elif numFirst > numSecond: - print(numFirst) - else: - print(' Числа равны') - -intMoreThan() diff --git a/Practice/amuratshin/lec4_practice/FizzBuzz.py b/Practice/amuratshin/lec4_practice/FizzBuzz.py deleted file mode 100644 index 5e038dc8..00000000 --- a/Practice/amuratshin/lec4_practice/FizzBuzz.py +++ /dev/null @@ -1,9 +0,0 @@ -for i in range(1, 101): - if i % 3 == 0 and i % 5 == 0: - print("FuzzBuzz") - elif i % 5 == 0: - print("Buzz") - elif i % 3 == 0: - print("Fuzz") - else: - print(i) \ No newline at end of file diff --git a/Practice/amuratshin/lec4_practice/dict.py b/Practice/amuratshin/lec4_practice/dict.py deleted file mode 100644 index f67d96bf..00000000 --- a/Practice/amuratshin/lec4_practice/dict.py +++ /dev/null @@ -1,9 +0,0 @@ -d = {"cat": "кошка", "table": "стол"} - -f = open("myfile.txt", "r") - -for line in f: - for k, v in d.items(): - line = line.replace(k, v) - line = line.replace(k.capitalize(), v.capitalize()) - print(line) diff --git a/Practice/amuratshin/pep8task.py b/Practice/amuratshin/pep8task.py deleted file mode 100644 index 262610f9..00000000 --- a/Practice/amuratshin/pep8task.py +++ /dev/null @@ -1,72 +0,0 @@ -import os # порядок импорты стандартной библиотеки \ сторонних библиотек \ импорты модулей текущего проекта -import sys # пробелы между группами импорта - -import hashlib -import ast -import argparse - -from fileinput import filename -from time import * - # 2 строки между блоком import и началом блока кода - -class Shuffler: # имена классов вида CamelCase - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): - mp3s = [] # выравнивание-отступы - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - os.rename(path + '/' + mp3, path + '/' + hashname) # два лишних закрывающих пробела в строке - f = open(output, 'r') # выравнивание-отступы - f.write(str(self.map)) - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: # использование filename без импорта - self.map = ast.literal_eval(f.read()) - mp3s = [] # выравнивание-отступы - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: - os.rename(path + '/' + hashname, path + '/' + self.map[hashname]) # лишняя скобка - os.remove(restore_path) - - def generate_name(self, seed=time()): # выравнивание-отступы и отсутствует ':' - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - shuffler = Shuffler() # имя экемпляра класса с маленькой а имя класса с заглавной - if args.subcommand == 'rename': - if args.output: - shuffler.rename(args.dirname, 'restore.info') - else: - shuffler.rename(args.dirname, args.output) - elif args.subcommand == 'restore': - shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() diff --git a/Practice/aulov_r/10lec1_client.py b/Practice/aulov_r/10lec1_client.py deleted file mode 100644 index 8a39e316..00000000 --- a/Practice/aulov_r/10lec1_client.py +++ /dev/null @@ -1,8 +0,0 @@ -import socket -import pickle - -data = ['first', 'second', 'third'] -s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) -s.sendto(pickle.dumps(data), ('127.0.0.1', 12345)) -print(*pickle.loads(s.recv(1024))) -s.close() \ No newline at end of file diff --git a/Practice/aulov_r/10lec1_server.py b/Practice/aulov_r/10lec1_server.py deleted file mode 100644 index edccf809..00000000 --- a/Practice/aulov_r/10lec1_server.py +++ /dev/null @@ -1,16 +0,0 @@ -import socket -import pickle - - -def decrypt(enc_words): - return [dec_dict[word] for word in enc_words] - - -dec_dict = {'first': 'one', 'second': 'two', 'third': 'three'} - -s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) -s.bind(('127.0.0.1', 12345)) - -while True: - data, address = s.recvfrom(1024) - s.sendto(pickle.dumps(decrypt(pickle.loads(data))), address) \ No newline at end of file diff --git a/Practice/aulov_r/2lec1.py b/Practice/aulov_r/2lec1.py deleted file mode 100644 index cbbc2d22..00000000 --- a/Practice/aulov_r/2lec1.py +++ /dev/null @@ -1,8 +0,0 @@ -def func(one, two): - if one >= two: - return one - else: - return two -a = int(input('введите первое число: ')) -b = int(input('введите второе число: ')) -print(func(a, b)) diff --git a/Practice/aulov_r/2lec2.py b/Practice/aulov_r/2lec2.py deleted file mode 100644 index 93a73172..00000000 --- a/Practice/aulov_r/2lec2.py +++ /dev/null @@ -1,10 +0,0 @@ -def max_numb(a, b): - if a > b: - print(a) - elif a == b: - print('числа равны') - else: - print(b) -x = int(input('введите первое число: ')) -y = int(input('введите второе число: ')) -max_numb(x, y) diff --git a/Practice/aulov_r/4lec1.py b/Practice/aulov_r/4lec1.py deleted file mode 100644 index 17e4d821..00000000 --- a/Practice/aulov_r/4lec1.py +++ /dev/null @@ -1,9 +0,0 @@ -for i in range(1,101): - if (i%15)==0: - print('FizzBuzz') - elif (i%3)==0: - print('Fizz') - elif (i%5)==0: - print('Buzz') - else: - print(i) diff --git a/Practice/aulov_r/4lec2.py b/Practice/aulov_r/4lec2.py deleted file mode 100644 index 9558a84f..00000000 --- a/Practice/aulov_r/4lec2.py +++ /dev/null @@ -1,3 +0,0 @@ -num = input('число пожалуйста: ') -for i in range(len(num)): - print(f"{i+1} число будет = {num[i]}") diff --git a/Practice/aulov_r/4lec3.py b/Practice/aulov_r/4lec3.py deleted file mode 100644 index 1fb66ea8..00000000 --- a/Practice/aulov_r/4lec3.py +++ /dev/null @@ -1,21 +0,0 @@ -from random import randint -def choice(array): - for i in range(len(array) - 1): - m = i - b = i + 1 - while b < len(array): - if array[b] < array[m]: - m = b - b = b + 1 - array[i], array[m] = array[m], array[i] - - -arr = [] -for i in range(6): - arr.append(randint(1, 99)) - -print(arr) -choice(arr) -print(arr) - - diff --git a/Practice/aulov_r/4lec4.py b/Practice/aulov_r/4lec4.py deleted file mode 100644 index 93cadf06..00000000 --- a/Practice/aulov_r/4lec4.py +++ /dev/null @@ -1,17 +0,0 @@ -def roll_up(file): - for line in file: - line = line.replace(' ', ' ') - print(line) - -def deploy(file): - for line in file: - line = line.replace(' ', ' ') - print(line) - -a = open("file1.txt", "r+") -cmd = int(input("Введите команду 1 - меняем пробелы на табуляцию; 2 - меняем табуляцию на пробелы: ")) -if cmd == 1: - roll_up(a) -else: - deploy(a) -a.close() diff --git a/Practice/aulov_r/4lec5.py b/Practice/aulov_r/4lec5.py deleted file mode 100644 index 5fafc0b5..00000000 --- a/Practice/aulov_r/4lec5.py +++ /dev/null @@ -1,7 +0,0 @@ -a = 'cat is better than dog' -b = {'cat': 'кошка','dog': 'собака'} -for i in b: - a = a.replace(i, b[i]) -print(a) - - diff --git a/Practice/aulov_r/5lec1.py b/Practice/aulov_r/5lec1.py deleted file mode 100644 index fa80875b..00000000 --- a/Practice/aulov_r/5lec1.py +++ /dev/null @@ -1,7 +0,0 @@ -class Man: - def __init__(self, name): - self.name = name - def solve_task(self): - print("I'm not ready yet") -a = Man('') -a.solve_task() diff --git a/Practice/aulov_r/5lec2.py b/Practice/aulov_r/5lec2.py deleted file mode 100644 index 910d7b14..00000000 --- a/Practice/aulov_r/5lec2.py +++ /dev/null @@ -1,17 +0,0 @@ -import random as rdm -import time - -class Man: - def __init__(self, name): - self.name = name - def solve_task(self): - print("I'm not ready yet") - -class Pupil(Man): - def solve_task(self): - time.sleep(rdm.randint(3, 6)) - print("I'm not ready yet") -a = Man('') -a.solve_task() -b = Pupil('') -b.solve_task() diff --git a/Practice/aulov_r/5lec3.py b/Practice/aulov_r/5lec3.py deleted file mode 100644 index 071d3e5a..00000000 --- a/Practice/aulov_r/5lec3.py +++ /dev/null @@ -1,25 +0,0 @@ -import tempfile - -class WrapStrToFIle: - def __init__(self): - self._filepath = tempfile.mkstemp() - - @property - def content(self): - try: - a = open(self.__filepath[1]) - return a.read() - except FileNotFoundError: - print('not file') - - @content.setter - def content(self, value): - a = open(self._filepath[1], 'w') - a.write(value) - - @content.deleter - def content(self): - self._filepath = 'delete file' - -b = WrapStrToFIle() -b.content diff --git a/Practice/aulov_r/6lec3.py b/Practice/aulov_r/6lec3.py deleted file mode 100644 index 37fe2386..00000000 --- a/Practice/aulov_r/6lec3.py +++ /dev/null @@ -1,18 +0,0 @@ -import time - -class Time: - def __init__(self): - self.start_time = 0 - - def __enter__(self): - self.start_time = time.perf_counter() - - def __exit__(self, exc_type, exc_val, exc_tb): - self.end_time = time.perf_counter() - self.start_time - print('Сколько времени прошло {}'.format(self.end_time)) - - -with Time(): - lst = [] - for i in range(1, 10000000): - lst.append(i ** 2) diff --git a/Practice/aulov_r/6lec4.py b/Practice/aulov_r/6lec4.py deleted file mode 100644 index fbd86b59..00000000 --- a/Practice/aulov_r/6lec4.py +++ /dev/null @@ -1,5 +0,0 @@ -import itertools as it -print(list(it.chain([1, 2, 3], [4, 5], [6, 7]))) -print(list(it.filterfalse(lambda i: len(i) < 5, - ['hello', 'i', 'write', 'cool', 'code']))) -print(list(it.combinations("password", 4))) diff --git a/Practice/aulov_r/7lec1.py b/Practice/aulov_r/7lec1.py deleted file mode 100644 index b8282b5d..00000000 --- a/Practice/aulov_r/7lec1.py +++ /dev/null @@ -1,20 +0,0 @@ -from _datetime import datetime,date - -a = input('Entered date гггг,мм,дд :') -a = a.split(',') -a = date(int(a[0]), int(a[1]), int(a[2])) -b = input('Entered date гггг,мм,дд :') -b = b.split(',') -b = date(int(b[0]), int(b[1]), int(b[2])) -cc = ((b - a).days) -w = datetime.weekday(a) -working_day = [] -for i in range(cc + 1): - if w < 5: - working_day.append(w) - w += 1 - elif w > 5: - w = 0 - else: - w += 1 -print('Number of working day ' + str(len(working_day))) diff --git a/Practice/aulov_r/7lec2.py b/Practice/aulov_r/7lec2.py deleted file mode 100644 index a8ff1c7b..00000000 --- a/Practice/aulov_r/7lec2.py +++ /dev/null @@ -1,8 +0,0 @@ -import subprocess - - -def read(file): - subprocess.run(['type', file], shell=True) - - -read(r"C:\text.txt") \ No newline at end of file diff --git a/Practice/aulov_r/8lec3.py b/Practice/aulov_r/8lec3.py deleted file mode 100644 index 51a22166..00000000 --- a/Practice/aulov_r/8lec3.py +++ /dev/null @@ -1,28 +0,0 @@ -def range(*num): - if not all(isinstance(arg, int) for arg in num): - raise TypeError('Только целые числа') - start, step = 0, 1 - if len(num) == 1: - result = num - elif len(num) == 2: - start, result = num - elif len(num) == 3: - start, result, step = num - if step == 0: - raise ValueError('Arg yне должно быть нулем') - else: - raise TypeError('Необходимо 3 arg') - - a = start - if step > 0: - while a < result: - yield a - a += step - else: - while a > result: - yield a - a += step - - -print(*range(2, 17, 2)) -print(*range(-5, -15, -3)) diff --git a/Practice/aulov_r/8lec5.py b/Practice/aulov_r/8lec5.py deleted file mode 100644 index d3170a80..00000000 --- a/Practice/aulov_r/8lec5.py +++ /dev/null @@ -1,9 +0,0 @@ -def count_symbol(st, smb): - a = 0 - for char in st: - if char == smb: - a += 1 - return a - - -print(count_symbol("Hi, Elvis, I am here!", "i")) \ No newline at end of file diff --git a/Practice/aulov_r/9lec1.py b/Practice/aulov_r/9lec1.py deleted file mode 100644 index dd9e50ed..00000000 --- a/Practice/aulov_r/9lec1.py +++ /dev/null @@ -1,38 +0,0 @@ -import math -import threading -import multiprocessing -import time - -def find_primes(start, end): - a = [] - for b in range(start, end + 1): - if all(b % i != 0 for i in range(2, int(math.sqrt(b)) + 1)): - a.append(b) - return a - -if __name__ == '__main__': - start_t = time.time() - find_primes(3, 100000) - find_primes(100001, 200000) - find_primes(200001, 300000) - print('Время выполнения: ', time.time() - start_t) - - start_t = time.time() - threads = [threading.Thread(target=find_primes, args=(3, 100000)), - threading.Thread(target=find_primes, args=(100001, 200000)), - threading.Thread(target=find_primes, args=(200001, 300000))] - for thread in threads: - thread.start() - for thread in threads: - thread.join() - print('Многопоточность время выполнения: ', time.time() - start_t) - - start_t = time.time() - processes = [multiprocessing.Process(target=find_primes, args=(3, 100000)), - multiprocessing.Process(target=find_primes, args=(100001, 200000)), - multiprocessing.Process(target=find_primes, args=(200001, 300000))] - for process in processes: - process.start() - for process in processes: - process.join() - print('Многопроцессорная обработка время выполнения: ', time.time() - start_t) \ No newline at end of file diff --git a/Practice/aulov_r/pep8.py b/Practice/aulov_r/pep8.py deleted file mode 100644 index e67fe448..00000000 --- a/Practice/aulov_r/pep8.py +++ /dev/null @@ -1,72 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from fileinput import filename -from time import * - - -class Shuffler: # class shuffler меняем на class Shuffler - - def __init__(self): - self.map = {} - - def rename(self, dir_name, output): # dirname поменять dir_name - mp3s = [] # сдвинуть на 2 пробела назад - - for root, directories, files in os.walk(dir_name): # dirname на dir_name - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hash_name = self.generateName() + '.mp3' # hashname на hash_name - self.map[hash_name] = mp3 # hashname на hash_name - os.rename(path + '/' + mp3, path + '/' + hash_name) # удалил скобки в средине и в конце, и заменить hashname на hash_name - f = open(output, 'r') # удалить пробелы - f.write(str(self.map)) # удалить пробелы - - def restore(self, dir_name, restore_path): # dirname поменять dir_name - with open(filename, '+') as f: # удалить 2 пробела. Импорт filename, добавляется from fileinput import filename - self.map = ast.literal_eval(f.read()) - mp3s = [] # добавить на пробелы - - for root, directories, files in os.walk(dir_name): # dirname поменять dir_name - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hash_name in mp3s: # hashname на hash_name - os.rename(path + '/' + hash_name, path + '/' + self.map[hash_name])) # удалить одну скобку в конце и заменить на hash_name - os.remove(restore_path) # добавить пробелы - def generate_name(self, seed=time()): # generateName менять на generate_name - return hashlib.md5(str(seed)).hexdigest() # удалить пробелы - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dir_name') # dirname поменять dir_name - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dir_name') # dirname поменять dir_name - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - - -def main(): - args = parse_arguments() - shuffler = Shuffler() # замена на shuffler = Shuffler() - if args.subcommand == 'rename': - if args.output: - shuffler.rename(args.dir_name, 'restore.info') - else: - shuffler.rename(args.dir_name, args.output) - elif args.subcommand == 'restore': - shuffler.restore(args.dir_name, args.restore_map) - else: - sys.exit() - - -main() \ No newline at end of file diff --git a/Practice/ekaryagin/lab2.py b/Practice/ekaryagin/lab2.py deleted file mode 100644 index 9a99a981..00000000 --- a/Practice/ekaryagin/lab2.py +++ /dev/null @@ -1,27 +0,0 @@ -def who_is_bigger_print (first_num, second_num): - if first_num > second_num: - print(f'{first_num} is bigger') - elif second_num > first_num: - print(f'{second_num} is bigger') - else: - print(f'{first_num} are equal {second_num}') - - -who_is_bigger_print(7, 5) -who_is_bigger_print(5, 7) -who_is_bigger_print(7, 7) - - -def return_biggest_number(number_1, number_2): - if number_1 > number_2: - return number_1 - elif number_2 > number_1: - return number_2 - else: - return None - - -print(return_biggest_number(4, 5)) -print(return_biggest_number(5, 4)) -print(return_biggest_number(5, 5)) - diff --git a/Practice/ekaryagin/lab4.py b/Practice/ekaryagin/lab4.py deleted file mode 100644 index c3d96a58..00000000 --- a/Practice/ekaryagin/lab4.py +++ /dev/null @@ -1,118 +0,0 @@ -import re - - -# Напишите программу, которая выводит на экран числа от 1 до 100 При этом вместо чисел, -# кратных трем, программа должна выводить слово Fizz а вместо чисел, кратных пяти -# слово Buzz Если число кратно пятнадцати, то программа должна выводить слово FizzBuzz - -def fizz_buzz(): - for i in range(1, 101): - if i % 15 == 0: - print('FizzBuzz') - elif i % 5 == 0: - print('Buzz') - elif i % 3 == 0: - print('Fizz') - else: - print(i) - - -fizz_buzz() - - -# Составить программу, которая будет считывать введённое пятизначное число После чего, -# каждую цифру этого числа необходимо вывести в новой строке - -def number_line_by_line(number): - count = 1 - for i in number: - print(f'{count} number is {i}') - count += 1 - - -your_number = input('Input your number: ') - -number_line_by_line(your_number) - - -# Реализовать алгоритм сортировки выбором. Алгоритм состоит из следующих шагов -# 1 найти наименьший элемент в массиве -# 2 поменять местами его и первый элемент в массиве -# 3 найти следующий наименьший элемент в массиве -# 4 и поменять местами его и второй элемент массива -# 5 продолжать это пока весь массив не будет отсортирован - -def arr_sort(arr): - for i in range(len(arr)): - min = i - for j in range(i + 1, len(arr)): - if arr[j] < arr[min]: - min = j - arr[i], arr[min] = arr[min], arr[i] - - -array = [19, 15, 27, 8, 0, 21] - -arr_sort(array) -print(array) - - -# Реализовать функциональность, которая бы “сворачивала и разворачивала“ символы -# табуляции в файле или строке То есть, передается на вход файл или строка, необходимо -# заменить все символы табуляции на четыре пробела, либо же заменить все комбинации из -# четырех символов пробела на символ табуляции - -def tabulator(string, tab_to_space=True): - if tab_to_space == True: - new_string = re.sub('\t', ' ', string) - else: - new_string = re.sub(' ', '\t', string) - - return new_string - - -print(tabulator('Hello\tworld')) -print(tabulator('Hello world', False)) - - -# Интерполировать некие шаблоны в строке Есть строка с определенного вида -# форматированием необходимо заменить в этой строке все вхождения шаблонов на их -# значение из словаря - -def substitution(string): - dictionary = {'плохое': 'хорошее', 'сомнительный': 'надежный'} - for key, value in dictionary.items(): - string = string.replace(key, value) - print(string) - -str = 'Сейчас плохое время для заключения сделки. Вы сомнительный партнер.' - -substitution(str) - -# Есть список списков ( Каждый внутренний список это строка матрицы -# Необходимо реализовать функцию, которая удаляет столбец, который содержит заданную -# цифру - -def correcting_matrix(matrix, number): - for i in matrix: - j = 0 - while j < len(i): - if i[j] == number: - delete_column(matrix, j) - j -= 1 - j += 1 - return matrix - - -def delete_column(matrix, j): - for i in range(len(matrix)): - matrix[i].pop(j) - - -exaple1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]] -exaple2 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]] -exaple3 = [[1, 2, 2, 0], [4, 5, 6, 1], [7, 8, 9, 2]] - -print(correcting_matrix(exaple1, 5)) -print(correcting_matrix(exaple2, 1)) -print(correcting_matrix(exaple3, 2)) diff --git a/Practice/ekaryagin/lab5.py b/Practice/ekaryagin/lab5.py deleted file mode 100644 index c5b02532..00000000 --- a/Practice/ekaryagin/lab5.py +++ /dev/null @@ -1,93 +0,0 @@ -import random -import time -import os -import tempfile - - -# Написать класс Man который принимает имя в конструкторе Имеет -# метод solve_task который просто выводит I'm not ready yet - -class Man: - def __init__(self, name): - self.name = name - - def solve_task(self): - print('I am not ready yet') - - -first_man = Man("Master") -first_man.solve_task() -print(first_man.name) - - -# Написать класс Pupil у которого переопределен метод solve_task На -# этот раз он будет думать от 3 до 6 секунд (c помощью метода sleep -# библиотеки time и randint библиотеки random - -class Pupil(Man): - def __init__(self, name): - super(Pupil, self).__init__(name) - - def solve_task(self): - time.sleep(random.randint(3, 6)) - print('Am I ready now?') - - -second_man = Pupil("Yeshua") -second_man.solve_task() -print(second_man.name) - - -# Написать класс WrapStrToFIle который будет иметь одно -# вычисляемое свойство property под названием content В -# конструкторе класс должен инициализовать атрибут filepath путем -# присваивания результата функции mktemp библиотеки tempfile При -# попытке чтения свойства content должен внутри кода свойства -# открываться файл, используя атрибут filepath (с помощью функции -# open из этого файла читается все содержимое и возвращается из -# свойства Если файл не существует, то возникает ошибка, поэтому -# должна быть обертка вокруг открытия файла на чтение -# try except с помощью которого будет возвращаться 'Файл еще не -# существует' При присваивании значения свойству content файл по -# указанному пути должен открываться на запись и записываться -# содержимое Не забудьте закрывать файл после чтения или записи -# При удалении атрибута content должен удаляться и файл - -class WrapStrToFile: - def __init__(self): - self.filepath = tempfile.mktemp() - - @property - def content(self): - try: - file = open(self.filepath, 'r') - string = file.read() - file.close() - return string - - except OSError: - return "File not found" - - @content.setter - def content(self, value): - try: - file = open(self.filepath, 'w') - file.write(value) - file.close() - except Exception as ex: - print("Unexpected error: {}".format(ex)) - - @content.deleter - def content(self): - try: - os.remove(self.filepath) - except Exception as ex: - print("Unexpected error: {}".format(ex)) - - -first = WrapStrToFile() -print(first.content) -first.content = 'Test' -print(first.content) -del first.content -print(first.content) diff --git a/Practice/ekaryagin/pep8task_.py b/Practice/ekaryagin/pep8task_.py deleted file mode 100644 index f757f664..00000000 --- a/Practice/ekaryagin/pep8task_.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * # лучше импортировать конкретные функции или использовать import time - - -class shuffler: # изменить имя класса на Shuffler - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): # изменить dirname на dir_name - mp3s = [] # лишние два пробела в начале строки - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' # изменить hashname на hash_name - self.map[hashname] = mp3 - os.rename(path + '/' + mp3), path + '/' + hashname)) # удалить лишние закрывающие скобки в середине и в конце - f = open(output, 'r') # лишние два пробела в начале строки - f.write(str(self.map)) # лишние два пробела в начале строки - - def restore(self, dirname, restore_path): # изменить dirname на dir_name - with open(filename, '+') as f: # лишние два пробела в начале строки - self.map = ast.literal_eval(f.read()) - mp3s = [] # добавить два пробела в начале строки - for root, directories, files in os.walk(dirname): # изменить dirname на dir_name - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: # изменить hashname на hash_name - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) # удалить лишнюю закрывающую скобку - os.remove(restore_path) - - def generateName(self, seed=time()): # Изменить generateName на generate_name и удалить лишний пробел в начале строки - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') # изменить dirname на dir_name - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") # лучше использовать везде один тип ковычек "" или '' - restore_parser.add_argument('dirname') # изменить dirname на dir_name - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() # изменить на shuffler = Shuffler() - if args.subcommand == 'rename': - if args.output: # лишние два пробела в начале строки - Shuffler.rename(args.dirname, 'restore.info') # лишние четыре пробела в начале строки - else: # лишние два пробела в начале строки - Shuffler.rename(args.dirname, args.output) # лишние четыре два пробела в начале строки - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() diff --git a/Practice/o_komissarova/for_lec10/task1/Client.py b/Practice/o_komissarova/for_lec10/task1/Client.py deleted file mode 100644 index 4088c95b..00000000 --- a/Practice/o_komissarova/for_lec10/task1/Client.py +++ /dev/null @@ -1,25 +0,0 @@ -import socket -import json - - -class Client: - def __init__(self, host, port, encoded_list): - self.host = host - self.port = port - self.encoded_list = encoded_list - self._socket = None - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect((self.host, self.port)) - self._socket.send(json.dumps(self.encoded_list).encode()) - data = self._socket.recv(1024).decode() - decoded_list = json.loads(data) - print('Received: {}'.format(decoded_list)) - self._socket.close() - - -if __name__ == '__main__': - encoded_list = ['pdqb', 'gliihuhqw', 'zrugv'] - my_client = Client('127.0.0.1', 5555, encoded_list) - my_client.run() diff --git a/Practice/o_komissarova/for_lec10/task1/Server.py b/Practice/o_komissarova/for_lec10/task1/Server.py deleted file mode 100644 index e5fe16e9..00000000 --- a/Practice/o_komissarova/for_lec10/task1/Server.py +++ /dev/null @@ -1,88 +0,0 @@ -import threading -import socket -import json - - -class ClientThread(threading.Thread): - def __init__(self, conn, addr): - super().__init__() - self._connection = conn - self._address = addr - self.decode_dict = { - 'd': 'a', - 'e': 'b', - 'f': 'c', - 'g': 'd', - 'h': 'e', - 'i': 'f', - 'j': 'g', - 'k': 'h', - 'l': 'i', - 'm': 'j', - 'n': 'k', - 'o': 'l', - 'p': 'm', - 'q': 'n', - 'r': 'o', - 's': 'p', - 't': 'q', - 'u': 'r', - 'v': 's', - 'w': 't', - 'x': 'u', - 'y': 'v', - 'z': 'w', - 'a': 'x', - 'b': 'y', - 'c': 'z' - } - - def run(self): - print('Connection from address {}'.format(self._address)) - data = self._connection.recv(1024).decode() - encoded_list = json.loads(data) - decoded_list = [] - for word in encoded_list: - decoded_word = '' - for i in word: - decoded_word += self.decode_dict[i] - decoded_list.append(decoded_word) - print('Received {}'.format(encoded_list)) - print('Decoded {}'.format(decoded_list)) - self._connection.send(json.dumps(decoded_list).encode()) - self._connection.close() - print('Closed connection from {}'.format(self._address)) - - -class Server: - def __init__(self, host, port): - self.host = host - self.port = port - self._socket = None - self._runnning = False - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self._socket.bind((self.host, self.port)) - self._socket.listen(5) - self._runnning = True - - print('Server is up') - while self._runnning: - conn, addr = self._socket.accept() - ClientThread(conn, addr).start() - - def stop(self): - self._runnning = False - self._socket.close() - print('Server is down') - - -if __name__ == '__main__': - srv = Server(host='127.0.0.1', port=5555) - try: - srv.run() - except KeyboardInterrupt: - srv.stop() - diff --git a/Practice/o_komissarova/for_lec10/task2/Client.py b/Practice/o_komissarova/for_lec10/task2/Client.py deleted file mode 100644 index 9ba85ddd..00000000 --- a/Practice/o_komissarova/for_lec10/task2/Client.py +++ /dev/null @@ -1,26 +0,0 @@ -import pickle -import socket -from Practice.o_komissarova.for_lec8.task9 import User - - -class Client: - def __init__(self, host, port, user): - self.host = host - self.port = port - self.user = user - self._socket = None - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect((self.host, self.port)) - self._socket.send(pickle.dumps(self.user)) - self._socket.close() - - -if __name__ == '__main__': - user_John = User('John', 25) - user_Jack = User('Jack', 30) - my_client1 = Client('127.0.0.1', 5555, user_John) - my_client1.run() - my_client2 = Client('127.0.0.1', 5555, user_Jack) - my_client2.run() diff --git a/Practice/o_komissarova/for_lec10/task2/Server.py b/Practice/o_komissarova/for_lec10/task2/Server.py deleted file mode 100644 index 83b6e168..00000000 --- a/Practice/o_komissarova/for_lec10/task2/Server.py +++ /dev/null @@ -1,51 +0,0 @@ -import pickle -import threading -import socket - - -class ClientThread(threading.Thread): - def __init__(self, conn, addr): - super().__init__() - self._connection = conn - self._address = addr - - def run(self): - print('Connection from address {}'.format(self._address)) - data = self._connection.recv(1024) - user = pickle.loads(data) - print('Received user - name: {}, age: {}'.format(user.getName(), user.getAge())) - self._connection.close() - print('Closed connection from {}'.format(self._address)) - - -class Server: - def __init__(self, host, port): - self.host = host - self.port = port - self._socket = None - self._runnning = False - - def run(self): - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self._socket.bind((self.host, self.port)) - self._socket.listen(5) - self._runnning = True - - print('Server is up') - while self._runnning: - conn, addr = self._socket.accept() - ClientThread(conn, addr).start() - - def stop(self): - self._runnning = False - self._socket.close() - print('Server is down') - - -if __name__ == '__main__': - srv = Server(host='127.0.0.1', port=5555) - try: - srv.run() - except KeyboardInterrupt: - srv.stop() diff --git a/Practice/o_komissarova/for_lec10/task3.py b/Practice/o_komissarova/for_lec10/task3.py deleted file mode 100644 index 8f8dd0ab..00000000 --- a/Practice/o_komissarova/for_lec10/task3.py +++ /dev/null @@ -1,21 +0,0 @@ -import re -from urllib import request - - -def get_urls(url): - req = request.Request(url) - response = request.urlopen(req) - web_page = response.read() - links = re.findall('"((http|ftp)s?://.*?)"', web_page) - for link in links: - print('link {} : {}'.format(link, url_ok(link))) - - -def url_ok(url): - r = request.urlopen('http://google.com').getcode() - return r.status_code == 200 - - -if __name__ == '__main__': - get_urls('http://google.com') - diff --git a/Practice/o_komissarova/for_lec11/task1.py b/Practice/o_komissarova/for_lec11/task1.py deleted file mode 100644 index 017fc8a2..00000000 --- a/Practice/o_komissarova/for_lec11/task1.py +++ /dev/null @@ -1,44 +0,0 @@ -import json -import sqlite3 as sq - - -class SqLyteConnector: - def __init__(self, db_name): - with sq.connect(db_name) as self.con: - self.cur = self.con.cursor() - - def select(self, sql_request): - self.cur.execute(sql_request) - data = self.cur.fetchall() - print(data) - response = [] - for i in range(len(data)): - object_map = {} - for j in range(len(data[i])): - key = self.cur.description[j][0] - value = data[i][j] - object_map[key] = value - response.append(object_map) - return json.dumps(response) - - def execute(self, sql_request): - self.cur.executescript(sql_request) - if 'CREATE' in sql_request: - return json.dumps({'table': 'created'}) - elif 'INSERT' in sql_request: - return json.dumps({'data': 'inserted'}) - elif 'DROP' in sql_request: - return json.dumps({'table': 'dropped'}) - - -if __name__ == '__main__': - my_connector = SqLyteConnector('test.bd') - print(my_connector.execute("""CREATE TABLE IF NOT EXISTS cars ( - car_id INTEGER PRIMARY KEY AUTOINCREMENT, - model TEXT, - price INTEGER - )""")) - print(my_connector.execute("INSERT INTO cars VALUES(1,'Audi',52642)")) - print(my_connector.execute("INSERT INTO cars VALUES(2,'Mercedes',57127)")) - print(my_connector.select("SELECT * FROM cars")) - print(my_connector.execute("DROP TABLE cars")) diff --git a/Practice/o_komissarova/for_lec11/task2.py b/Practice/o_komissarova/for_lec11/task2.py deleted file mode 100644 index f66c11df..00000000 --- a/Practice/o_komissarova/for_lec11/task2.py +++ /dev/null @@ -1,101 +0,0 @@ -import os -import sqlite3 as sq - - -def create_tables(cursor): - cursor.executescript(""" - PRAGMA foreign_keys=on; - CREATE TABLE Vendors( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL); - - CREATE TABLE Customers( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - second_name TEXT NOT NULL); - - CREATE TABLE Products( - id INTEGER PRIMARY KEY AUTOINCREMENT, - vendor_id INTEGER, - customer_id INTEGER, - name TEXT NOT NULL, - price REAL CHECK (price >0), - quantity INTEGER, - FOREIGN KEY (Vendor_id) REFERENCES Vendors(id), - FOREIGN KEY (Customer_id) REFERENCES Customers(id) - );""") - - -def insert_data(cursor): - cursor.execute("INSERT INTO Vendors(name) VALUES('Toy store')") - cursor.execute("INSERT INTO Vendors(name) VALUES('Book store')") - cursor.execute("INSERT INTO Vendors(name) VALUES('Fabric store')") - cursor.execute("INSERT INTO Vendors(name) VALUES('Car store')") - cursor.execute("INSERT INTO Customers(name, second_name) " - "VALUES('John', 'Peterson')") - cursor.execute("INSERT INTO Customers(name, second_name) " - "VALUES('Jack', 'Anderson')") - cursor.execute("INSERT INTO Customers(name, second_name) " - "VALUES('Sandy', 'Clark')") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(1, 1, 'Puzzle', 5, 1)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(1, 3, 'Bear_toy', 8, 1)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(1, 3, 'Barbie_toy', 7, 1)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(2, 2, 'Lord of the rings', 15, 1)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(2, 2, 'The chronics of Narnia', 20, 2)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(2, 1, 'Pride and Prejudice', 10, 1)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(3, 3, 'Blue cotton', 8, 2)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(3, 3, 'Scarlet silk', 25, 3)") - cursor.execute("INSERT INTO Products(vendor_id, customer_id, name, price, quantity)" - "VALUES(3, 3, 'Black velour', 12, 2)") - - -def get_data(cursor): - cursor.execute("SELECT DISTINCT Vendors.name FROM Vendors, Products " - "WHERE Vendors.id == vendor_id " - "AND price <= 10 " - "GROUP BY quantity " - "HAVING SUM(quantity) >= 2" - ) - print(cursor.fetchall()) - - cursor.execute("SELECT DISTINCT Customers.name, Vendors.name " - "FROM Customers " - "INNER JOIN Vendors JOIN Products " - "ON Vendors.id == vendor_id " - "AND Customers.id == customer_id " - "ORDER BY Vendors.name" - ) - print(cursor.fetchall()) - - cursor.execute("SELECT DISTINCT Vendors.name, Products.name, MAX(quantity) " - "FROM Vendors, Products " - "WHERE Vendors.id == vendor_id " - "GROUP BY Vendors.name " - "ORDER BY quantity DESC") - print(cursor.fetchall()) - - cursor.execute("SELECT DISTINCT Vendors.name, Products.name, (price*quantity) as Profit " - "FROM Vendors LEFT JOIN Products " - "ON Vendors.id == vendor_id " - "ORDER BY Profit DESC, Vendors.name ASC") - print(cursor.fetchall()) - - -if __name__ == '__main__': - name_bd = "task2.bd" - bd_created = os.path.exists(name_bd) - with sq.connect(name_bd) as con: - cur = con.cursor() - if bd_created is False: - create_tables(cur) - insert_data(cur) - get_data(cur) - diff --git a/Practice/o_komissarova/for_lec2/biggest_number.py b/Practice/o_komissarova/for_lec2/biggest_number.py deleted file mode 100644 index b4414cbd..00000000 --- a/Practice/o_komissarova/for_lec2/biggest_number.py +++ /dev/null @@ -1,27 +0,0 @@ -def get_biggest_number(number_1, number_2): - if number_1 > number_2: - print(number_1) - elif number_2 > number_1: - print(number_2) - else: - print('numbers are equal') - - -get_biggest_number(1, 2) -get_biggest_number(2, 1) -get_biggest_number(2, 2) - - -def return_biggest_number(number_1, number_2): - if number_1 > number_2: - return number_1 - elif number_2 > number_1: - return number_2 - else: - return None - - -print(return_biggest_number(4, 5)) -print(return_biggest_number(5, 4)) -print(return_biggest_number(5, 5)) - diff --git a/Practice/o_komissarova/for_lec2/game.py b/Practice/o_komissarova/for_lec2/game.py deleted file mode 100644 index 87e7fda8..00000000 --- a/Practice/o_komissarova/for_lec2/game.py +++ /dev/null @@ -1,111 +0,0 @@ -from random import randint - - -class Personage: - x = 0 - speed = 1 - action = "run" - - def draw(self): - pass - - def run(self): - self.x += self.speed - if self.action == "run": - print("run forward") - elif self.action == "fly": - print("fly forward") - elif self.action == "swim": - print("swim forward") - - def shoot(self): - print("dead shot") - - def peek(self, thing): - if thing.speed_change != 0: - print(thing.speed_change, thing.action) - self.speed += thing.speed_change - print(self.speed) - if thing.action is not None: - print(thing.speed_change, thing.action) - self.action = thing.action - print(self.action) - print(thing.name + " peeked. Speed is " + - str(self.speed) + ". Action is " + self.action) - - -class Human(Personage): - def __init__(self): - print("Human is chosen") - - def draw(self): - print("I'm Human at {}".format(self.x)) - - -class Vampire(Personage): - def draw(self): - print("I'm Vampire at {}".format(self.x)) - - def __init__(self): - print("Vampire is chosen") - - def fly(self): - self.x += self.speed - print("fly forward") - - -class Thing: - name = "abstract thing" - action = None - speed_change = 0 - - -class FastBoots(Thing): - name = "fast boots" - speed_change = 7 - - -class SlowBoots(Thing): - name = "slow boots" - speed_change = -1 - - -class MagicCarpet(Thing): - name = "magic carpet" - action = "fly" - - -class Flippers(Thing): - name = "flippers" - action = "swim" - - -class Boots(Thing): - name = "boots" - action = "run" - - -personages = [Human(), Vampire()] -things = [FastBoots(), SlowBoots(), MagicCarpet(), Flippers(), Boots()] -for personage in personages: - personage.draw() -while True: - n = int(input("Введите номер персонажа (от 0 до 1): ")) - cmd = input("Введите команду (shoot, run, peek или fly (для вампира): ") - if cmd == "run": - personages[n].run() - elif cmd == "shoot": - personages[n].shoot() - elif cmd == "peek": - rand = randint(0, 4) - personages[n].peek(things[rand]) - elif cmd == "fly": - if isinstance(personages[n], Vampire): - personages[n].fly() - else: - print("Human can't fly") - else: - break - for personage in personages: - personage.draw() - diff --git a/Practice/o_komissarova/for_lec4/fizz_buzz.py b/Practice/o_komissarova/for_lec4/fizz_buzz.py deleted file mode 100644 index 2bcaf6be..00000000 --- a/Practice/o_komissarova/for_lec4/fizz_buzz.py +++ /dev/null @@ -1,17 +0,0 @@ -# Напишите программу, которая выводит на экран числа от 1 до 100. При этом вместо чисел, -# кратных трем, программа должна выводить слово Fizz, а вместо чисел, кратных пяти — -# слово Buzz. Если число кратно пятнадцати, то программа должна выводить слово FizzBuzz. - -def fizz_buzz(): - for i in range(1, 100): - if i % 15 == 0: - print("FizzBuzz") - elif i % 5 == 0: - print("Buzz") - elif i % 3 == 0: - print("Fizz") - else: - print(i) - - -fizz_buzz() diff --git a/Practice/o_komissarova/for_lec4/interpolate.py b/Practice/o_komissarova/for_lec4/interpolate.py deleted file mode 100644 index b67a6c59..00000000 --- a/Practice/o_komissarova/for_lec4/interpolate.py +++ /dev/null @@ -1,10 +0,0 @@ -def interpolate(string, dictionary): - for key in dictionary: - if key in string: - string = string.replace(key, dictionary[key]) - return string - - -dict = {'cat': 'кошка', 'table': 'стол'} -str = 'cat is on the table' -print(interpolate(str, dict)) diff --git a/Practice/o_komissarova/for_lec4/matrix.py b/Practice/o_komissarova/for_lec4/matrix.py deleted file mode 100644 index 6a0f6bfb..00000000 --- a/Practice/o_komissarova/for_lec4/matrix.py +++ /dev/null @@ -1,49 +0,0 @@ -def del_column(number, matrix): - column_number = [] - for i in range(len(matrix)): - for j in range(len(matrix[i])): - if matrix[i][j] == number: - if j in column_number: - continue - column_number.append(j) - if column_number is None: - print('number is not found') - else: - column_number.sort() - column_number.reverse() - for row in matrix: - for number in column_number: - del (row[number]) - return matrix - - -def print_matrix(matrix): - for row in matrix: - for x in row: - print("{:4d}".format(x), end="") - print() - - -# delete two columns -matrix = [[1, 2, 3], [3, 5, 6], [7, 8, 9]] -print_matrix(matrix) -del_column(3, matrix) -print_matrix(matrix) - -# delete all columns -matrix = [[1, 2, 3], [3, 5, 6], [7, 3, 9]] -print_matrix(matrix) -del_column(3, matrix) -print_matrix(matrix) - -# delete one column -matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] -print_matrix(matrix) -del_column(3, matrix) -print_matrix(matrix) - -# delete column with repeating numbers -matrix = [[1, 2, 3], [4, 5, 3], [7, 8, 3]] -print_matrix(matrix) -del_column(3, matrix) -print_matrix(matrix) diff --git a/Practice/o_komissarova/for_lec4/number_reader.py b/Practice/o_komissarova/for_lec4/number_reader.py deleted file mode 100644 index 0fa42d24..00000000 --- a/Practice/o_komissarova/for_lec4/number_reader.py +++ /dev/null @@ -1,14 +0,0 @@ -# Составить программу, которая будет считывать введённое пятизначное число. -# После чего, каждую цифру этого числа необходимо вывести в новой строке: - -def read_number(number): - if not str(number).isdigit(): - print("incorrect input") - return False - numbers = str(number) - for num, val in enumerate(numbers, 1): - print(str(num) + ' цифра равна ' + str(val)) - return True - - -read_number(10819) diff --git a/Practice/o_komissarova/for_lec4/replace.py b/Practice/o_komissarova/for_lec4/replace.py deleted file mode 100644 index af3c326c..00000000 --- a/Practice/o_komissarova/for_lec4/replace.py +++ /dev/null @@ -1,39 +0,0 @@ -def replace(source, action): - # check file or string - formats = (".txt", ".json") - type = None - for i in formats: - if i in source: - type = "file" - if type is None: - type = "string" - # work with file - if type == "file": - f = open(source, 'r') - str = f.read() - f.close() - f = open(source, 'w') - if action == "spaces_to_tabs": - f.write(str.replace(' ', '\t')) - f.close() - return True - elif action == "tabs_to_spaces": - f.write(str.replace('\t', ' ')) - f.close() - return True - else: - print("incorrect action. spaces_to_tabs or tabs_to_spaces are available") - f.close() - return False - # work with string - elif type == "string": - if action == "spaces_to_tabs": - return source.replace(' ', '\t') - elif action == "tabs_to_spaces": - return source.replace('\t', ' ') - else: - print("incorrect action. spaces_to_tabs or tabs_to_spaces are available") - return None - - -print(replace("file.txt", "spaces_to_tabs")) diff --git a/Practice/o_komissarova/for_lec4/sort.py b/Practice/o_komissarova/for_lec4/sort.py deleted file mode 100644 index cd490fbb..00000000 --- a/Practice/o_komissarova/for_lec4/sort.py +++ /dev/null @@ -1,17 +0,0 @@ -# Реализовать алгоритм сортировки выбором. - -def sort(array): - for i in range(0, len(array) - 1): - pos_for_change = i - minimum = i - for j in range(i + 1, len(array)): - if array[j] < array[minimum]: - minimum = j - array[pos_for_change], array[minimum] = array[minimum], array[pos_for_change] - - -arr = [0, 3, 24, 2, 3, 7] -print(arr) -sort(arr) -print(arr) - diff --git a/Practice/o_komissarova/for_lec5/man_pupil.py b/Practice/o_komissarova/for_lec5/man_pupil.py deleted file mode 100644 index 56f3a718..00000000 --- a/Practice/o_komissarova/for_lec5/man_pupil.py +++ /dev/null @@ -1,24 +0,0 @@ -from random import randint -from time import sleep - - -class Man: - def __init__(self, name): - self.name = name - - def solve_task(self): - print("I'm not ready yet") - - -class Pupil(Man): - def solve_task(self): - print("thinking...") - time = randint(3, 6) - sleep(time) - print("I'm ready") - - -man = Man("Peter") -man.solve_task() -pupil = Pupil("Alex") -pupil.solve_task() diff --git a/Practice/o_komissarova/for_lec5/wrap_str_to_file.py b/Practice/o_komissarova/for_lec5/wrap_str_to_file.py deleted file mode 100644 index 1cf47771..00000000 --- a/Practice/o_komissarova/for_lec5/wrap_str_to_file.py +++ /dev/null @@ -1,43 +0,0 @@ -import tempfile -import os - - -class WrapStrToFile: - def __init__(self): - self._filepath = tempfile.mktemp() - - @property - def content(self): - try: - f = open(self._filepath, 'r') - string = f.read() - f.close() - return string - except (IOError, EOFError): - return "file doesn't exist" - - @content.setter - def content(self, value): - try: - f = open(self._filepath, 'w') - f.write(value) - f.close() - except Exception as e: - print("unexpected error: {}".format(e)) - - @content.deleter - def content(self): - try: - os.remove(self._filepath) - except Exception as e: - print("unexpected error: {}".format(e)) - - -wstf = WrapStrToFile() -print(wstf.content) -wstf.content = "test str" -print(wstf.content) -wstf.content = "text 2" -print(wstf.content) -del wstf.content -print(wstf.content) diff --git a/Practice/o_komissarova/for_lec6/cont_manager.py b/Practice/o_komissarova/for_lec6/cont_manager.py deleted file mode 100644 index 3bc4b2c8..00000000 --- a/Practice/o_komissarova/for_lec6/cont_manager.py +++ /dev/null @@ -1,15 +0,0 @@ -import time - - -class ContManager: - def __enter__(self): - self._start = time.time() - - def __exit__(self, exc_type, exc_val, exc_tb): - print('time: {}'.format(time.time() - self._start)) - - -with ContManager(): - print("smth is doing") - time.sleep(10) - print("smth is done") diff --git a/Practice/o_komissarova/for_lec6/itertools_task.py b/Practice/o_komissarova/for_lec6/itertools_task.py deleted file mode 100644 index f11f0455..00000000 --- a/Practice/o_komissarova/for_lec6/itertools_task.py +++ /dev/null @@ -1,5 +0,0 @@ -import itertools - -print(list(itertools.chain([1, 2, 3], [4, 5], [6, 7]))) -print(list(itertools.filterfalse(lambda x: len(x) < 5, ['hello', 'i', 'write', 'cool', 'code']))) -print(list(itertools.combinations('password', 4))) diff --git a/Practice/o_komissarova/for_lec7/dir_follower.py b/Practice/o_komissarova/for_lec7/dir_follower.py deleted file mode 100644 index 54c41b37..00000000 --- a/Practice/o_komissarova/for_lec7/dir_follower.py +++ /dev/null @@ -1,24 +0,0 @@ -import os -import datetime -import shutil - - -def follow_dir(path_to_dir): - while True: - for root, dirs, files in os.walk(path_to_dir): - for _file in files: - path_to_current_file = os.path.join(root, _file) - creation_time = datetime.datetime.fromtimestamp(os.path.getctime(path_to_current_file)) - difference = datetime.datetime.now() - creation_time - if difference > datetime.timedelta(seconds=60): - os.remove(path_to_current_file) - - for _dir in dirs: - path_to_current_dir = os.path.join(root, _dir) - creation_time = datetime.datetime.fromtimestamp(os.path.getctime(path_to_current_dir)) - difference = datetime.datetime.now() - creation_time - if difference > datetime.timedelta(seconds=120): - shutil.rmtree(path_to_current_dir) - - -follow_dir('/home/olesya/temporary') diff --git a/Practice/o_komissarova/for_lec7/human.data b/Practice/o_komissarova/for_lec7/human.data deleted file mode 100644 index d7bf995686c2744c91cd1aed7764ace544515867..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 601 zcmbWzJqyAx5P)Gp+bZ}Q#8DSVokSEtK~S*n;jEzsn?%~wPD0(YdHuf@s#vS|l`Vne z$$PPpuu^t(l@Jb05Q5s6h8zT*v3M(AAy8XE=x2AscBE42JGc~QJ#9vm zxm$&^xvqQcz=TWo9ysZwWm8bfqZqC`v61ZlH?7rH@<68lcv43nRQZEy1J9S%mU2yf zm2>;|+CkB+*&v!@MqPRB-G48eL$UE`^d4{A@ktRcton!O7qqzuBJei1W#`;((S3}* E0OEAs@Bjb+ diff --git a/Practice/o_komissarova/for_lec7/human.py b/Practice/o_komissarova/for_lec7/human.py deleted file mode 100644 index f1e2a1e2..00000000 --- a/Practice/o_komissarova/for_lec7/human.py +++ /dev/null @@ -1,50 +0,0 @@ -import random, pickle - - -class Human: - def __init__(self, name, surname, age, weight, living_place): - self.name = name - self.surname = surname - self.age = age - self.weight = weight - self.living_place = living_place - - def __str__(self): - return "{} {}, age - {}, weight - {}, living place - {}". \ - format(self.name, self.surname, self.age, self.weight, self.living_place) - - -def create_people(people_number): - if people_number <= 0: - return None - names = ['Ann', 'Andrew', 'Peter', 'Sam', 'Alice'] - surnames = ['Scott', 'Thomson', 'Robertson', 'Richardson', 'Oswald'] - living_places = ['Chicago', 'San Diego', 'Seattle', 'Denver', 'Washington'] - people = [] - - for i in range(people_number): - human = Human(random.choice(names), random.choice(surnames), random.randint(15, 70), - random.randint(50, 80), random.choice(living_places)) - people.append(human) - serialize_people(people) - return people - - -def serialize_people(people): - with open('human.data', 'wb') as f: - for human in people: - pickle.dump(human, f, protocol=pickle.HIGHEST_PROTOCOL) - - -def deserialize_people(file_name, number): - with open(file_name, 'rb') as f: - people = [] - for i in range(number): - people.append(pickle.load(f)) - return people - - -create_people(5) -people = deserialize_people('human.data', 5) -for human in people: - print(human) diff --git a/Practice/o_komissarova/for_lec7/subprocess_cat.py b/Practice/o_komissarova/for_lec7/subprocess_cat.py deleted file mode 100644 index 3cf51c5d..00000000 --- a/Practice/o_komissarova/for_lec7/subprocess_cat.py +++ /dev/null @@ -1,13 +0,0 @@ -from subprocess import Popen, PIPE - - -def read_file(file_name): - proc = Popen(['cat', file_name], stdout=PIPE, stderr=PIPE) - proc.wait() - res = proc.communicate() - if proc.returncode: - print(res[1]) - print(res[0]) - - -read_file('text.txt') diff --git a/Practice/o_komissarova/for_lec7/text.txt b/Practice/o_komissarova/for_lec7/text.txt deleted file mode 100644 index 0e47f17d..00000000 --- a/Practice/o_komissarova/for_lec7/text.txt +++ /dev/null @@ -1,5 +0,0 @@ -Reedfish armored gurnard sturgeon pompano dolphinfish gray reef shark. Sand stargazer flier northern pearleye wrasse black dragonfish smalltooth sawfish, red snapper blue triggerfish." - -Walu largemouth bass Bitterling john dory coho salmon loach catfish climbing catfish. Sind danio shark bigscale fish tope ballan wrasse eeltail catfish zander whitefish channel bass. Northern pearleye, northern clingfish, "beardfish," beardfish mudfish yellow-edged moray. - -Mexican blind cavefish velvet-belly shark squirrelfish sand diver buri dwarf loach arrowtooth eel Blenny glass catfish whitebait: Asiatic glassfish. Snoek slickhead; climbing catfish, Pacific albacore zingel? Great white shark spearfish smalleye squaretail alooh lemon shark zebra oto spearfish jewelfish eelpout. Striped bass sucker swordfish Bitterling round stingray Pacific salmon giant gourami danio needlefish mackerel. Swallower warty angler, goldeye plaice morid cod spotted danio Oriental loach blackfish lemon shark yellow-and-black triplefin louvar long-finned pike Sacramento blackfish tidewater goby. Peladillo southern smelt snake eel threadfin bream lumpsucker golden dojo pearlfish lightfish longnose dace labyrinth fish. Southern Dolly Varden nase olive flounder burbot starry flounder oceanic flyingfish yellowtail kingfish tiger shovelnose catfish ribbon eel. Graveldiver squaretail noodlefish glowlight danio yellowfin tuna crestfish char tiger shark swampfish; sculpin sawtooth eel. Zebra tilapia king of herring unicorn fish sand stargazer mail-cheeked fish. Threespine stickleback lemon shark, "goby dhufish stingray jewelfish," madtom whale catfish northern squawfish pelagic cod. Wahoo, deep sea anglerfish, salmon rudderfish convict blenny anglerfish. Mouthbrooder ghost flathead Black angelfish moonfish; Rattail Oregon chub righteye flounder, river stingray deep sea eel. \ No newline at end of file diff --git a/Practice/o_komissarova/for_lec7/warm_up_find_git.py b/Practice/o_komissarova/for_lec7/warm_up_find_git.py deleted file mode 100644 index 1d13fd16..00000000 --- a/Practice/o_komissarova/for_lec7/warm_up_find_git.py +++ /dev/null @@ -1,11 +0,0 @@ -import re - - -def find_git(path): - with open(path) as f: - text = f.read() - result = set(re.findall('git [a-z,A-Z]+', text)) - print(result) - - -find_git('../dir/README.md') diff --git a/Practice/o_komissarova/for_lec7/warm_up_gen.py b/Practice/o_komissarova/for_lec7/warm_up_gen.py deleted file mode 100644 index 43ca3a56..00000000 --- a/Practice/o_komissarova/for_lec7/warm_up_gen.py +++ /dev/null @@ -1,8 +0,0 @@ -def my_gen(file_name): - with open(file_name) as f: - for line in f: - yield line - - -for i in my_gen('text.txt'): - print(i) diff --git a/Practice/o_komissarova/for_lec7/warm_up_iter.py b/Practice/o_komissarova/for_lec7/warm_up_iter.py deleted file mode 100644 index d29ddd6d..00000000 --- a/Practice/o_komissarova/for_lec7/warm_up_iter.py +++ /dev/null @@ -1,28 +0,0 @@ -class MyIter: - def __init__(self, text, separator): - self.text = text - self.separator = separator - self.position = 0 - - def __iter__(self): - return self - - def __next__(self): - text_array = self.text - result = "" - while True: - if self.position == len(text_array): - raise StopIteration - elif text_array[self.position] == self.separator: - self.position += 1 - elif text_array[self.position + 1] == self.separator: - result += text_array[self.position] - self.position += 1 - return result - else: - result += text_array[self.position] - self.position += 1 - - -for i in MyIter('123\t456\t789\t', '\t'): - print(i) diff --git a/Practice/o_komissarova/for_lec7/warm_up_transpose.py b/Practice/o_komissarova/for_lec7/warm_up_transpose.py deleted file mode 100644 index 6029081c..00000000 --- a/Practice/o_komissarova/for_lec7/warm_up_transpose.py +++ /dev/null @@ -1,30 +0,0 @@ -def transpose(matrix): - i_max = len(matrix) - i = 0 - j_max = len(matrix[0]) - new_matrix = [] - for j in range(j_max): - line = [] - while i < i_max: - line.append(matrix[i][j]) - i += 1 - new_matrix.append(line) - i = 0 - return new_matrix - - -def print_matrix(matrix): - for row in matrix: - for x in row: - print("{:4d}".format(x), end="") - print() - - -matr = [ - [1, 2, 3], - [4, 5, 6] -] - -print_matrix(matr) -print() -print_matrix(transpose(matr)) diff --git a/Practice/o_komissarova/for_lec7/workdays_counter.py b/Practice/o_komissarova/for_lec7/workdays_counter.py deleted file mode 100644 index e6440cf7..00000000 --- a/Practice/o_komissarova/for_lec7/workdays_counter.py +++ /dev/null @@ -1,24 +0,0 @@ -import datetime - - -def workdays_count(date_start, date_end): - if date_start >= date_end: - return 0 - current_date = date_start - count = 0 - while current_date <= date_end: - if is_week_day(current_date): - count += 1 - current_date = current_date + datetime.timedelta(days=1) - return count - - -def is_week_day(date): - if date.weekday() == 5 or date.weekday() == 6: - return False - return True - - -date1 = datetime.datetime.now() -date2 = date1+datetime.timedelta(days=30) -print(workdays_count(date1, date2)) diff --git a/Practice/o_komissarova/for_lec8/bonus.py b/Practice/o_komissarova/for_lec8/bonus.py deleted file mode 100644 index 6f1bd2dd..00000000 --- a/Practice/o_komissarova/for_lec8/bonus.py +++ /dev/null @@ -1,45 +0,0 @@ -# Сложность алгоритма сортировки слиянием O(nlog (n)) -# Сложность доступа к элементам отсортированного листа O(n) -# Сложность алгоритма выбора O(nlog (n)) + O(n), что можно сократить до O(nlog (n)) - - -def max_numbers(arr, n): - reverse_sorted_arr = reverse_sort_numbers(arr) - max_numbers_arr = [] - for i in range(n): - max_numbers_arr.append(reverse_sorted_arr[i]) - return max_numbers_arr - - -def reverse_sort_numbers(arr): - if len(arr) <= 1: - return arr - mid = len(arr) // 2 - left_list = reverse_sort_numbers(arr[:mid]) - right_list = reverse_sort_numbers(arr[mid:]) - return merge(left_list, right_list) - - -def merge(left_list, right_list): - sorted_list = [] - left_list_index = right_list_index = 0 - left_list_length, right_list_length = len(left_list), len(right_list) - for i in range(left_list_length + right_list_length): - if left_list_index < left_list_length and right_list_index < right_list_length: - if left_list[left_list_index] >= right_list[right_list_index]: - sorted_list.append(left_list[left_list_index]) - left_list_index += 1 - else: - sorted_list.append(right_list[right_list_index]) - right_list_index += 1 - elif left_list_index == left_list_length: - sorted_list.append(right_list[right_list_index]) - right_list_index += 1 - elif right_list_index == right_list_length: - sorted_list.append(left_list[left_list_index]) - left_list_index += 1 - return sorted_list - - -array = [1, 6, 2, 15, 12, 3, 45, 24] -print(max_numbers(array, 3)) diff --git a/Practice/o_komissarova/for_lec8/source.txt b/Practice/o_komissarova/for_lec8/source.txt deleted file mode 100644 index a1ffce3e..00000000 --- a/Practice/o_komissarova/for_lec8/source.txt +++ /dev/null @@ -1 +0,0 @@ -what a wonderful world \ No newline at end of file diff --git a/Practice/o_komissarova/for_lec8/task1.py b/Practice/o_komissarova/for_lec8/task1.py deleted file mode 100644 index 3fc2ad5b..00000000 --- a/Practice/o_komissarova/for_lec8/task1.py +++ /dev/null @@ -1,8 +0,0 @@ -def myLen(list): - length = 0; - for element in list: - length += 1; - return length - - -print(myLen([1, 2, 3, 4, 5])) \ No newline at end of file diff --git a/Practice/o_komissarova/for_lec8/task10.py b/Practice/o_komissarova/for_lec8/task10.py deleted file mode 100644 index 36ac2873..00000000 --- a/Practice/o_komissarova/for_lec8/task10.py +++ /dev/null @@ -1,79 +0,0 @@ -class Money: - def __init__(self, rub, kop): - self._rub = rub - self._kop = kop - - @property - def dollar_course(self): - return self._dollar_course - - @dollar_course.setter - def dollar_course(self, value): - self._dollar_course = float(value) - - def convert(self): - number = float(str(self).replace(",", ".")) - return number*self._dollar_course - - def __float__(self): - return float(str(self).replace(",", ".")) - - def __str__(self): - return "{},{}".format(self._rub, self._kop) - - def __add__(self, other): - if isinstance(other, Money): - number = str(round(float(self)+float(other), 2)).split('.') - money = Money(number[0], number[1]) - return money - - def __sub__(self, other): - if isinstance(other, Money): - number = str(round(float(self) - float(other), 2)).split('.') - money = Money(number[0], number[1]) - return money - - def __mul__(self, other): - if isinstance(other, Money): - number = str(round(float(self) * float(other), 2)).split('.') - money = Money(number[0], number[1]) - return money - - def __truediv__(self, other): - if isinstance(other, Money): - number = str(round(float(self) / float(other), 2)).split('.') - money = Money(number[0], number[1]) - return money - - def __lt__(self, other): - if isinstance(other, Money): - if float(self) < float(other): - return True - return False - - def __gt__(self, other): - if isinstance(other, Money): - if float(self) > float(other): - return True - return False - - def __eq__(self, other): - if isinstance(other, Money): - if float(self) == float(other): - return True - return False - - -money1 = Money(20, 15) -money2 = Money(10, 21) -money3 = Money(20, 15) -print(money1, money2) -print(money1 + money2) -print(money1 - money2) -print(money1 * money2) -print(money1 / money2) -print(money1 < money2) -print(money1 > money2) -print(money1 == money3) -money1.dollar_course = 75.5 -print(money1.convert()) diff --git a/Practice/o_komissarova/for_lec8/task2.py b/Practice/o_komissarova/for_lec8/task2.py deleted file mode 100644 index 93661667..00000000 --- a/Practice/o_komissarova/for_lec8/task2.py +++ /dev/null @@ -1,5 +0,0 @@ -def reverse(my_list): - return my_list[::-1] - - -print(reverse([1, 2, 3, 4, 5])) \ No newline at end of file diff --git a/Practice/o_komissarova/for_lec8/task3.py b/Practice/o_komissarova/for_lec8/task3.py deleted file mode 100644 index e5985e2c..00000000 --- a/Practice/o_komissarova/for_lec8/task3.py +++ /dev/null @@ -1,38 +0,0 @@ -def my_range(*args): - for i in args: - if not str(i).isdigit(): - try: - float(str(i)) - except ValueError: - return None - start = 0 - step = 1 - stop = 0 - result = [] - if len(args) == 1: - stop = args[0] - elif len(args) >= 2: - start = args[0] - stop = args[1] - if len(args) == 3: - step = args[2] - if step == 0: - raise ValueError - position = start - if step > 0: - while position <= stop: - result.append(position) - position += step - return result - else: - while position >= stop: - result.append(position) - position += step - return result - - -print(my_range(5)) # [0, 1, 2, 3, 4, 5] -print(my_range(2, 15)) # [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -print(my_range(2, 15, 2)) # [2, 4, 6, 8, 10, 12, 14] -print(my_range(15, 2, -2)) # print(my_range(15, 2, -2)) # -print(my_range(15, 2, "g")) # None diff --git a/Practice/o_komissarova/for_lec8/task4.py b/Practice/o_komissarova/for_lec8/task4.py deleted file mode 100644 index a184a616..00000000 --- a/Practice/o_komissarova/for_lec8/task4.py +++ /dev/null @@ -1,12 +0,0 @@ -def to_title(string): - str = string.split(" ") - new_str = "" - i = 0 - for i in range(len(str)): - new_str += str[i][0].capitalize() - new_str += str[i][1:] - new_str += " " - return new_str - - -print(to_title('what a wonderful world')) diff --git a/Practice/o_komissarova/for_lec8/task5.py b/Practice/o_komissarova/for_lec8/task5.py deleted file mode 100644 index 71d6071f..00000000 --- a/Practice/o_komissarova/for_lec8/task5.py +++ /dev/null @@ -1,9 +0,0 @@ -def count_symbol(string, symbol): - frequency = 0 - for i in string: - if i == symbol: - frequency += 1 - return frequency - - -print(count_symbol('what wonderful world', 'w')) diff --git a/Practice/o_komissarova/for_lec8/task6.py b/Practice/o_komissarova/for_lec8/task6.py deleted file mode 100644 index ea863357..00000000 --- a/Practice/o_komissarova/for_lec8/task6.py +++ /dev/null @@ -1,22 +0,0 @@ -def my_format(*args): - length = len(args)-1 - template = args[0] - for pos in reversed(range(len(template))): - if template[pos] == '{' and template[pos+1] == '}': - template = template[:pos]+args[length]+template[pos+2:] - length -= 1 - elif template[pos] == '{' and template[pos+1] != '}': - end = pos+1 - str_num = "" - while template[end] != '}': - str_num += template[end] - end += 1 - number = int(str_num) - template = template.replace(template[pos:end+1], args[number+1]) - return template - - -print(my_format('{1}, {0}, {2}', 'a', 'b', 'c')) -print(my_format('coordinates: {}, {}', '37.4N', '18.3W')) -print(my_format('{10}, {0}, {2}', 'a', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'u')) - diff --git a/Practice/o_komissarova/for_lec8/task7.py b/Practice/o_komissarova/for_lec8/task7.py deleted file mode 100644 index 4bc06f7f..00000000 --- a/Practice/o_komissarova/for_lec8/task7.py +++ /dev/null @@ -1,10 +0,0 @@ -from pathlib import Path - - -def copy_file(source, destination): - content = "" - with open(source, 'r') as f: - content = f.read() - with open(destination, 'x') as f: - f.write(content) - diff --git a/Practice/o_komissarova/for_lec8/task8.py b/Practice/o_komissarova/for_lec8/task8.py deleted file mode 100644 index b8c84497..00000000 --- a/Practice/o_komissarova/for_lec8/task8.py +++ /dev/null @@ -1,30 +0,0 @@ -import os -from pathlib import Path -from Practice.o_komissarova.for_lec8.task7 import copy_file - - -def copy_dir(source, destination): - if not Path(source).is_dir(): - raise NotADirectoryError - if Path(destination).is_dir(): - raise IsADirectoryError - full_path = str(source).split("/") - name_of_source_dir = full_path[len(full_path) - 1] - copy_dir_path = Path(destination).joinpath(name_of_source_dir) - try: - os.mkdir(destination) - except OSError: - print("Создать директорию %s не удалось" % copy_dir_path) - - for root, dirs, files in os.walk(source): - for _file in files: - file_path = Path(source).joinpath(_file) - file_copy_path = Path(destination).joinpath(_file) - copy_file(file_path, file_copy_path) - for _dir in dirs: - dir_path = Path(source).joinpath(_dir) - dir_copy_path = Path(destination).joinpath(_dir) - copy_dir(dir_path, dir_copy_path) - - -copy_dir('/home/olesya/temporary', '/home/olesya/temporary2') diff --git a/Practice/o_komissarova/for_lec8/task9.py b/Practice/o_komissarova/for_lec8/task9.py deleted file mode 100644 index a9bbc938..00000000 --- a/Practice/o_komissarova/for_lec8/task9.py +++ /dev/null @@ -1,45 +0,0 @@ -class NotANumberException(Exception): - pass - - -class User: - def __init__(self, name, age): - self._name = name - self._age = age - - def setName(self, name): - self._name = str(name) - - def setAge(self, age): - if str(age).isdigit(): - self._age = age - else: - raise NotANumberException - - def getName(self): - return self._name - - def getAge(self): - return self._age - - -class Worker(User): - def __init__(self, name, age, salary): - super().__init__(name, age) - self.salary = salary - - def setSalary(self, salary): - if str(salary).isdigit(): - self.salary = salary - else: - raise NotANumberException - - def getSalary(self): - return self.salary - - -if __name__ == '__main__': - worker_John = Worker("John", 25, 1000) - print(worker_John.getName(), worker_John.getAge(), worker_John.getSalary()) - worker_Jack = Worker("Jack", 26, 2000) - print(worker_Jack.getName(), worker_Jack.getAge(), worker_Jack.getSalary()) diff --git a/Practice/o_komissarova/for_lec9/task1.py b/Practice/o_komissarova/for_lec9/task1.py deleted file mode 100644 index e204789d..00000000 --- a/Practice/o_komissarova/for_lec9/task1.py +++ /dev/null @@ -1,50 +0,0 @@ -import multiprocessing -import threading -import time - - -def find_primes(start, end): - lst = [] - for i in range(start, end + 1): - for j in range(2, i): - if i % j == 0: - break - else: - lst.append(i) - print(len(lst)) - return lst - - -start_time = time.time() -find_primes(3, 10000) -find_primes(10001, 20000) -find_primes(20001, 30000) -execution_time = time.time() - start_time -print(execution_time) - -start_time = time.time() -threads = [threading.Thread(target=find_primes, args=(3, 10000)), - threading.Thread(target=find_primes, args=(10001, 20000)), - threading.Thread(target=find_primes, args=(20001, 30000))] -for thread in threads: - thread.start() -for thread in threads: - thread.join() -execution_time = time.time() - start_time -print(execution_time) - -start_time = time.time() -processes = [multiprocessing.Process(target=find_primes, args=(3, 10000)), - multiprocessing.Process(target=find_primes, args=(10001, 20000)), - multiprocessing.Process(target=find_primes, args=(20001, 30000))] -for process in processes: - process.start() -for process in processes: - process.join() -execution_time = time.time() - start_time -print(execution_time) - -# if forget start() there will be AssertionError: can only join a started thread/process - -# if forget join() execution time will be count and printed earlier, -# because we don't wait for the end of threads/processes diff --git a/Practice/o_komissarova/for_lec9/task2.py b/Practice/o_komissarova/for_lec9/task2.py deleted file mode 100644 index 77562faf..00000000 --- a/Practice/o_komissarova/for_lec9/task2.py +++ /dev/null @@ -1,30 +0,0 @@ -import threading - - -def sum_different(*args): - for i in range(len(args)): - if not isinstance(args[i], type(args[0])): - raise TypeError - if isinstance(args[0], list): - new_list = [] - for i in range(len(args)): - new_list += args[i] - return new_list - elif isinstance(args[0], int): - return sum(args) - elif isinstance(args[0], str): - new_str = "" - for i in range(len(args)): - new_str += args[i] - return new_str - else: - raise TypeError - - -threads = [threading.Thread(target=sum_different, args=([1, 2, 3], [4, 5, 6])), - threading.Thread(target=sum_different, args=(1, 2, 3, 4, 5, 6)), - threading.Thread(target=sum_different, args=("a", "b", "c"))] -for thread in threads: - thread.start() -for thread in threads: - thread.join() diff --git a/Practice/o_komissarova/for_lec9/task3.py b/Practice/o_komissarova/for_lec9/task3.py deleted file mode 100644 index eb69a062..00000000 --- a/Practice/o_komissarova/for_lec9/task3.py +++ /dev/null @@ -1,17 +0,0 @@ -import threading - - -class PrivateThread(threading.Thread): - def __init__(self, data): - threading.Thread.__init__(self) - self._data = data - - def run(self): - print(f"Thread's name: {threading.current_thread().name}, data: {self._data}") - - -threads = [PrivateThread("abc"), PrivateThread(5), PrivateThread([1, 2, 3, 4])] -for thread in threads: - thread.start() -for thread in threads: - thread.join() diff --git a/Practice/o_komissarova/pep8task.py b/Practice/o_komissarova/pep8task.py deleted file mode 100644 index fc349aac..00000000 --- a/Practice/o_komissarova/pep8task.py +++ /dev/null @@ -1,86 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * -from fileinput import filename - -# Изменить имя класса на Shuffler -class shuffler: - - def __init__(self): - self.map = {} - - # Изменить dirname на dir_name - def rename(self, dirname, output): - # Сдвинуть на два пробела влево - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - # изменить hashname на hash_name - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - # удалить две закрывающие скобки - os.rename(path + '/' + mp3), path + '/' + hashname)) - f = open(output, 'r') - f.write(str(self.map)) - - # изменить dirname на dir_name - def restore(self, dirname, restore_path): - # добавить from fileinput import filename - # сдвинуть на два пробела влево - with open(filename, '+') as f: - self.map = ast.literal_eval(f.read()) - mp3s = [] - # изменить dirname на dir_name - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - # изменить hashname на hash_name - for path, hashname in mp3s: - # убрать закрывающую скобку - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) - os.remove(restore_path) - # Изменить generateName на generate_name - # Сдвинуть на один пробел влево - def generateName(self, seed=time()): - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - # изменить dirname на dir_name - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - # изменить dirname на dir_name - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - # изменить на shuffler = Shuffler() - Shuffler = shuffler() - if args.subcommand == 'rename': - # сдвинуть на два пробела влево - if args.output: - Shuffler.rename(args.dirname, 'restore.info') - else: - Shuffler.rename(args.dirname, args.output) - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() - diff --git a/Practice/shashalina/lec 4 task3.py b/Practice/shashalina/lec 4 task3.py deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/shashalina/lec4 task1.py b/Practice/shashalina/lec4 task1.py deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/shashalina/lec4 task2.py b/Practice/shashalina/lec4 task2.py deleted file mode 100644 index e69de29b..00000000 diff --git a/Practice/shashalina/pep8task.py b/Practice/shashalina/pep8task.py deleted file mode 100644 index 3ee1dc80..00000000 --- a/Practice/shashalina/pep8task.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * # при данном импорте могут быть конфликты имен, теряется логическое разделение кода - - -class shuffler: # имена классов начинаться с заглавной буквыдолжны согласно соглашению CapWords - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): - mp3s = [] # не соблюден отступ относительно функции rename - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - os.rename(path + '/' + mp3), path + '/' + hashname)) # несоответствие открывающих и закрывающих скобок - f = open(output, 'r') # не ошибка, но количество пробелов в отступе более 4х относительно функции rename - f.write(str(self.map)) # не ошибка, но количество пробелов в отступе более 4х относительно функции rename - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: - self.map = ast.literal_eval(f.read()) - mp3s = [] # не соблюден отступ относительно with - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) # несоответствие открывающих и закрывающих скобок - os.remove(restore_path) - - def generateName(self, seed=time()): # присутствует лишний отступ относительно класса shuffler - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() - if args.subcommand == 'rename': - if args.output: # не ошибка, но количество пробелов в отступе более 4х относительно if - Shuffler.rename(args.dirname, 'restore.info') # не ошибка, но количество пробелов в отступе более 4х относительно if - else: # не ошибка, но количество пробелов в отступе более 4х относительно if - Shuffler.rename(args.dirname, args.output) # не ошибка, но количество пробелов в отступе более 4х относительно else - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main() diff --git a/Practice/solkin/test1.py b/Practice/solkin/test1.py deleted file mode 100644 index 6c736079..00000000 --- a/Practice/solkin/test1.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -import os -import hashlib -import ast -import argparse -from time import * - - -class shuffler: - - def __init__(self): - self.map = {} - - def rename(self, dirname, output): - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append([root, file]) - for path, mp3 in mp3s: - hashname = self.generateName() + '.mp3' - self.map[hashname] = mp3 - os.rename(path + '/' + mp3), path + '/' + hashname)) - f = open(output, 'r') - f.write(str(self.map)) - - def restore(self, dirname, restore_path): - with open(filename, '+') as f: - self.map = ast.literal_eval(f.read()) - mp3s = [] - for root, directories, files in os.walk(dirname): - for file in files: - if file[-3:] == '.mp3': - mp3s.append({root, file}) - for path, hashname in mp3s: - os.rename(path + '/' + hashname, path + '/' + self.map[hashname])) - os.remove(restore_path) - - def generateName(self, seed=time()): - return hashlib.md5(str(seed)).hexdigest() - - -def parse_arguments(): - parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(dest='subcommand', help='subcommand help') - rename_parser = subparsers.add_parser('rename', help='rename help') - rename_parser.add_argument('dirname') - rename_parser.add_argument('-o', '--output', help='path to a file where restore map is stored') - restore_parser = subparsers.add_parser('restore', help="command_a help") - restore_parser.add_argument('dirname') - restore_parser.add_argument('restore_map') - args = parser.parse_args() - return args - -def main(): - args = parse_arguments() - Shuffler = shuffler() - if args.subcommand == 'rename': - if args.output: - Shuffler.rename(args.dirname, 'restore.info') - else: - Shuffler.rename(args.dirname, args.output) - elif args.subcommand == 'restore': - Shuffler.restore(args.dirname, args.restore_map) - else: - sys.exit() - - -main()