【问题标题】:Best way to perform calculations on a list/tuple in Python 3x在 Python 3x 中对列表/元组执行计算的最佳方法
【发布时间】:2016-08-03 02:49:58
【问题描述】:

我编写了这个程序,它会告诉你输入的两个 multiples 因数。前任。如果我输入 35(一个半素数),程序会输出 5 和 7,这是乘以 35 的两个素数。

但我想知道是否有更简洁或 Python 的方式来遍历这个元组,这样我就不必编写您在下面看到的所有“elif”语句。

如果我不需要依赖任何外部库,那就太好了。

# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

        try:
                semiprime = int(input('Enter Semiprime: '))

        except ValueError:
                print('INPUT MUST BE AN INTEGER')
                continue

        # index 0 - 3
        if (tuple1[0]) * (tuple1[0]) == semiprime:
                print((tuple1[0]), (tuple1[0]))

        elif (tuple1[0]) * (tuple1[1]) == semiprime:
                print((tuple1[0]), (tuple1[1]))

        elif (tuple1[0]) * (tuple1[2]) == semiprime:
                print((tuple1[0]), (tuple1[2]))

        elif (tuple1[0]) * (tuple1[3]) == semiprime:
                print((tuple1[0]), (tuple1[3]))

        # index 1 - 3
        elif (tuple1[1]) * (tuple1[0]) == semiprime:
                print((tuple1[1]), (tuple1[0]))

        elif (tuple1[1]) * (tuple1[1]) == semiprime:
                print((tuple1[1]), (tuple1[1]))

        elif (tuple1[1]) * (tuple1[2]) == semiprime:
                print((tuple1[1]), (tuple1[2]))

        elif (tuple1[1]) * (tuple1[3]) == semiprime:
                print((tuple1[1]), (tuple1[3]))

        # index 2 - 3
        elif (tuple1[2]) * (tuple1[0]) == semiprime:
                print((tuple1[2]), (tuple1[0]))

        elif (tuple1[2]) * (tuple1[1]) == semiprime:
                print((tuple1[2]), (tuple1[1]))

        elif (tuple1[2]) * (tuple1[2]) == semiprime:
                print((tuple1[2]), (tuple1[2]))

        elif (tuple1[2]) * (tuple1[3]) == semiprime:
                print((tuple1[2]), (tuple1[3]))

        #index 3 - 3
        elif (tuple1[3]) * (tuple1[0]) == semiprime:
                print((tuple1[3]), (tuple1[0]))

        elif (tuple1[3]) * (tuple1[1]) == semiprime:
                print((tuple1[3]), (tuple1[1]))

        elif (tuple1[3]) * (tuple1[2]) == semiprime:
                print((tuple1[3]), (tuple1[2]))

【问题讨论】:

  • @jedwards 的方式是智慧!嵌套的 for 循环似乎也可以。
  • 您可以计算给定数的素数分解,而不是将自己限制在预先计算的素数列表中,使用素数检查函数或生成素数的函数,如 Eratostenes 筛

标签: python python-3.x tuples


【解决方案1】:

我在评论中暗示了这一点,但意识到仅指向函数文档的链接可能还不够。

以下是使用itertools.combinations_with_replacement 编写代码的方法:

from itertools import combinations_with_replacement

# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )

# tuple 1 calculations
while True:

    try:
        semiprime = int(input('Enter Semiprime: '))

    except ValueError:
        print('INPUT MUST BE AN INTEGER')
        continue

    for (x,y) in combinations_with_replacement(tuple1, 2):
        if x * y == semiprime:
            print(x,y)

好多了,IMO :)

编辑:以前的版本使用 itertools.combinations,它不会产生具有相同值的 (x,y) 对(例如,(x,y) = (2,2) 永远不会发生)。 combinations_with_replacement 允许重复。感谢@Copperfield 指出这一点。

【讨论】:

  • 在这种情况下,我认为 combinations_with_replacement 是正确的,因为 OP 还会检查相同位置的元素
  • @Copperfield 你是对的,他们这样做了——编辑它。
  • @jedwards 好多了,谢谢!但是在 for 循环中,函数参数中的 '2' 是什么?
  • @miro.kh combinations_with_replacement 的第二个参数,在这种情况下为2,是您从中获得的每组结果的期望大小,2 得到(2, 2), (2, 3), (2, 5), (2, 7), (3, 3), ...,3你会得到(2, 2, 2), (2, 2, 3), (2, 2, 5), (2, 2, 7), (2, 3, 3), ...
  • @miro.kh 组合的长度/要产生的元素数量。
【解决方案2】:

虽然 jedwards 演示了最 Pythonic 的方法 - 使用您将了解和喜爱的 itertools 库 - 这里是更“经典”的方法,使用 for 循环来实现您想要的模式。我提出它是因为作为一个编程初学者,了解这个基本的命令式习语很重要:

>>> tuple1 = (2,3,5,7)
>>> for i in range(len(tuple1)):
...   for j in range(i+1, len(tuple1)):
...     print(tuple1[i], tuple1[j])
... 
2 3
2 5
2 7
3 5
3 7
5 7
>>> 

因此,您的代码将缩短为:

for i in range(len(tuple1)):
    for j in range(i+1, len(tuple1)):
        if tuple1[i] * tuple1[j] == semiprime
            print(tuple1[i], tuple1[j])

【讨论】:

  • 我不讨厌嵌套循环,但我认为迭代元组(例如for e1 in tuple1: for e2 in tuple1: ...)可能会更好
  • @jedwards 但是你会得到产品,而不是每个独特的组合。您可以通过使用切片(或者更好的是,islice)并遍历元组来避免这种情况,但我不想提出这个问题,因为无论如何它都是重要的模式。
【解决方案3】:

尽管@jedwards 解决方案很棒,(以及简洁/pythonic);另一种可能的解决方案:

def prime_multiples(l,t ):  
    for i in l:  # Iterate over our list.
        for j in t:  # Iterate over the tuple of prime factors.
            #  We check to see that we can divide without a remainder with our factor,
            #  then check to see if that factor exists in our tuple.
            if i%j == 0 and i/j in t:
                print "Prime factors: {} * {} = {}".format(j, i/j, i)
                break  # We could go not break to print out more options.

示例输出:

l = [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49]
t = ( 2, 3, 5, 7 )
prime_multiples(l, t)
>>> Prime factors: 2 * 2 = 4
... Prime factors: 2 * 3 = 6
... Prime factors: 3 * 3 = 9
... Prime factors: 2 * 5 = 10
... Prime factors: 2 * 7 = 14
... Prime factors: 3 * 5 = 15
... Prime factors: 3 * 7 = 21
... Prime factors: 5 * 5 = 25
... Prime factors: 5 * 7 = 35
... Prime factors: 7 * 7 = 49

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2020-05-29
    • 1970-01-01
    • 2020-07-07
    相关资源
    最近更新 更多