gpt4 book ai didi

python - 在 List[int] 中将 0 替换为 01,将 1 替换为 10

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:02 25 4
gpt4 key购买 nike

我正在努力解决问题K-th Symbol in Grammar - LeetCode

On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001

我写了这么一个replace函数

        def replace(row: "List[int]") -> "List[int]":
"""
rtype: row
"""
for i in range(len(row)):
if row[i] == 0: #0 -> 01
row.insert(i+1, 1)
elif row[i] == 1: #1 -> 10
row.insert(i+1, 0)
return row

但是,它不能正常工作。

In [3]: r2 = replace([0])                                                                                                     
In [4]: r2
Out[4]: [0, 1]
In [5]: r3 = replace(r2); print(r3)
[0, 1, 0, 1] # correct is [0, 1, 1, 0]
In [6]: r4 = replace(r3); print(r4)
[0, 1, 0, 1, 0, 1, 0, 1] #correct is ['0', '1', '1', '0', '1', '0', '0', '1']

使用新列表也不行。

    def replace(row: "List[int]") -> "List[int]":
"""
rtype: row
"""
copy = list(row)
for i in range(len(copy)):
if copy[i] == 0: #0 -> 01
row.insert(i+1, 1)
elif copy[i] == 1: #1 -> 10
row.insert(i+1, 0)
return row

有什么问题?

最佳答案

str.joindict一起使用:

a = '0'
d = {'0': '01', '1': '10'}
# Now run below line only
a = ''.join(d[s] for s in a)
a

输出:

01
0110
01101001
...

关于python - 在 List[int] 中将 0 替换为 01,将 1 替换为 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com