我在试着理解我目前的解决方案有什么问题。 的问题如下:使用Python 2.7.6"代码调试:'取0-9之间的整数列表,返回最大可被3整除的数字'
你有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呢? 该列表中始终至少包含一个数字。