1 回答

TA贡献1887条经验 获得超5个赞
这比我想象的要艰难。可能有一个更简单的解决方案,但你可以试试这个:
list_of_words = text.split()
current_character_count_for_row = 0
current_string_for_row = ""
current_row = 1
how_many_times_has_sentence_been_written = 0
is_space_available = True
# Keep going until told to stop.
while is_space_available:
for word in list_of_words:
# If a word is too long for a row, then return false.
if len(word) > columns:
is_space_available = False
break
# Check if we can add word to row.
if len(word) + current_character_count_for_row < columns:
# If at start of row, then just add word if short enough.
if current_character_count_for_row == 0:
current_string_for_row = current_string_for_row + word
current_character_count_for_row += len(word)
# otherwise, add word with a space before it.
else:
current_string_for_row = current_string_for_row +" " + word
current_character_count_for_row += len(word) + 1
# Word doesn't fit into row.
else:
# Fill rest of current row with *'s.
current_string_for_row = current_string_for_row + "*"*(columns - current_character_count_for_row)
# Print it.
print(current_string_for_row)
# Break if on final row.
if current_row == rows:
is_space_available = False
break
# Otherwise start a new row with the word
current_row +=1
current_character_count_for_row = len(word)
current_string_for_row = word
if current_row > rows:
is_space_available = False
break
# Have got to end of words. Increment the count, unless we've gone over the row count.
if is_space_available:
how_many_times_has_sentence_been_written +=1
print(how_many_times_has_sentence_been_written)
添加回答
举报