首页 > 解决方案 > 仅迭代给定列表 Python 中的零

问题描述

我有一个问题,我已经为它编写了伪代码,而且我很难将它翻译成可行的 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

我的目标是尽可能简单地实现这一点,虽然我觉得我错过了一些非常明显的东西,但我很难过。

标签: pythonloopspseudocode

解决方案


嗯,最直接和容易理解的方法是只使用一个索引指针,你只需使用它一遍又一遍地迭代列表,然后使用一个计数器来计算你接下来需要跳过的空间量。一个简单的例子:

list_sizes = [4, 5]
for list_size in list_sizes:
    your_list = [0] * list_size
    index = 0
    spaces_to_skip = 1
    space_count = 0
    while spaces_to_skip <= len(your_list):
        if your_list[index] == 0:
            # Found a space at the current pointer, determine what to do.
            if space_count == spaces_to_skip:
                # Skipped the correct amount of spaces (entries with 0)
                # Set value in the list
                your_list[index] = spaces_to_skip
                # Set the new amount of spaces to skip
                spaces_to_skip += 1
                # Reset the current space counter
                space_count = 0
            else:
                # Increase the current amount of spaces found
                space_count += 1

        # Move to next entry in list or start from the beginning
        index = (index + 1) % len(your_list)
    
    print(your_list)

作为输出给出:

[2, 1, 4, 3]
[3, 1, 4, 5, 2]

推荐阅读