【问题标题】:Python prime numbersPython素数
【发布时间】:2014-02-01 15:40:58
【问题描述】:

您好,我是编程和 python 方面的新手,我有一个无法完成的作业。我必须编写一个 Python 程序来计算和打印前 200 个素数。输出必须用标题格式化,并且素数必须打印在 5 个正确对齐的列中。到目前为止我已经使用了这个代码:

numprimes = raw_input('Prime Numbers  ')    
count = 0    
potentialprime = 2

def primetest(potentialprime):
    divisor = 2
    while divisor <= potentialprime:
        if potentialprime == 2:
            return True
        elif potentialprime % divisor == 0:
            return False
            break
        while potentialprime % divisor != 0:
            if potentialprime - divisor > 1:
                divisor += 1
            else:
                return True

while count < int(numprimes):
    if primetest(potentialprime) == True:
        print potentialprime
        count += 1
        potentialprime += 1
    else:
        potentialprime += 1

但我在单个列中得到结果。我怎样才能把它分成 5 行?

【问题讨论】:

  • 请粘贴您的实际代码。然后突出显示它并单击{} 按钮。内容在发布时出现乱码。

标签: python numbers


【解决方案1】:
col=0                  #add this line
while count < int(numprimes):
    if primetest(potentialprime) == True:
        print "%5d"%potentialprime, #and this line
        col += 1        #and this block
        if col==5:      #
            print "\n"  #
            col=0       #
        count += 1
        potentialprime += 1
    else:
        potentialprime += 1

【讨论】:

    【解决方案2】:

    为当前列的编号添加一个变量currentCol初始化为0并将print potentialprime行更改为以下5行:

    print str(potentialprime).ljust(5),
    currentCol += 1
    if currentCol==5:
        print ""
        currentCol=0
    

    注意对ljustprint 行末尾的, 的调用,以防止打印数字末尾出现换行符。在打印 5 列 (if currentCol==5) 后,您打印一个换行符并将 currentCol 重置为 0。

    请参阅http://ideone.com/WsLnDK 以了解具有预期输出的整个修改程序。

    【讨论】:

      【解决方案3】:
      while count < int(numprimes):
          if primetest(potentialprime) == True:
              print "%5d" % potentialprime, #and this line
              col += 1        #and this block
      
              if col == 5:      #
                  print "\n"    #
                  col = 0       #
      
              count += 1
              potentialprime += 1
          else:
              potentialprime += 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-22
        • 2014-03-08
        • 2015-01-08
        • 1970-01-01
        相关资源
        最近更新 更多