【发布时间】: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