Skip to content Skip to sidebar Skip to footer

Python- Writing Sentence In Given Format

I have a file with one sentence. I let the user choose the number of 'rows' and 'columns'. I want to check how many times I can write the sentence in this kind of table without spl

Solution 1:

This was tougher than I thought it would be. There might be an easier solution out there but you can try this:

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)

Post a Comment for "Python- Writing Sentence In Given Format"