所以我试着编写一个程序,使用3的幂来产生整数的分解:1,3,3,27和81.在每次计算中只能使用一次数。
示例:
1 = 1
2 = 3 - 1
3 = 3
4 = 3 + 1
5 = 9 - 3 - 1
我该如何解决这个问题,同时也考虑到负数?它适用于大多数数字,但不适用于5,例如,它包含3次两次。
add = True;
ans = ""
nums = [1, 3, 9, 27, 81] #list of powers of 3
check = result
while(check): #loop through the value if it exsists
distance = abs(check - 1)
close = 1
for i in nums:
temp_distance = abs(check-i)
if (distance and (distance >= temp_distance)): #check if the distance is greater than the temp distance and not a perfect match
distance = temp_distance
close = i
else: #if its a perfect match then no calculation needed
break
if close > check:
add = not add
check = distance
if check:
ans += str(close)
if add:
ans += ' + '
else:
ans += ' - '
else:
ans += str(close)
答案 0 :(得分:0)
一种方法是将数字转换为三元基础系统。例如:
32(10 = 1012(3 = 27 + 3 + 2*1
此处(b
表示该数字位于基础b
中。根据你的算法,数字应该只使用一次,所以你必须这样工作:
1)创建一个将整数转换为三个幂列表的函数。
def powerthree(input):
if input<0: return powerthree(abs(input))
powthree = []
while input > 0:
powerthree.append(input % 3)
input /= 3
powethree.reverse() #Reverse to show factors decreasing to 1
return powethree
2)在列表的开头添加一个虚拟0
:
pw3 = [0] + powerthree(input)
3)从右向左扫描列表。如果元素为2
,则设置为-1
并将1
添加到列表的上一个元素,直到位置为止。
def accomodate(pw3list):
for i in xrange(-1, -len(pw3list), -1): #Run from right to left, rememember that Python allows negative indices!
if pw3list[i] == 2:
pw3list[i] = -1
pw3list[i-1]+=1
return pw3list
4)容纳列表中的值表示您是应该添加,减去还是跳过3的幂。写下结果:
def printresult(orignumber, pw3list):
print "%d = " % orignumber,
for i in xrange(len(pw3list)):
pow3 = 3 ** (len(pw3list) - i - 1)
print "%d" % (pow3 * pw3list[i])
应使用32
32 = 27 + 9 - 3 - 1
希望我能帮助你!正如我通常所说的那样,英语不是我的母语,所以在我的帖子中可以犯错误。我们将随时欢迎更正。