您的位置:首页 > 编程语言 > Python开发

Python实现Pat 1032. Sharing (25)

2017-12-06 21:56 676 查看

题目

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (<=10000) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Do not output leading zeros.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

解答

排序题,关键在于字符串的大小比较。比较两个字符串大小时如32和321,如果有相同前缀,则删除较长的字符串中的前缀,并比较剩下的数的大小,即32和321的比较结果应该是32和1的比较结果。

from functools import cmp_to_key
def cmpt(s1,s2):
len1=len(s1)
len2=len(s2)
maxl=max(len1,len2)
for i in range(maxl):
if s1[i%len1]!=s2[i%len2]:
return  int(s1[i%len1])-int(s2[i%len2])
else:
return 0
line0=input().split(' ')[1:]
line0.sort(key=cmp_to_key(cmpt))
num=''
for e in line0:
num+=e
count=0
#剔除无效的‘0’
for e in num:
if e=='0':
count+=1
else:
break
num=num[count:]
#特殊情况
if not num:
num='0'
print (num)


又错了一个小点。不管了

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: