我怎样才能让程序在执行操作时循环遍历更改列表

How can i get a program to loop through a changing list whilst performing operations

假设我有两个包含自然数元素的列表。

集合 A 有 n 个元素集合 B 以单个元素


现在我可以编写一个程序,从集合 A 中获取一个成员,执行一个操作 包含集合 B 中的所有元素,然后将集合 A 中的元素添加到集合 B。重复此过程,直到集合 A 中的所有元素都已添加到集合 B。


示例:

Set A = {3, 4, 5, 6} & Set B = {2}

检查集合 A 中的第一个元素是否可以被集合 B 中的任何元素整除。检查完成后,A 中的第一个元素进入集合 B。

Set A = {4, 5, 6} & Set B = {2, 3}

Repeat

Set A = {5, 6} & Set B = { 2, 3, 4 } 

Repeat 

Set A = {6} & Set B = { 2, 3, 4, 5 }

Repeat

Set A = {} & Set B = { 2, 3, 4, 5, 6 }

END

已解决

def getprime(n):

for p in range(2, n+1):
    for i in range(2, p):
        if p % i == 0:
            break
    else:
        print(p)

此代码解决了您的示例问题

Check to see if the first element from set A can be divided wholly by all elements from set B. After this check has been done the first element from A goes to set B.

希望您能理解如何将此应用到其他类似问题。

A = [2, 4, 5, 6]
B = [2]

# while the list A is not empty
while len(A) > 0:
    # the first number in the list
    num = A[0]
    # for every element in list B
    for j in B:
        fully_divisible = True
        # the the number is not divisible by a number from list B
        if num % j != 0:
            fully_divisible = False

    if fully_divisible:
        # this will only print if ALL the numbers currently in list B are divisible by num
        print num, "can be divided wholly by all elements from set B"
    else:
        # this will print if there is at least one number in list B the is not divisible by num
        print num, "cannot be divided wholly by all elements from set B"

    # remove the first element from list A, next time we loop the first element of the list (A[0]) will be different
    A.remove(num)
    # add that number to list B
    B.append(num)

输出:

2 can be divided wholly by all elements from set B
4 can be divided wholly by all elements from set B
5 cannot be divided wholly by all elements from set B
6 cannot be divided wholly by all elements from set B