forked from pablorus/Python_lessons_basic
-
Notifications
You must be signed in to change notification settings - Fork 457
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Lesson05 #884
Open
AlexN-github
wants to merge
7
commits into
GeekBrainsTutorial:master
Choose a base branch
from
AlexN-github:lesson05
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Lesson05 #884
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3d8fdf7
Почти все выполено
AlexN-github 1ccbf58
Восстановил стертое случайно задание про даты
AlexN-github 336f26c
Все сделал
AlexN-github 9c5e9bc
Финал
AlexN-github bf6b232
Все выполнено
AlexN-github 736db30
Промежуточный комит
AlexN-github 6b3d15f
Сделал все
AlexN-github File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,125 @@ | ||
__author__ = 'Насонов Алексей Сергеевич' | ||
|
||
# Задача-1: | ||
# Дан список, заполненный произвольными целыми числами, получите новый список, | ||
# элементами которого будут квадратные корни элементов исходного списка, | ||
# но только если результаты извлечения корня не имеют десятичной части и | ||
# если такой корень вообще можно извлечь | ||
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2] | ||
|
||
print("Задача-1:") | ||
NumList1 = [1, 2, 3, 4, 5, -10, 25] | ||
NumList2 = [] | ||
import math | ||
for Num in NumList1: | ||
if Num >= 0: | ||
Res = math.sqrt(Num) | ||
if (float(Res) % 1) == 0: | ||
NumList2.append(int(Res)) | ||
print(NumList2) | ||
|
||
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013. | ||
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года. | ||
# Склонением пренебречь (2000 года, 2010 года) | ||
|
||
print("Задача-2:") | ||
days = ["первое", | ||
"второе", | ||
"третье", | ||
"четвертое", | ||
"пятое", | ||
"шестое", | ||
"седьмое", | ||
"восьмое", | ||
"девятое", | ||
"десятое", | ||
"одиннадцатое", | ||
"двенадцатое", | ||
"тринадцатое", | ||
"четырнадцатое", | ||
"пятнадцатое", | ||
"шестнадцатое", | ||
"семьнадцатое", | ||
"восемнадцатое", | ||
"девятнадцатое", | ||
"двадцатое", | ||
"двадцать первое", | ||
"двадцать второе", | ||
"двадцать третье", | ||
"двадцать четвертое", | ||
"двадцать пятое", | ||
"двадцать шестое", | ||
"двадцать седьмое", | ||
"двадцать восьмое", | ||
"двадцать девятое", | ||
"тридцатое", | ||
"тридцать первое"] | ||
month = ["января", | ||
"февраля", | ||
"марта", | ||
"апреля", | ||
"мая", | ||
"июня", | ||
"июля", | ||
"августа", | ||
"сентября", | ||
"октября", | ||
"ноября", | ||
"декабря"] | ||
date = "26.02.1975" | ||
D = int((date.split("."))[0]) | ||
M = int((date.split("."))[1]) | ||
Y = (date.split("."))[2] | ||
print(date) | ||
print("Дата: {0} {1} {2} года".format(days[D-1],month[M-1],Y)) | ||
|
||
|
||
# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами | ||
# в диапазоне от -100 до 100. В списке должно быть n - элементов. | ||
# Подсказка: | ||
# для получения случайного числа используйте функцию randint() модуля random | ||
|
||
print("Задача-3") | ||
import random | ||
NumList = [] | ||
# Задаем количество элементов списка случайных значений | ||
n = 10 | ||
for item in range(n): | ||
NumList.append(random.randint(-100, 100)) | ||
print(NumList) | ||
|
||
# Задача-4: Дан список, заполненный произвольными целыми числами. | ||
# Получите новый список, элементами которого будут: | ||
# а) неповторяющиеся элементы исходного списка: | ||
# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6] | ||
# б) элементы исходного списка, которые не имеют повторений: | ||
# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6] | ||
|
||
print("Задача-4") | ||
NumList1 = [1, 2, 4, 5, 6, 2, 5, 2] | ||
NumList_a = [] | ||
NumList_b = [] | ||
NumList_temp = NumList1.copy() | ||
# Выполняем проверку первого элемента и удаляем его, | ||
# если элемент встречается в исходном списке несколько раз, | ||
# то заносим его только в новый список NumList_a | ||
# если элемент встречается в исходном списке только один раз, | ||
# то добавляем его в списки NumList_a, NumList_b | ||
while NumList_temp: | ||
Num = NumList_temp[0] | ||
NumList_temp.remove(Num) | ||
if Num in NumList_temp: | ||
NumList_a.append(Num) | ||
while Num in NumList_temp: | ||
NumList_temp.remove(Num) | ||
else: | ||
NumList_a.append(Num) | ||
NumList_b.append(Num) | ||
|
||
print("Исходный список:") | ||
print(NumList1) | ||
print("Список с уникальными элементами:") | ||
print(NumList_a) | ||
print("Список без повторяющихся элементов:") | ||
print(NumList_b) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,8 +3,51 @@ | |
# из которой запущен данный скрипт. | ||
# И второй скрипт, удаляющий эти папки. | ||
|
||
# Создаем новую директорию | ||
print("Задача-1") | ||
|
||
print("Создаем директории dir_1..dir_9") | ||
import os | ||
current_path = os.getcwd() | ||
try: | ||
for i in range(1,10): | ||
FullNameDir = os.path.join(current_path, "dir_"+str(i)) | ||
os.mkdir(FullNameDir) | ||
print("Директории dir_1..dir_2 созданы") | ||
except FileExistsError: | ||
print('Директория {} уже существует'.format("dir_"+str(i))) | ||
|
||
print("Удаляем директории dir_1..dir_9") | ||
import os | ||
current_path = os.getcwd() | ||
try: | ||
for i in range(1,10): | ||
FullNameDir = os.path.join(current_path, "dir_"+str(i)) | ||
if os.path.isdir(FullNameDir): | ||
os.rmdir(FullNameDir) | ||
print("Директории dir_1..dir_2 удалены") | ||
except : | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. очень плохая практика, хотя бы Exception надо писать |
||
print('Ошибка при удалении директории {}'.format("dir_"+str(i))) | ||
|
||
#exit() | ||
|
||
|
||
# Задача-2: | ||
# Напишите скрипт, отображающий папки текущей директории. | ||
|
||
print("Задача-2") | ||
|
||
import os | ||
print([item for item in os.listdir(os.getcwd()) if os.path.isdir(item)]) | ||
|
||
# Задача-3: | ||
# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт. | ||
|
||
import sys | ||
import shutil | ||
ScriptPath = sys.argv[0] | ||
CopyScriptPath = ScriptPath+"_copy" | ||
print(ScriptPath) | ||
print(ScriptPath+"_copy") | ||
|
||
shutil.copy(ScriptPath, CopyScriptPath) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
так, а если ошибка вылетит на первой же итерации, получиться что вообще ни одной папки не создастся