Python,codewars,Range Extraction

# https://www.codewars.com/kata/51ba717bb08c1cd60f00002f/solutions/python?filter=all&sort=best_practice&invalids=false
# Range Extraction

def solution(args):
    result = [str(args[0])]
    count = 0
    # range()函数返回的是一个range对象,range对象是一个可迭代对象,可以通过for循环进行遍历
    for i in range(1,len(args)):
        strNum = str(args[i])
        if(args[i-1] + 1 == args[i]):
            count += 1
        else:
            count = 0
        if(count==0):
            result.append(',')
            result.append(strNum)
        elif(count==1):
            result.append(','+strNum)
        elif(count==2):
            # result[-1]表示列表result的最后一个元素
            result[-1] = '-'
            result.append(strNum)
        elif(count>2):
            result[-1] = strNum
    return ''.join(result)

# best practices
def solutionOfOthers(args):
    beg = end = args[0]
    ans = []
    for num in args[1:]+[""]:# [""]是为了处理最后一个元素
        if num != end + 1:
            if beg == end:
                ans.append(str(beg))
            elif end == beg + 1:
                ans.append([str(beg),str(end)])
            else:
                ans.append(str(beg)+'-'+str(end))
                beg = num
        end = num
    return ','.join(ans)

posted @ 2025-03-07 20:34  Kazuma_124  阅读(5)  评论(0)    收藏  举报