一道按順序排列組合題的幾種解法
阿新 • • 發佈:2019-01-01
有一道面試題: 一個字串"Yes", 用程式碼實現,輸出其全部大小寫組合,
比如說字串"no"則輸出['no', 'No', 'nO', 'NO']
想到了如下的幾種解法:
方法一:藉助於itertools.combinations
# coding = utf -8 def handle_string(src=""): from itertools import combinations res = "" for char in src: res += char.upper() + char.lower() words = list(combinations(list(res), 3)) for i in range(len(src)): words = ["".join(item) for item in filter(lambda x:x[i].lower() == src[i].lower(), words)] return words if __name__ == "__main__": print(handle_string("Yes"))
方法二:藉助於random模組
# coding = utf -8 def handle_string(src=""): import random sl = src.lower() su = src.upper() sa = ["".join(list(x+y)) for (i, x) in enumerate(sl) for (j, y) in enumerate(su) if i == j] temp = [] lens = 2 ** len(src) while True: item = "".join(random.choice(i) for i in sa) if item not in temp: temp.append(item) if len(temp) == lens: break return temp if __name__ == "__main__": print(handle_string("Yes"))