[本文出自天外歸雲的博客園]算法
第一題:給你一個字符串,打印出來先後沒有空格,單詞之間只有一個空格的字符串。app
第二題:公雞3元/只,母雞4元/只,小雞1元3只,給你money元一共多少種買法。函數
普通版解法以下:spa
def print_str(str, ret=[]): for i in range(len(str)): if i == 0: ret.append(str[i]) else: if str[i - 1] == " " and str[i] == " ": pass else: ret.append(str[i]) print("".join(ret).strip()) def calc(money, count=0): for i in range(1, money // 3 + 1): for j in range(1, (money - i * 3) // 4 + 1): count += 1 # print(f"公雞{i}只 母雞{j}只 小雞{(money-i*3-j*4)*3}只") print(f"共有{count}種買法") return count if __name__ == '__main__': print_str(" I love Netease ") calc(100)
Pythonic版解法以下,一個算法一行:code
print_str = lambda str: print("".join([str[i] if i == 0 else str[i] for i in range(len(str)) if not (str[i - 1] == " " and str[i] == " ")]).strip()) calc = lambda money, count=0: print(f"共有{len([(i,j,(money-i*3-j*4)*3) for i in range(1, money // 3 + 1) for j in range(1, (money - i * 3) // 4 + 1)])}種買法") if __name__ == '__main__': print_str(" I love Netease ") calc(100)
對於第一題,大師兄後來給我一個更簡單的解法:blog
print(" ".join(" I love Netease ".strip().split()))
果真思路的優先級是更高的,一個好的思路有時候比好的實現優先級應該更高才對。ip
再來一個不用內置函數解決的方法:字符串
str = " I love Netease " new_str = "" for i in range(len(str)): if len(new_str)==0: if str[i]==" ": pass else: new_str += str[i] else: if new_str[::-1][0] != " ": new_str += str[i] else: if str[i] != " ": new_str += str[i] if new_str[::-1][0] == " ": new_str = new_str[:-1] print(new_str)