1

刚接触 Python 5 天,通过 Code Academy 学习。我对任何其他语言一无所知(对 Ruby 知之甚少!)。

我对这段代码做错了什么?


问:写一个函数,by_three调用第二个函数,cube如果一个数能被 3 整除,"False"否则。然后,您应该返回从中获得的结果cube。至于cube,该函数应该返回从传递的数字的立方体by_three。(乘以一个数字与将其提高到三次方相同)。

因此,例如,by_three应该取 9,确定它可以被 3 整除,然后将其传递给立方体,它返回 729(9**3 的结果)。但是,如果by_three得到 4,它应该返回False并保留它。

最后,by_three在三个单独的线路上分别拨打 11、12 和 13。

回答:

def by_three(n):
    orig_num = n
    if (isinstance(orig_num, int) and orig_num%3 == 0 ):
        cube(orig_num)
    else:
        print "False"

def cube(orig_num):
    cube = orig_num**3
    print cube
    return

by_three(11)
by_three(12)
by_three(13)

当我运行上面的代码时,这就是我得到的。为什么这些值会以这种方式出现?

False
1728
False
==> None
False
False
1728
Oops, try again.
4

3 回答 3

1

我不能说为什么你会看到奇怪的结果。当我将您的代码复制到解释器中时,我看到:

>>> def by_three(n):
...     orig_num = n
...     if (isinstance(orig_num, int) and orig_num%3 == 0 ):
...         cube(orig_num)
...     else:
...         print "False"
... 
>>> def cube(orig_num):
...     cube = orig_num**3
...     print cube
...     return
... 
>>> by_three(11)
False
>>> by_three(12)
1728
>>> by_three(13)
False

不过,我认为这个问题比你做的要简单得多。很难说,因为这个问题写得不好,但这将是我的答案:

def by_three(n): return False if n % 3 else cube(n)

def cube(n): return n**3

by_three(11)
by_three(12)
by_three(13)

这就是它在解释器中的样子:

>>> def by_three(n): return False if n % 3 else cube(n)
... 
>>> def cube(n): return n**3
... 
>>> by_three(11)
False
>>> by_three(12)
1728
>>> by_three(13)
False
于 2012-11-23T05:53:07.417 回答
1

首先,您需要更改cube函数以实际返回cube. 您甚至可以cube通过仅返回cube而不存储临时结果来简化您的方法:-

def cube(orig_num):
    return orig_num**3   # Just return the cube

然后在你的by_three函数中,而不是打印“False”,你应该返回它。另外,返回value函数返回cube:-

def by_three(n):
    if (isinstance(n, int) and n % 3 == 0):
        return cube(n)  # Added return here
    else:
        return False  #Changed print to return.

您还可以将此方法简化为仅single行返回语句。如果你在你的传递一个值,你应该使用try-except块而不是检查实例: -isinstancefunction

def by_three(n):
    try:
        return cube(n) if n % 3 == 0 else False
    except TypeError, e:
        return False

然后,当您调用该方法时,打印获得的结果:-

print by_three(11)
print by_three(12)
print by_three(13)
于 2012-11-23T05:54:17.777 回答
0

在您的cube方法中,您实际上并没有返回任何东西。与返回块中最后一条语句的 Ruby 不同,您必须明确声明要返回的内容。也没有必要创建价值的防御性副本。此外,您不能重用 name cube,否则会破坏您的方法定义。

def cube(orig_num):
    return orig_num ** 3

接下来,您必须在调用者方法中返回值。我将把它作为练习留给你——从这里弄清楚应该不会太棘手。

第三,如果数字是整数还是浮点数,您(有点)不必担心。虽然浮点数存在不精确性,但这些值不应完全被 3 整除。

于 2012-11-23T05:57:40.573 回答