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
16 changes: 16 additions & 0 deletions Practice/obugrova/lec.3_Palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
w = input("Введите слово: ")
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.

Небольшое замечание по стилю: определения функций и классов обычно пишутся в начале файла, а весь код в глобальной области видимости (вне каких-либо функций и классов) - внизу.

w = w.lower()

def palindrome(w):
if len(w) == 1 or len(w) == 0:
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.

Можно чуть упростить: if len(w) < 2

return 0
if w[0] == w[-1]:
return palindrome(w[1:-1])
else:
return 1

test = palindrome(w)
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.

Замечательная идея - реализовать функцию через рекурсию! Если вместо 0/1 возвращать True/False, то и проверку можно чуть упростить:

if palindrom(w):
    print("Это палиндром")
else:
    print("Введённое слово не является палиндромом")

Есть, правда пара нюансов:

  1. w[1:-1] - это копирование подсписка, что может оказаться достаточно затратной по времени операцией; лучше передавать тот же список (w) и два индекса, которые будут сравниваться (1 и -1, 2 и -2, и так пока первый не превысит len(w)/2).
  2. Лучше если lower() будет выполняться внутри функции, т.к. эта операция тоже относится к проверке на палиндром, а чтоб lower() не выполнялся на каждом рекурсивном вызове, можно сделать функцию-обертку:
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("Введённое слово не является палиндромом")
17 changes: 17 additions & 0 deletions Practice/obugrova/lec2_ex.1,2.py
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)
4 changes: 4 additions & 0 deletions Practice/obugrova/lec_4, ex_2.py
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
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.

Да, если работать c num, как с числом, то проще не получится. И с этой точки зрения решение корректное. НО мы же запросто можем привести число к строковому типу и работать с ним, как с последовательностью символов (тем более input сразу возвращает строку), тогда и никакие сложные вычисления не потребуются.

print(5 - i, "цифра равна", n)
69 changes: 69 additions & 0 deletions Practice/obugrova/pep8task.py
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]) # лишний отступ
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.

В этой строке с отступами все в порядке. 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: # лишние отступы
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.

Только в этой строке или во всем блоке 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()
45 changes: 45 additions & 0 deletions Practice/obugrova/tanks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class Tank:
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.

Нужно еще создать экземпляр класса 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 # выстрел имеет направление
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.

Просто так объявлять поля класса бессмысленно. Надо им присвоить какие-то значения.

distance # дистанция, которую он преодолевает
color
speed
coordinate

def Move(self):
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.

Здесь и в стр.45: функции и методы без тела интерпретатор не пропустит. Надо добавить хотя бы pass.


def Hit(self): # Выстрел поразил цель или нет