我已经编写了以下代码来解决这个话题"将一个整数编号重新排列为最大的回文数"
示例:
输入数据为485,输出应为'不是回文数'
输入数据为445,输出应为454
输入数据为24266,输出应为62426(最大回文,而不是26462)
请看一下并帮我纠正这个
我遇到的问题: 输入112 - >它只返回2
谢谢!
def largest_palindrome(self, number):
a = list(str(number))
duplicate = [item for item, count in collections.Counter(a).items() if count > 1]
if (round(len(a)/2,0) != len(duplicate)):
print 'Not palindrome number'
else:
uniq = []
max_item = a[0]
for i in range (1, len (a)):
if a[i] > max_item:
max_item = a[i]
uniq=uniq.append(max_item)
return uniq
答案 0 :(得分:3)
import itertools
print "".join(max(x for x in itertools.permutations("100") if x == tuple(reversed(x))))
换句话说:找到所有排列,选择回文,找到最大的排列,并显示它。
答案 1 :(得分:2)
from collections import Counter
def largest_palindrome(num):
# suppose, num is 34347
c = Counter(str(num))
# lst is [('4', 2), ('3', 2), ('7', 1)]
lst = [(k, v) for k, v in c.items()]
# lst is [('7', 1), ('4', 2), ('3', 2)]
# we sort, because we want to process the largest digits first
# to get the largest palindrome
lst.sort(key=lambda elt: elt[0], reverse=True)
head = middle = ''
for k, v in lst:
if v % 2 == 1:
# digit, that number is odd, goes to middle, so '7' goes to middle
if middle:
# if some digit is already in middle, we can't place
# another digit there, e. g. for number '1123'
print('Not palindrome number')
return
middle = k
# if k is '4', v is 2 -> '44'
# if k is '7', v is 1 -> '7' * (1 // 2) -> '7' * (0) -> ''
head += k * (v // 2)
# head is '43', middle is '7'
return head + middle + head[::-1]
答案 2 :(得分:0)
我已经尝试了下面的代码并且它可以正常工作
#Ex1 - Return max proportional number
def return_arrange(self,number):
line = list(str(number))
if len(line)<3:
print "This number could not be a palindrome number."
return
lineA = []
lineB = []
i=0
while i<len(line):
for j in range(i+1,len(line)):
if int(line[i]) == int(line[j]):
lineA.append(line[i])
line.pop(j)
line.pop(i)
i=-1
break
if (i>-1):
lineB.append(line[i])
line.pop(i)
i=-1
if (len(lineB) > 1):
print "This number could not be a palindrome number."
return
i=i+1
lineC = sorted(lineA,reverse=True)+lineB+sorted(lineA)
return str("".join(lineC))