Python Program to Print Words Alternately on Separate Lines
Approach
- Read the integer 'n' from input.
- Read the string message from input.
- Split the message into a list of words using the 'split()' method.
- Initialize an empty list 'lines' to store the output lines.
- 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'.
- 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'.
原文地址: https://www.cveoy.top/t/topic/pc8C 著作权归作者所有。请勿转载和采集!