【问题标题】:Intro to Computation and Programming Using Python使用 Python 进行计算和编程简介
【发布时间】:2015-05-12 22:48:22
【问题描述】:

我正在尝试解决手指练习 3.1,但我无法弄清楚我在这里做错了什么。当我输入 '1' 作为整数时,它返回 0 和 0。

我是编程和 Stack Overflow 的新手,所以我不确定我是否正确执行此操作,但我想我会试一试。

这就是问题所在: 编写一个程序,要求用户输入一个整数并打印两个整数, root 和 pwr,这样 0

到目前为止,这是我的解决方案:

x = int(raw_input('Enter a positive integer: '))
root = 0
pwr = 0
while pwr < 6:
    pwr += 1
    while root**pwr < x:
        root += 1
if root**pwr == x:
    print "The root is " + str(root) + " and the power is " + str(pwr)
else:
    print "No such pair of integers exists."

如何修复我的代码以使其返回正确的整数? 我在这里做错了什么?我错过了什么逻辑?

【问题讨论】:

  • 当我复制并粘贴您写的代码并输入“1”时,我得到“根为 1,幂为 6”的返回,我想我会在这个特殊的地方重新编写情况下,电源不会一直到 6,但我没有收到您的错误。您是否完全按照您在此处发布的内容运行?但是,当我们谈到这个主题时,从技术上讲,零到零的幂确实等于一。
  • 这段代码有很多问题。与其从代码开始,不如弄清楚你将如何手工完成。然后将该算法翻译成代码。
  • 我认为您不能正确地说明问题。任何整数 x 都有 x**1=x(即:root=x, pwr=1),所以程序可以只做print x, 1。也许你的意思是 1
  • 谢谢你们的帮助。我对编程完全陌生,所以我确信我的代码有很多问题。哈哈。我希望随着时间的推移学习如何更有效地编程。

标签: python logic computation


【解决方案1】:

一个问题是,虽然您确实有结束循环的条件,但它们总是会一直达到最大允许条件。您可以使用break 或如图所示在函数中使用return 来解决这个问题。另外,不要使用计数器,而是使用xrange() 函数(Python 3 中的range())。

>>> def p(num):
...     for power in xrange(6):
...         for root in xrange(num/2+1):
...             if root**power==num:
...                 return root, power
...
>>> r, pwr = p(8)
>>> print 'The root is', r, 'and the power is', pwr
The root is 2 and the power is 3

【讨论】:

  • 谢谢。之前没见过xrange()函数,所以一定会看文档搜索一下。
【解决方案2】:

尽管对于 Python 来说不是很惯用,但您已经接近正确答案了。

第一个问题是你永远不会重置root,所以你只会执行一次内部循环。将root = 0 移到外循环应该可以解决它。

第二个错误是当你达到你寻求的条件时你永远不会中断循环。将测试移到循环内部将解决此问题。

让我们看看到目前为止我们做得如何:

x = int(raw_input('Enter a positive integer: '))
pwr = 0
while pwr < 6:
    root = 0
    pwr += 1
    while root**pwr < x:
        root += 1
        if root**pwr == x:
            print "The root is {} and the power is {}".fornat(
               root, pwr
            )
else:
    print "No such pair of integers exists."

这个输出:

Enter a positive integer: 16
The root is 16 and the power is 1
The root is 4 and the power is 2
The root is 2 and the power is 4
No such pair of integers exists.

由于这是一个学习练习,我会让你找出并修复你的代码的其他问题。

【讨论】:

  • 谢谢。这对我帮助很大。我没有考虑将'root = 0'放在while循环中。我还将处理我的整体代码。我是新手,希望随着时间的推移变得更好。再次感谢!
  • 你做得很好,Jen,继续练习这种代码 kata,你很快就会成为黑带。如果有一天你想成为一名专业人士,我建议阅读来自Uncle Bob 的“Clean Coder”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2020-11-22
  • 2010-09-18
  • 2016-02-27
相关资源
最近更新 更多