Python Program to Print Words Alternately in Separate Lines

This Python program demonstrates how to take an integer 'n' and a string as input and print the words of the string alternately in 'n' separate lines. The code provides a clear explanation of the algorithm and includes an example to illustrate the process.

Code:

# Read the input values
n = int(input())
message = input()

Separate the words in the message

words = message.split()

Initialize a variable to keep track of the current line number

line_number = 1

Initialize an empty list to store the words for each line

lines = [[] for _ in range(n)]

Iterate through each word in the message

for word in words: # Add the word to the current line lines[line_number - 1].append(word)

# Increment the line number and wrap around if necessary
line_number = (line_number % n) + 1

Print each line

for line in lines: print(' '.join(line))

Explanation:

  • Input: The program reads two inputs: an integer 'n' representing the number of lines and a string containing the message.
  • Word Separation: The message is split into individual words using the split() method.
  • Line Management: A variable 'line_number' tracks the current line, and a list 'lines' stores the words for each line.
  • Word Allocation: Each word is added to the appropriate line in the 'lines' list based on the 'line_number'. The 'line_number' is then incremented, and the modulo operation (%) ensures that it wraps around to the beginning when it reaches the end of the lines.
  • Output: Finally, the program prints each line in the 'lines' list, joining the words with spaces.

Example:

Input:
2
This If is you not are a reading very this good then way you to have hide done a it message. wrong.

Output: This is not a very good way to hide a message. If you are reading this then you have done it wrong.

Constraints:

  • 2 < n < 10
  • 1 ≤ Length of the string ≤ 256
Python Program to Print Words Alternately in Separate Lines

原文地址: https://www.cveoy.top/t/topic/pc8Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录