我想解决以下问题:
字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)
P A H N
A P L S I I G
Y I R
然后逐行阅读:“PAHNAPLSIIGYIR”
编写将采用字符串的代码并在给定多行的情况下进行此转换:
string convert(string s,int numRows);
我编写了以下代码,但是我在粗体行中遇到错误“TypeError:不支持的操作数类型为+:'NoneType'和'unicode'”
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1:
return s
templist=[None]*numRows
ret=" "
curRow=0
goingDown=0
for each_char in s:
if templist[curRow]:
templist[curRow]=each_char
else:
**templist[curRow]=templist[curRow] + each_char**
if (curRow==numRow-1 or curRow == 0):
goingDown = not goingDown
if goingDown:
curRow=curRow+1
else:
curRow=curRow-1
for each_str in templist:
ret=ret+each_str
print ret
我在这做错了吗?如果有人可以在这里指出问题,那将会很棒。提前致谢
您的条件似乎在以下几行中颠倒过来:
if templist[curRow]:
templist[curRow]=each_char
else:
**templist[curRow]=templist[curRow] + each_char**
它可能应该是:
if templist[curRow]:
templist[curRow]=templist[curRow] + each_char
else:
templist[curRow]=each_char
如果该字符串已经存在(不是templist[curRow]
),这确保它只附加到None
中的字符串,因此避免了向None
添加字符串的错误。
更好的方法可能是设置templist = [""] * numRows
,即空字符串列表,然后使用templist[curRow] += each_char
添加到它,这将始终有效,因为您可以将字符添加到空字符串。
是的,你做错了什么。
线templist=[None]*numRows
使你的templist
变量持有一堆None
s。然后你继续使用其中一个None
s,并尝试将其中一个“添加”到一个字符串,其中包含您以粗体显示的语句:templist[curRow]=templist[curRow] + each_char
(即此赋值的右侧评估为None + each_char
)。
你不能在Python中添加字符串和None
,因此错误。
string = 'PAHNAPLSIIGYIR'
string = list(string)
rows = []
def make_output(string, num_rows):
i = 0
while i < num_rows:
if i%2 == 0:
a = []
while len(a) < 4:
if len(string)==0:
break
a.append(string.pop(0))
rows.append(a)
if i%2 != 0:
a = []
while len(a) < 7:
a.append(string.pop(0))
rows.append(a)
i += 1
for i in range(len(rows)):
if i%2 == 0:
print(' '.join(rows[i]))
if i%2 != 0:
print(' '.join(rows[i]))
make_output(string, 3)
你可以使用这样的函数,在那里你指定偶数和奇数行的长度,然后你可以从你的字符串中pop
。然后你可以只有print
偶数和奇数行与适当的间距。
(xenial)vash@localhost:~/python/AtBS$ python3.7 solve.py P A H N A P L S I I G Y I R (xenial)vash@localhost:~/python/AtBS$ python3.7 solve.py M M * H Y A E S V S * N I A