【问题标题】:code debugging: 'take a list of ints between 0-9, return largest number divisible by 3'代码调试:'获取 0-9 之间的整数列表,返回可被 3 整除的最大数'
【发布时间】:2017-02-15 14:50:30
【问题描述】:

我正在尝试了解我当前的解决方案有什么问题。 问题如下:

使用 python 2.7.6"

您有L,一个包含一些数字(0 到 9)的列表。编写一个函数answer(L),它找出可以由这些数字中的部分或全部组成且能被 3 整除的最大数。如果不可能产生这样的数字,则返回 0 作为答案。 L 将包含 1 到 9 位数字。同一个数字可能在列表中出现多次,但列表中的每个元素只能使用一次。

input: (int list) l = [3, 1, 4, 1]
output: (int) 4311
input (int list) l = [3 ,1 ,4 ,1 ,5, 9]
output: (int) = 94311

这是我解决问题的代码:

import itertools

def answer(l):
    '#remove the zeros to speed combinatorial analysis:'
    zero_count = l.count(0)
    for i in range(l.count(0)):
        l.pop(l.index(0))

   ' # to check if a number is divisible by three, check if the sum '
   ' # of the individual integers that make up the number is divisible '
   ' # by three. (e.g.  431:  4+3+1 = 8,  8 % 3 != 0,  thus 431 % 3 != 0)'
    b = len(l)
    while b > 0:
        combo = itertools.combinations(l, b)
        for thing in combo:

            '# if number is divisible by 3, reverse sort it and tack on zeros left behind' 

            if sum(thing) % 3 == 0:
                thing = sorted(thing, reverse = True)
                max_div_3 = ''
                for digit in thing:
                    max_div_3 += str(digit)
                max_div_3 += '0'* zero_count
                return int(max_div_3)
        b -= 1

    return int(0)

我已经在我自己的沙盒中多次测试了这个任务,它总是有效的。 然而,当我向我的导师提交它时,我最终总是失败 1 个案例.. 没有解释原因。我无法审问导师的测试,它们是盲目地反对代码。

是否有人知道我的代码无法返回可被 3 整除的最大整数,或者如果不存在,则返回 0 的情况? 列表中始终至少包含一个数字。

【问题讨论】:

    标签: python-2.7 list debugging combinations itertools


    【解决方案1】:

    原来问题出在 itertools.combinations(l, b) 的顺序上 并排序(事物,反向=真)。原始代码是查找 n%3 == 0 的第一个匹配项,但不一定是最大匹配项。在 itertools.combinations 之前执行排序允许 itertools 找到最大的 n%3 == 0。

    【讨论】:

    • 感谢上帝...我所有的测试用例都通过了,因为我也在 itertools 之后进行排序。学到了一些新东西。谢谢@MBS
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2011-04-29
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多