例如‘aabbcc’,去重后為‘abc’
同樣是兩種方法,一種是循環迭代
def shrink_consecutive_nb(list_of_nb): output = f'{list_of_nb[0]}' for i in range(1, len(list_of_nb)): if list_of_nb[i] != list_of_nb[i - 1]: output += list_of_nb[i] return output
另一種是遞歸
def remove_repeated_value(string): if not string: return '' if len(string) == 1: return string L = remove_repeated_value(string[1:]) if string[0] in L: return L else: return string[0] + L
