PAT 1031 Hello World for U python解法

1031 Hello World for U (20 分)
Given any string of N (≥5) characters, you are asked to form the characters into the shape of U. For example, helloworld can be printed as:

h  d
e  l
l  r
lowo

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n​1​​ characters, then left to right along the bottom line with n​​2​​ characters, and finally bottom-up along the vertical line with n​​3​​ characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that n​1​​ = n​​3 ​​= max { k | k ≤ n​2​​ for all 3 ≤ n​2 ​​≤ N} with n​​1 + n​​2​​ + n​3​​ − 2 = N.

Input Specification:
Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space.

Output Specification:
For each test case, print the input string in the shape of U as specified in the description.

Sample Input:

helloworld!

Sample Output:

h   !
e   d
l   l
lowor

题意:将一串字符U型输出,满足n​1​​ = n​​3 ​​= max { k | k ≤ n​2​​ for all 3 ≤ n​2 ​​≤ N} with n​​1 + n​​2​​ + n​3​​ − 2 = N.。这里要理解n​1、n​2和n​3指的是哪些字符。如图:蓝色是n​1,红色是n​2,绿色是n​3
在这里插入图片描述
解题思路:理清题意后就很简单了,首先为了满足题设条件,n​1​​ = n​3​​ = (N+2)/3,n​2​​ = N - 2 - n​1 - n​3,得到n​1、n2、n​3之后,先输出n​1-1行,每一行是字符串的头和尾以及中间加上n2+2个空格,最后输出中间的字符。

s = input()
n1 = (len(s)+2)//3
n2 = len(s) - 2*n1 -2
for i in range(n1-1):
    print(s[i] + ' '*(n2+2) + s[-i-1])
print(s[n1-1:len(s)-n1+1])

你可能感兴趣的:(python,用Python刷PAT,(Advanced,Level),Practice)