【问题标题】:Implementing the collatz function using Python使用 Python 实现 collat​​z 函数
【发布时间】:2017-08-31 21:21:46
【问题描述】:

我目前无法完成“自动化无聊的东西”中的这个挑战:

我的代码是:

def collatz(number):
    global seqNum
    if (seqNum % 2 == 0):
        return seqNum // 2
    elif (seqNum % 2 == 1):
        return 3 * seqNum + 1


print('What number would you like to use?')
seqNum = input()
number = int(seqNum)
i = number

while i > 1:
    collatz(seqNum)
    print(number)

我收到了这个错误:

"Traceback (most recent call last):
  File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 15, in <module>
    collatz(seqNum)
  File "C:/Users/Administrative/AppData/Local/Programs/Python/Python36-32/collatzSeq.py", line 3, in collatz
    if (seqNum % 2 == 0):
TypeError: not all arguments converted during string formatting"

我知道我在编写代码的方式上做错了,但我不明白它到底是什么。非常感谢任何和所有帮助!

我也在使用 python 3。

【问题讨论】:

  • 您没有使用您的论点...我认为您想使用数字而不是 seqNum。这不起作用,因为输入返回一个字符串,它不是数字。此外,您实际上并不需要 elif,您可以使用 else,因为唯一可能的值是 1。
  • ^ 并摆脱那里的全局声明,这没有帮助

标签: python string python-3.x function collatz


【解决方案1】:
  1. 您正在对字符串进行算术运算,而不是整数。

  2. 不需要global 变量。将参数传递给函数,并让它相应地返回一个值。


def collatz(number):
    if (number % 2 == 0):
        return number // 2

    elif (number % 2 == 1):
        return 3 * number + 1

print('What number would you like to use?')

i = int(input())
while i > 1:     
    i = collatz(i)
    print(i)

【讨论】:

  • 我还有一个关于这个的问题:所以你写了“while True”,因为我正在调用 collat​​z() 函数并且该函数没有可能的 False 值?我也可以在while之后使用任何表达式吗?所以如果我愿意,我可以写 while False, 1
  • 我用 12 运行它并收到完整的序列?我很困惑
【解决方案2】:

这里有几个问题,但导致您的异常的一个是您在函数中使用了seqNum,这是input() 返回的内容。 input() 返回一个字符串(至少在 Python 3 上)。而strings the % 是“格式化运算符”,它也解释了异常消息,其中谈到了“字符串格式化”。

你可以这样写(使用number而不是seqNum):

def collatz(number):  
    # you pass the number to the function and you return, so no need for global        
    if number % 2 == 0:       # python doesn't need parenthesis for "if"s
        return number // 2
    else:                     # it can only be even OR odd so no need to calculate the modulo again
        return 3 * number + 1

# You can put the question as argument for "input" instead of printing it
seqNum = input('What number would you like to use?')  
number = int(seqNum)

while number > 1 :
    number = collatz(number)   # assign the result of the function to "number"
    print(number)

【讨论】:

    【解决方案3】:

    seqNum 是一个字符串。

    >>> "3" % 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: not all arguments converted during string formatting
    >>>
    

    【讨论】:

    • ...解决方案是使用number。
    • 我认为这不能作为问题的真正答案。
    • @cᴏʟᴅsᴘᴇᴇᴅ 好吧,从纯粹的技术角度来说,这确实回答了这个问题。这将解决 OP 发布的错误。然而,有人可以说这是一个不太理想的答案。
    【解决方案4】:
    # This could be the simplest solution
    def collatz(number):
        while True:
            if number <= 1:
                break
            elif number % 2 == 0:
                number = number // 2
                print(number)
            elif number % 2 == 1:
                number = 3 * number + 1
                print (number)
    try:
        print('Enter a number \n')
        number = int(input())
        collatz(number)
    except ValueError:
        print('Invalid value, Enter a number.')
    

    【讨论】:

      【解决方案5】:

      我认为对于像我这样的初学者来说这是最容易理解的:

      def collatz(number):
      while number != 1:
          if number % 2 == 0:
              number = number // 2
              print(number)
          else:
              number = 3 * number + 1
              print(number)
      
      try:
          collatz(number=int(input("Enter the number: \n")))
      except ValueError:
          print('Error: Invalid argument \nPlease enter a number')
      

      【讨论】:

        【解决方案6】:

        看来您应该将i 传递给您的函数,而不是seqNum。

        并且在您的函数中删除所有对seqNum 的引用并改用number。

        【讨论】:

          【解决方案7】:

          您好,我是编码新手,也在看这个练习。如果这里有帮助的话,我使用 1 x 函数 + 2 x while 循环所采用的方法。我还注意到程序没有很好地处理零值作为输入:

          # This program runs the Collatz sequence - Automate book, Chapter 3 practice project
          # It includes the 'Input Validaton' additional exercise
          # It also inlcudes a further test for zero value input as this makes collatz non-terminating
          
          def collatz(number):
              #test even
              if number % 2 == 0:
                  return number // 2
              #or implicit it is odd
              else:
                  return 3 * number + 1
          
          # Get the user input and validate - loop continues until non-zero integer entered
          while True:
              try:
                  print('Enter a non-zero number')
                  number = int(input())
                  if number == 0:
                      continue
                  else:
                      break
              except ValueError:
                  print('Error: You must enter and integer')
          
          # Iterate over the input number until it == 1              
          while number != 1:
              # return value assigned to global var
              number = collatz(number) 
              # output the result of collatz to screen
              print(number)
          

          【讨论】:

            猜你喜欢
            • 2012-11-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-17
            • 1970-01-01
            • 2017-03-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多