Skip to content

Instantly share code, notes, and snippets.

@Suor
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Suor/0e60c8bcbf6add69b791 to your computer and use it in GitHub Desktop.
Save Suor/0e60c8bcbf6add69b791 to your computer and use it in GitHub Desktop.
Text Justify Code Review
import textwrap
# def task_with_text(text, width):
# new_text = textwrap.TextWrapper()
# new_text.width = width
# return new_text
#print task_with_text("Napoleon was born on the island of Corsica to a relatively modest family of noble Italian ancestry.", 7)
# def justify_line(line, width):
# pass
text = """Napoleon was born on the island of Corsica to a relatively modest family of noble
Italian ancestry"""
text_list = textwrap.wrap(text, 20) # all text in list divided to strings - future lines
#print text_list
number_of_line = 0
for e in text_list:
if len(e) == 20:
number_of_line = number_of_line + 1
continue
else:
#e = text_list[1] #second stroph
line_list = e.split()#stroph as a list
last_element = line_list.pop()
number_of_rest_expand_spaces = 20 - len(e)
index = 0
while number_of_rest_expand_spaces > 0:
line_list[index] = line_list[index] + " "
index = index + 1
number_of_rest_expand_spaces = number_of_rest_expand_spaces - 1
if index == len(line_list):
index = 0
line_list.append(last_element)
text_list[number_of_line] = " ".join(line_list)
number_of_line = number_of_line + 1
text_string = " ".join(text_list)
wrapped_text = textwrap.fill(text_string, 20)
print wrapped_text
# -*- coding: utf-8 -*-
import textwrap
# R: мёртвый код
# def task_with_text(text, width):
# new_text = textwrap.TextWrapper()
# new_text.width = width
# return new_text
#print task_with_text("Napoleon was born on the island of Corsica to a relatively modest family of noble Italian ancestry.", 7)
# R: слишком длинная строка
text = """Napoleon was born on the island of Corsica to a relatively modest family of noble Italian ancestry"""
# R: text_list -> lines
# R: использовать именованную константу вместо 20 - это магическое число
# R: мы уже разбили текст на строки, просто пока без выравнивания, коммент несколько путает
text_list = textwrap.wrap(text, 20) # all text in list divided to strings - future lines
#print text_list
number_of_line = 0 # R: line_number
for e in text_list: # R: for line in lines:
if len(e) == 20:
number_of_line = number_of_line + 1 # R: number_of_line += 1
continue
else:
#e = text_list[1] #second stroph
# R: words = line.split()
line_list = e.split()#stroph as a list
last_element = line_list.pop() # R: не надо менять список, просто last_word = words[-1]
# хотя на самом деле эта строчка вообще не нужна
number_of_rest_expand_spaces = 20 - len(e) # R: spare_spaces_left
# RR: можно распределять сразу несколько пробелов, тогда сработает for
index = 0
while number_of_rest_expand_spaces > 0:
line_list[index] = line_list[index] + " " # R: words[index] += ' '
index = index + 1
number_of_rest_expand_spaces = number_of_rest_expand_spaces - 1
if index == len(line_list): # R: использовать неравенство
index = 0
line_list.append(last_element)
text_list[number_of_line] = " ".join(line_list)
number_of_line = number_of_line + 1
# R: wrapped_text = '\n'.join(lines)
text_string = " ".join(text_list)
wrapped_text = textwrap.fill(text_string, 20)
print wrapped_text
# -*- coding: utf-8 -*-
import textwrap
TEXT_WIDTH = 20
text = """Napoleon was born on the island of Corsica to a relatively modest
family of noble Italian ancestry"""
# Split text into lines
lines = textwrap.wrap(text, TEXT_WIDTH)
# R: следует большие блоки кода разбивать пустыми строками на логические куски,
# блоки кода можно и нужно сопровлждать комментариями
line_number = 0
for line in lines:
if len(line) == TEXT_WIDTH:
# R: одно и то же действие в двух местах, следует преобразовать этот
# код так, чтобы эти места совместились
line_number += 1
continue
else:
words = line.split()
spare_spaces_left = TEXT_WIDTH - len(line)
index = 0
while spare_spaces_left > 0:
words[index] += " "
index += 1 # R: манипуляции с индексом следует собрать в кучу
spare_spaces_left -= 1
if index >= len(words) - 1:
index = 0
lines[line_number] = " ".join(words)
line_number += 1
print '\n'.join(lines)
# -*- coding: utf-8 -*-
import textwrap
TEXT_WIDTH = 20
# R: width сделан параметром, чтобы функция была чистой
def justify_line(line, width):
words = line.split()
spare_spaces_left = width - len(line)
index = 0
while spare_spaces_left > 0:
words[index] += " "
spare_spaces_left -= 1
# Переходим к следующему слову, если слова кончились, а пробелы нет,
# то возвращаемся к первому
index += 1
if index >= len(words) - 1:
index = 0
return " ".join(words)
# R: следует выделить работу ещё в одну функцию, т.к. тут смешивается задание и работа
text = """Napoleon was born on the island of Corsica to a relatively modest
family of noble Italian ancestry"""
# R: этот комментарий не особо необходим
# Split text into lines
lines = textwrap.wrap(text, TEXT_WIDTH)
# R: в питоне есть идеоматический способ идти по массиву с индексами - enumerate()
line_number = 0
for line in lines:
if len(line) < TEXT_WIDTH:
lines[line_number] = justify_line(line, TEXT_WIDTH)
line_number += 1
print '\n'.join(lines)
# -*- coding: utf-8 -*-
import textwrap
TEXT_WIDTH = 20
def justify_line(line, width):
words = line.split()
spare_spaces_left = width - len(line)
index = 0
while spare_spaces_left > 0:
words[index] += " "
spare_spaces_left -= 1
# Переходим к следующему слову, если слова кончились, а пробелы нет,
# то возвращаемся к первому
index += 1
if index >= len(words) - 1:
index = 0
return " ".join(words)
def justify_text(text, width):
lines = textwrap.wrap(text, TEXT_WIDTH)
# R: можно использовать списковое выражение
for line_number, line in enumerate(lines):
lines[line_number] = justify_line(line, TEXT_WIDTH)
return '\n'.join(lines)
text = """Napoleon was born on the island of Corsica to a relatively modest
family of noble Italian ancestry"""
print justify_text(text, TEXT_WIDTH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment