Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Practice/mkudryavceva/Practice_11.05.2023_04.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
name = input("Напиши что-нибудь: ")
print(f"Echo: {name}")
10 changes: 10 additions & 0 deletions Practice/mkudryavceva/Practice_15.05.2023_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import math


def square(r):
return math.pi * r ** 2


radius = input("Введите радиус: ")
result = square(int(radius))
print(f"Площадь круга: {result}")
6 changes: 6 additions & 0 deletions Practice/mkudryavceva/Practice_15.05.2023_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
start = input("Топлива было: ")
end = input("Топлива осталось: ")
distance = input("Расстояние: ")
diff = int(start) - int(end)
result = int(diff) / int(distance)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

diff - и так число, потому что определён как разность двух чисел (в стр.4). Поэтому в int здесь его можно не оборачивать.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

print(f"Расход бензина: {result}")
79 changes: 79 additions & 0 deletions Practice/mkudryavceva/Practice_15.05.2023_03.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import sys
import os
import hashlib
import ast
import argparse
# Возможно, здесь знак умножения нужно заменить на time.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, хорошее предложение. Тем более функция time, которую Вы, по факту, предлагаете импортировать из модуля time (from time import time), как раз используется в стр.46
Только "знак умножения" лучше назвать "звёздочкой", т.к. в этом контексте он точно не обозначает умножение.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

from time import *


class shuffler:

def __init__(self):
self.map = {}

def rename(self, dirname, output):
mp3s = []
# Я пока не поняла саму суть этого года, но в конце строки должно быть либо "os.walk()", либо "os.path.dirname()".
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет, в этом ошибки нет. Здесь имеется в виду переменная dirname, переданная сюда в стр.15.
os.walk(dirname) - это обход всех файлов и папок, лежащих в папке dirname.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

for root, directories, files in os.walk(dirname):
for file in files:
if file[-3:] == '.mp3':
# Не совсем поняла какой элемент списка mp3s будет добавляться в конец, если элементов в списке пока нет.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь в список mp3s добавляется ещё один список (да, так тоже можно) из пары значений root и file.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

mp3s.append([root, file])
# В самом верху кода не указано "from pathlib import Path".
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Path и path - это разные, с точки зрения Python, слова. Для него регистр буквы имеет значение. В любом случае path здесь - это просто переменная. Как можно понять из предыдущего замечания, mp3s будет состоять из пар root (путь к текущему файлу) и file (имя файла). И здесь мы эти пары последовательно извлекаем из mp3s, так что path указывает на root, а mp3 - на file.
Мы это еще будем разбирать детально, когда пройдем функции и списки.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поняла.

# И непонятно как связаны "mp3" и "mp3s", если "mp3s" является списком, то что такое "mp3"?
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" относиться к "class shuffler", то должно отступить 4 пробела.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не относится. Об говорит, например, отсутствие специального аргумента self, который есть у функций выше. Этот аргумент по PEP8 принято использовать только в методах - функция, которые лежат внутри классов.

def parse_arguments():
# Такое чувство, что в этом блоке либо нужно проставить if, else, либо переименовать функции.
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')
# В коде используются либо одинарные, либо двойные скобки. Если их и смешивают, то для цитирования '"Какой-то фразы"'.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хороший комментарий! Первый раз вижу, чтоб на это обратили внимание! Но да, всё по делу.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы же про это говорили)
P.S. пыталась найти хоть какие-то ошибки, которые я понимаю что это ошибки.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да. Тут и требовалось найти ВСЕ ошибки. Только те, которые понятны.

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():
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функция верхнего уровня (т.е. не вложенная ни в класс, ни в другую функцию) должна обособляться двумя пустыми строками (PEP8) А чем эта функция хуже других?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

О! Это интересно. Спасибо за разъяснение!

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() используется для разделения блоков кода в программе. Какой смысл от неё в конце кода?
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему она используется для разделения блоков в программе?
Это обычная функция) В стр.65-76 она определяется (описывается, как она должна работать). А здесь она вызывается. По сути, это единственная строчка основного кода в этом файле.

main()
6 changes: 6 additions & 0 deletions Practice/mkudryavceva/Practice_18.05.2023_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Написать программу для расчёта периметра прямоугольника по введённым длине и ширине.

long = input("Введите длинну: ")
width = input("Введите ширину: ")
sguare = (int(long) + int(width)) * 2
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название переменной sguare вводит в заблуждение) Мы же всё-таки периметр рассчитываем, а не площадь.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Когда делала задание, думала о периметре, а написала площадь facepalm.
Буду более внимательней.

print(sguare)
7 changes: 7 additions & 0 deletions Practice/mkudryavceva/Practice_18.05.2023_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Написать программу для расчёта средней скорости автомобиля по введённым значениям времени и расстояния,
# пройденного за это время.

time = input("Введите время: ")
distance = input("Введите расстояние: ")
average_speed = int(distance) / int(time)
print("Средняя скорость автомобиля: ", int(average_speed), "км/ч.")
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно уже попробовать форматную строку применить;)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что за форматная версия приложения?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"форматная версия приложения"???
Нет, всего лишь форматная строка:

print(f"Средняя скорость автомобиля: {int(average_speed)}км/ч.")

5 changes: 5 additions & 0 deletions Practice/mkudryavceva/Practice_18.05.2023_03_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
code = 65498
key = 356
res = code ^ key
print(res)

5 changes: 5 additions & 0 deletions Practice/mkudryavceva/Practice_18.05.2023_03_code2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
has = 65214
key = 356
res = has ^ key
print(res)

5 changes: 5 additions & 0 deletions Practice/mkudryavceva/Practice_18.05.2023_04.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Написать программу, заменяющую все буквы “А” в слове, введённом пользователем, на символ “*”.

s = input('Напишите слово, начинающееся на букву "А": ')
print(s.replace("А", "*", 1))
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему только одну букву А заменяем? Надо же ВСЕ.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То, что две подряд АА программа не заменяет, я сейчас вижу. Исправлю.
А программа должна заменять "А" в верхнем и нижнем регистре?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В задании речь только о большой букве "А"