【发布时间】:2021-02-15 14:45:38
【问题描述】:
我有一个问题,我已经为它编写了伪代码,我很难将它翻译成可行的 Python 代码。它的工作原理是这样的:我列表中的 0 代表我可以插入数字的可用位置,我想通过计算空闲空间将下一个数字插入下一个可用位置,然后我将计数的位置数量增加 1对于每个循环。我也在尝试编写此代码以使用任何给定大小的列表。我的第一次尝试是尝试索引超出列表的大小,认为它会循环返回,但它不起作用,因为您无法索引列表中不存在的位置。
这是伪代码:
Cycle 1: Count 1 space starting from first available space: 0 1 0 0 0
Cycle 2: Count 2 spaces starting from first available space from last insertion: 0 1 0 0 2
Cycle 3: Count 3 spaces starting from first available space from last insertion: 3 1 0 0 2
Cycle 4: Count 4 spaces starting from first available space from last insertion: 3 1 4 0 2
Cycle 5: Count 5 spaces starting from first available space from last insertion: 3 1 4 5 2
注意:插入到列表中的数字从 1 开始,每循环一次就增加 1。
这是我目前设置的代码:
#The output for list of size 4 should have the numbers in this order: 2 1 4 3
#The output for list of size 5 should have the numbers in this order: 3 1 4 5 2
results = [4, 5]
print(results)
for i in results:
myList = [0] * i
print(myList)
count = 0
while count < len(myList):
myList[count] = count+1
print(myList)
count += 1
我的目标是尽可能简单地实现这一点,虽然我觉得我错过了一些非常明显的东西,但我很难过。
【问题讨论】:
-
有没有可能没有零剩下但你还需要数数?
-
不,我们只循环直到这个特定问题的列表中没有 0。
标签: python loops pseudocode