Python练习题答案: 处罚超速【难度:3级】--景越Python编程实例训练营,1000道上机题等你来挑战

处罚超速【难度:3级】:

答案1:

# return str of the smallest value of the combined numbers in a_list
# the length of a_list can vary betweem 2 and 20  
def penalty(a_list):
    return ''.join(sorted(a_list, cmp=(lambda a, b: cmp(a+b, b+a))))

答案2:

def penalty(lst):
    lst, maxLen = list(map(str, lst)), max(map(len, lst))
    return ''.join(sorted(lst, key=lambda s: s.ljust(maxLen, s[-1])))

答案3:

# return str of the smallest value of the combined numbers in a_list
def penalty(a_list):
  return ''.join(sorted(a_list, key = lambda n: n + n[:1]))

答案4:

penalty=lambda a:''.join(sorted(a,key=lambda n:2*n))

答案5:

from functools import cmp_to_key

def penalty(a_list):
    return ''.join(sorted(a_list, key = cmp_to_key(sorter)))
    
def sorter(a, b):
    return -1 if a + b < b + a else 1

答案6:

# return str of the smallest value of the combined numbers in a_list
# the length of a_list can vary betweem 2 and 20  
def penalty(l):
    return "".join(sorted(l, key=lambda k: (k*2, -len(k))))

答案7:

# return str of the smallest value of the combined numbers in a_list
# the length of a_list can vary betweem 2 and 20  
def penalty(i):
    a = sorted(i, key=lambda k:(k*1000, -len(k)))
    return "".join(a)

答案8:

# return str of the smallest value of the combined numbers in a_list
# the length of a_list can vary betweem 2 and 20     

def penalty(a_list):
    return ''.join(sorted(a_list, cmp=lambda x,y: int(x+y) - int(y+x) ))

答案9:

def penalty(a):
    m = len(max(a, key=len))
    return "".join(x[:len(x)//m] for x in sorted(x * m for x in a))

答案10:

from functools import cmp_to_key


def cmp (a, b):
# should be a > b if a[0] > b[0]
# if a[0] == b[0], should be a > b if a[1] 
    a = list(a)
    b = list(b)
    if a == b:
        return 0
    if int(a[0]) < int(b[0]):
        return -1
    elif int(a[0]) > int(b[0]):
        return 1
    else:  #a[0] == b[0]
        if len(a) > 1 and len(b) > 1:
            return cmp(a[1:], b[1:])
        elif len(a) > 1 and len(b) == 1:
            return (-1 if int(a[1]) < int(b[0]) else 1)
        elif len(a) == 1 and len(b) > 1:
            return (-1 if int(a[0]) < int(b[1]) else 1)
        

def penalty(a_list):
    print(a_list) 
    return ''.join(sorted(a_list,key = cmp_to_key(cmp)))



Python基础训练营景越Python基础训练营QQ群

在这里插入图片描述
欢迎各位同学加群讨论,一起学习,共同成长!

你可能感兴趣的:(Python编程习题答案)