-
Notifications
You must be signed in to change notification settings - Fork 0
Домашнее задание к 1-ой лекции #72
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| name = input("Напиши что-нибудь: ") | ||
| print(f"Echo: {name}") |
| 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}") |
| 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) | ||
| print(f"Расход бензина: {result}") | ||
| 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. | ||
|
Owner
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. Кстати, хорошее предложение. Тем более функция time, которую Вы, по факту, предлагаете импортировать из модуля time (from time import time), как раз используется в стр.46
Collaborator
Author
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. Поняла. |
||
| from time import * | ||
|
|
||
|
|
||
| class shuffler: | ||
|
|
||
| def __init__(self): | ||
| self.map = {} | ||
|
|
||
| def rename(self, dirname, output): | ||
| mp3s = [] | ||
| # Я пока не поняла саму суть этого года, но в конце строки должно быть либо "os.walk()", либо "os.path.dirname()". | ||
|
Owner
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. Нет, в этом ошибки нет. Здесь имеется в виду переменная dirname, переданная сюда в стр.15.
Collaborator
Author
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. Поняла. |
||
| for root, directories, files in os.walk(dirname): | ||
| for file in files: | ||
| if file[-3:] == '.mp3': | ||
| # Не совсем поняла какой элемент списка mp3s будет добавляться в конец, если элементов в списке пока нет. | ||
|
Owner
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. Здесь в список mp3s добавляется ещё один список (да, так тоже можно) из пары значений root и file.
Collaborator
Author
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. Поняла. |
||
| mp3s.append([root, file]) | ||
| # В самом верху кода не указано "from pathlib import Path". | ||
|
Owner
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. Path и path - это разные, с точки зрения Python, слова. Для него регистр буквы имеет значение. В любом случае path здесь - это просто переменная. Как можно понять из предыдущего замечания, mp3s будет состоять из пар root (путь к текущему файлу) и file (имя файла). И здесь мы эти пары последовательно извлекаем из mp3s, так что path указывает на root, а mp3 - на file.
Collaborator
Author
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. Поняла. |
||
| # И непонятно как связаны "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 пробела. | ||
|
Owner
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. Не относится. Об говорит, например, отсутствие специального аргумента 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') | ||
| # В коде используются либо одинарные, либо двойные скобки. Если их и смешивают, то для цитирования '"Какой-то фразы"'. | ||
|
Owner
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. Хороший комментарий! Первый раз вижу, чтоб на это обратили внимание! Но да, всё по делу.
Collaborator
Author
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. Вы же про это говорили)
Owner
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. Да. Тут и требовалось найти ВСЕ ошибки. Только те, которые понятны. |
||
| 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(): | ||
|
Owner
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. Функция верхнего уровня (т.е. не вложенная ни в класс, ни в другую функцию) должна обособляться двумя пустыми строками (PEP8) А чем эта функция хуже других?
Collaborator
Author
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. О! Это интересно. Спасибо за разъяснение! |
||
| 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() используется для разделения блоков кода в программе. Какой смысл от неё в конце кода? | ||
|
Owner
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. Почему она используется для разделения блоков в программе? |
||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # Написать программу для расчёта периметра прямоугольника по введённым длине и ширине. | ||
|
|
||
| long = input("Введите длинну: ") | ||
| width = input("Введите ширину: ") | ||
| sguare = (int(long) + int(width)) * 2 | ||
|
Owner
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. Название переменной sguare вводит в заблуждение) Мы же всё-таки периметр рассчитываем, а не площадь.
Collaborator
Author
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. Когда делала задание, думала о периметре, а написала площадь facepalm. |
||
| print(sguare) | ||
| 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), "км/ч.") | ||
|
Owner
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. Можно уже попробовать форматную строку применить;)
Collaborator
Author
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. Что за форматная версия приложения?
Owner
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. "форматная версия приложения"??? print(f"Средняя скорость автомобиля: {int(average_speed)}км/ч.") |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| code = 65498 | ||
| key = 356 | ||
| res = code ^ key | ||
| print(res) | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| has = 65214 | ||
| key = 356 | ||
| res = has ^ key | ||
| print(res) | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Написать программу, заменяющую все буквы “А” в слове, введённом пользователем, на символ “*”. | ||
|
|
||
| s = input('Напишите слово, начинающееся на букву "А": ') | ||
| print(s.replace("А", "*", 1)) | ||
|
Owner
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. А почему только одну букву А заменяем? Надо же ВСЕ.
Collaborator
Author
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. То, что две подряд АА программа не заменяет, я сейчас вижу. Исправлю.
Owner
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. В задании речь только о большой букве "А" |
||
|
|
||
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.
diff - и так число, потому что определён как разность двух чисел (в стр.4). Поэтому в int здесь его можно не оборачивать.
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.
Поняла.