python - 哥德巴赫 Python 输出

标签 python output

我为哥德巴赫猜想编写了一个Python代码。 问题是我的输出看起来像这样

Enter the lower limit: 8
Enter the Upper limit: 10
8 = 3 + 5
10 = 3 + 7
10 = 5 + 5

我希望我的输出看起来像这样

8 = 3 + 5
10 = 3 + 7 = 5 + 5

有什么办法可以将其格式化吗?

我只发布 for 循环:

for n in range (lo_limit, up_limit + 1): #lo_limit and up_limit is what you input
  if (n % 2 == 0):
    for a in range (1, n + 1): 
      if is_prime(a): #is_prime represent numbers that are prime
        for b in range(1, n + 1):
          if is_prime(b):
            if (a + b == n):
              if (a <= b):
                print(n, "=", a, "+", b)

主函数

最佳答案

通过一些简单的更改,您的函数可以得到简化并加快速度:

def goldbach(lo, hi):
    # 1. just step by 2 instead of checking for even numbers
    for n in range(lo, hi + 1, 2):
        # 2. keep a list of found matches instead of building up a string 
        matches = [str(n)] 
        # 3. for any 'a', you can just subtract to find 'b' instead of looping
        # 4. instead of testing for a <= b, just run the 'a' loop halfway
        for a in range(1, n // 2 + 1):
            if is_prime(a) and is_prime(n-a):
                matches.append('{} + {}'.format(a, n-a))
        # 5. join up the matches and print at the end
        print(' = '.join(matches))

为了更加简洁,整个内部 for 循环也可以表示为列表理解。

您可以通过预先生成范围内的素数列表,然后迭代这些素数并检查补集的成员资格,而不是重复进行素数测试,可以轻松地进一步优化这一点。

关于python - 哥德巴赫 Python 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32745748/

相关文章:

python - 在Python中复制值集的列表

python - 访问嵌套列表的元素

file - 对于三位数的指数,Fortran在输出中删除 'E'

html - 如何使用 Ant 在 JMeter 测试中附加结果 HTML 输出文件

c - 这段 C 代码的输出是如何产生的?

python - 将函数写入文件,没有得到

regression - 使用 TensorFlow 进行多项式回归过度拟合

python - 我的表单的 is_valid 方法返回 false

c - 如何使用 open() 和 printf() 写入文件?

Python删除方括号和它们之间的无关信息