Approach

  1. Read the integer 'n' from input.
  2. Read the string message from input.
  3. Split the message into a list of words using the 'split()' method.
  4. Initialize an empty list 'lines' to store the output lines.
  5. Iterate over the words in the message.
    • If the current word is at an even index, add it to the last line in 'lines'.
    • If the current word is at an odd index, add it as a new line in 'lines'.
  6. Print each line in 'lines'.

Steps

# Read the integer n from input
n = int(input())

# Read the string message from input
message = input()

# Split the message into a list of words
words = message.split()

# Initialize an empty list to store the output lines
lines = []

# Iterate over the words in the message
for i, word in enumerate(words):
    # If the current word is at an even index, add it to the last line in lines
    if i % 2 == 0:
        if lines:
            lines[-1].append(word)
        else:
            lines.append([word])
    # If the current word is at an odd index, add it as a new line in lines
    else:
        lines.append([word])

# Print each line in lines
for line in lines:
    print(' '.join(line))

Complexity Analysis

The time complexity for this approach is O(n), where n is the number of words in the message. This is because we iterate over each word in the message once.

The space complexity for this approach is O(n), where n is the number of words in the message. This is because we store the words in a list called 'lines'.

Python Program to Print Words Alternately on Separate Lines

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

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