-
Notifications
You must be signed in to change notification settings - Fork 0
homework lec.1 #8
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
b63ff7e
8eb8802
073c535
081466b
62bb0e1
16ddbc8
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,16 @@ | ||
| w = input("Введите слово: ") | ||
| w = w.lower() | ||
|
|
||
| def palindrome(w): | ||
| if len(w) == 1 or len(w) == 0: | ||
|
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. Можно чуть упростить: if len(w) < 2 |
||
| return 0 | ||
| if w[0] == w[-1]: | ||
| return palindrome(w[1:-1]) | ||
| else: | ||
| return 1 | ||
|
|
||
| test = palindrome(w) | ||
|
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. Замечательная идея - реализовать функцию через рекурсию! Если вместо 0/1 возвращать True/False, то и проверку можно чуть упростить: if palindrom(w):
print("Это палиндром")
else:
print("Введённое слово не является палиндромом")Есть, правда пара нюансов:
def palindrome_ci(w): # ci - case insensitive - регистронезависимый
def palindrome(w):
# здесь ваш код для рекурсивной проверки на палиндром
return palinfrome(w.lower())
w = input("Введите слово: ")
if palindrome_ci(w):
.... |
||
| if test == 0: | ||
| print("Это палиндром") | ||
| elif test == 1: | ||
| print("Введённое слово не является палиндромом") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| def biggest(a, b): | ||
| if a > b: | ||
| print(a) | ||
| else: | ||
| print(b) | ||
| biggest(2, 3) | ||
|
|
||
|
|
||
| def returnbiggest(a, b): | ||
| if a > b: | ||
| return a | ||
| else: | ||
| return b | ||
|
|
||
|
|
||
| c = returnbiggest(8, 7) | ||
| print(c) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| num = int(input("Введите пятизначное число: ")) | ||
| for i in range(4, -1, -1): | ||
| n = (num % 10**(i + 1)) // 10**i | ||
|
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. Да, если работать c num, как с числом, то проще не получится. И с этой точки зрения решение корректное. НО мы же запросто можем привести число к строковому типу и работать с ним, как с последовательностью символов (тем более input сразу возвращает строку), тогда и никакие сложные вычисления не потребуются. |
||
| print(5 - i, "цифра равна", n) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| 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]) # лишний отступ | ||
|
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. В этой строке с отступами все в порядке. PyCharm может подсвечивать эту строку, как ошибочную из-за строки 15. Интерпретатор Python требует, чтоб все строки внутри блока выравнивались одинаковыми отступами, однако не указывает конкретный размер этих отступов. Строка 15 и строки 16-19 относятся к одному блоку, но имеют разное выравнивание. Это несоответствие и сбивает PyCharm с толку. Согласно рекомендациям PEP8, размер отступа - 4 пробела, поэтому строки 16-19 можно считать отформатированными корректно, а строку 15 - ошибочной. |
||
| 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: # лишние отступы | ||
|
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. Только в этой строке или во всем блоке 28-30? |
||
| 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() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| class Tank: | ||
|
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. Нужно еще создать экземпляр класса Tank (ниже) и написать примеры вызова его методов. |
||
| x = 0 | ||
| y = 0 | ||
| color = 0 | ||
| speed = 1 | ||
|
|
||
| def Move (self, direction): | ||
| if direction == "up" and y < 20: | ||
| y = y - speed | ||
| if direction == "right" and x < 20: | ||
| x = x - speed | ||
| if direction == "down" and y > 0: | ||
| y = y + speed | ||
| if direction == "left" and x > 0: | ||
| x = x + speed | ||
| print(f"Moving to (x).(y)") | ||
|
|
||
| def Shoot(self): | ||
| print("shooting") | ||
|
|
||
|
|
||
| class Map: | ||
| # Массив ячеек | ||
| width = 20 | ||
| length = 20 | ||
|
|
||
|
|
||
| class Cell: | ||
| wall = 0 | ||
| ''' | ||
| Поле состоит из клеток | ||
| Клетка либо пуста, либо содержит препятствие | ||
| ''' | ||
|
|
||
|
|
||
| class Shot: | ||
| direction # выстрел имеет направление | ||
|
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. Просто так объявлять поля класса бессмысленно. Надо им присвоить какие-то значения. |
||
| distance # дистанция, которую он преодолевает | ||
| color | ||
| speed | ||
| coordinate | ||
|
|
||
| def Move(self): | ||
|
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. Здесь и в стр.45: функции и методы без тела интерпретатор не пропустит. Надо добавить хотя бы pass. |
||
|
|
||
| def Hit(self): # Выстрел поразил цель или нет | ||
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.
Небольшое замечание по стилю: определения функций и классов обычно пишутся в начале файла, а весь код в глобальной области видимости (вне каких-либо функций и классов) - внизу.