這是我的代碼:
import math
import random
def start_of_func():
characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
total = ""
look_for = input("search for a specific word: ")
count = 0
for x in characters:
for y in characters:
for z in characters:
count = 1
print(f"{x}{y}{z}")
total = total f"{x}{y}{z}, "
if look_for in total:
print(f"found it! This took {count} attempts.")
return
else:
# coult not find it
pass
start_of_func()
基本上我希望用戶能夠選擇一個自定義長度的單詞,然后讓函式通過它。但問題是,我只看到一個選項,即手動檢查單詞數量,然后檢查需要多少個 for 回圈。例如,此代碼僅適用于 3 個字母的單詞,因為只有 3 個 for 回圈。但是如果我想要一個 4 個字母的單詞怎么辦?
幫助表示贊賞
uj5u.com熱心網友回復:
您可以使用以下方法將多個回圈替換為唯一的回圈itertools.product:
from itertools import product
import string
def start_of_func():
characters = string.ascii_lowercase
total = ""
look_for = input("search for a specific word: ")
count = 0
for seq in product(characters, repeat=len(look_for)):
count = 1
print(''.join(seq))
total = total f"{''.join(seq)}, "
if look_for in total:
print(f"found it! This took {count} attempts.")
return
else:
# coult not find it
pass
start_of_func()
我還添加string.ascii_lowercase了讓你的字母更容易。
uj5u.com熱心網友回復:
你可以試試:
from itertools import permutations as pm
def start_of_func():
characters = [chr(i) for i in range(97, 97 26)]
look_for = input('search for a specific word: ')
count = 0
for word in pm(characters, len(look_for)):
count = 1
if look_for == ''.join(word):
print(f'found it! This took {count} attempts. ')
return
start_of_func()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364523.html
上一篇:檢測數字是否為階乘遞回
