首页 > 解决方案 > Python equivalence for this c++ program

问题描述

I am having trouble solving problems in python because I can't find any equivalent for this while (getline()) in python. So even though I solve my problems they are not accepted because of the right way of taking input. How can I recode this in python? especially the while block!

#include <iostream>
#include <string>

using namespace std;

string sentences[105];

int main()
{
    int pos = 0;
    int longest = 0;
    while (getline(cin, sentences[pos]))
    {
        if (sentences[pos].size() > longest)
            longest = sentences[pos].size();
        ++pos;
    }

    for (int j = 0; j < longest; ++j)
    {
        for (int i = pos - 1; i >= 0; --i)
        {
            if (sentences[i].size() > j)
                cout << sentences[i][j];
            else
                cout << ' ';
        }
        cout << '\n';
    }
}

This is my python code.

while True:
    try:
        lst = []
        n = 0
        while True:
            line1 = [' ']*100
            line = input()
            if n < len(line):
                n = len(line)
            for i in range(len(line)):
                line1[i] = line[i]
            if line:
                lst.append(line1)
            else:
                break
        for i in range(0,n):
            x = '' 
            for j in range(len(lst)-1,-1,-1):
                x += lst[j][i]
            print(x)
    except EOFError:
        break

标签: pythonpython-3.x

解决方案


Python 2.7中,您有:

line = raw_input("Please input a new line: ")

Python 3.5+中,您有:

line = input("Please input a new line: ")

两者都raw_input返回input一个字符串对象。您需要解析/扫描line以检索您的数据。

MESSAGE = "Please input a new line: "

# I comprehend that `sentences` is a list of lines
sentences = []
longest = 0

line = input(MESSAGE)

while line:
    # Loop continues as long as `line` is available

    # Keep a track of all the lines
    sentences.append(line)
    # Get the length of this line
    length = len(line)

    if length > longest:
        longest = length

    for i in range(longest):
        for j in range(len(sentences) - 1, -1, -1):
            if len(sentences[j]) > i:
                print(sentences[j][i])

    line = input(MESSAGE)

推荐阅读