def complete_recursive(input_str): lenth = len(input_str) if lenth == 1: return input_str elif lenth < 2: raise ValueError result = [] for out_str in complete_recursive(input_str[0:-1]): for i in range(len(out_str)+1): element = out_str[0:i] + input_str[-1] + out_str[i:] if i==0 or not element[i-1] == input_str[-1]: result.append(element) return result def complete_stack(input_str): str_stack = [] result = [] for c in input_str: str_stack.append(c) result.append(str_stack.pop()) while len(str_stack) >0: c = str_stack.pop() tmp_result = [] for element in result: for i in range(len(element)+1): tmp_str = element[0:i] + c + element[i:] if i==0 or not c == tmp_str[i-1]: tmp_result.append(tmp_str) result = tmp_result return result def duplicate_removal(input_list): result = [] tem_input_stack = [e for e in input_list] while len(tem_input_stack) > 0: element = tem_input_stack.pop(0) result.append(element) i=0 while i < len(tem_input_stack): if tem_input_stack[i] == element: tem_input_stack.pop(i) else: i += 1 return result if __name__ == "__main__": result1 = duplicate_removal(complete_recursive("1234567")) result2 = duplicate_removal(complete_stack("1234567")) result1.sort() result2.sort() print(result1) # print(result2) print(result2 == result1)
当字符串多于7个的时候计算时间会很长(组合的可能性为7的阶乘)
Powered by Froala Editor
发表评论 (对文章评论)