My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried >because each month a list with the weights of members is published and each month he is >the last on the list which means he is the heaviest.
I am the one who establishes the list so I told him: "Don't worry any more, I will >modify the order of the list". It was decided to attribute a "weight" to numbers. The >weight of a number will be from now on the sum of its digits.
For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will >come before 99.
Given a string with the weights of FFC members in normal order can you give this string >ordered by "weights" of these numbers?
Example:
"56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes:"100 180 90 56 65 74 68 86 99"
When two numbers have the same "weight", let us class them as if they were strings >>。>(alphabetical ordering) and not numbers:180 is before 90 since, having the same "weight" (9), it comes before as a string.
All numbers in the list are positive numbers and the list can be empty.Notes
it may happen that the input string have leading, trailing whitespaces and more than a >unique whitespace between two consecutive numbers
For C: The result is freed.
題目理解:設計一函式將字串strng內數字,依"權重"來排序,其定義一個數字的權重為該數的所有位數數字相加,例:
1810 >> 1+8+1+0 = 10
依權重將數字由小排到大,若遇到權重相同時,將數字以字符串形式做排序比較。可以理解為當數字以字符串形式去做sorted時會獲得的順序,例:
print(sorted([180,90])) #返還[90, 180]
print(sorted(["180","90"])) #返還['180', '90']
故需遵從以上兩點,將strng重新排序後以字串形式輸出。
示例如下:
def order_weight(strng):
"將strng內數字依權重規則重新排列後輸出成字串"
#將字串內數字切割入列表arr存儲
arr = strng.split(" ")
lst = []
#將arr內數字依(權重weight,字串num)形式重新存成列表lst
for nb in arr:
lst.append((sum([int(i) for i in nb]),nb))
reslut = ""
#sorted()時會先從每個元組內的第一個元素做排序,故會先依int型態的權重做排序
#若遇相同結果時,sorted()會從該元組的第二元素依其string型態的數字本身做排序
sort_lst = sorted(lst)
#故此時sort_lst中的num順序以符合題目要求
for weight,num in sort_lst:
reslut += num
#如果當前遞迴並非最後一組元組,皆需加上" "
if (weight,num) != sort_lst[-1]:
reslut += " "
return reslut