【问题标题】:How can i get a program to loop through a changing list whilst performing operations如何让程序在执行操作时循环遍历更改列表
【发布时间】:2017-04-10 22:01:09
【问题描述】:

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

Set A 有 n 个元素Set B 从单个元素开始


现在我可以编写一个程序,从 Set 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)

【问题讨论】:

  • 使用 for 循环。

标签: list python-3.x loops elements


【解决方案1】:

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

检查集合 A 中的第一个元素是否可以被集合 B 中的所有元素完全分割。完成此检查后,来自 A 的第一个元素进入集合 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

【讨论】:

  • 非常感谢您,这对我了解如何去做对我有很大帮助。不幸的是,它不会检查 B 中的每个元素,例如输出 6 可以除以 2。
  • @Dead_Ling0 它确实检查集合 B 中的每个元素,但它只打印 true 数字 for instance 6 可以被集合 B 中的所有数字整除(甚至写在 cmets 中)。 for 循环 for j in B: 是它的行,所以这段代码循环遍历集合 B 中的每个元素。
  • 对不起,也许我应该更清楚(我现在已经改变了问题的全部部分)。我的意思是如果集合 B 中至少有 1 个元素可以将 num 整除。而不是检查 num 是否可以被所有元素整除。
  • 你自己试试看能不能解决,如果不行我帮你解决,但是你自己试试,因为这是目的性的改变。
  • 我是个白痴,在编码方面很糟糕找到了我想要的东西,这是我真的应该学习循环的 6 行简单的代码
猜你喜欢
  • 2017-10-27
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 2012-04-01
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
相关资源
最近更新 更多