[英]Print 4 letter combinations of a string without using lists or itertools
我們要編寫一個 function,它接受一個參數字符串,然后從字符串的可能組合中輸出每 4 個字母的排列。 因此,例如,即使它是一個 5 個字母的單詞,您也必須返回該字符串的所有 4 個字母組合。 它也只能迭代地解決,所以沒有遞歸。
目前我已經嘗試使用嵌套 for 循環,例如
for i in word:
for x in word:
for z in word:
for y in word:
print(y)
print(z)
print(x)
print(i)
然而,我遇到的問題是,首先,我不確定如何將這些輸出連接成一個字符串 output ,因為我不能使用列表或任何形式的集合/字典/元組等。其次,究竟如何我會避免重復的字符串嗎?
您可以只使用+
運算符將兩個字符串連接在一起:
a = 'str1'
b = 'str2'
c = a + b
print(c)
output:
'st1str2'
因此,您可以使用它來將 i、x、z 和 y 連接成一個字符串,並將其打印為 1 個“字”。
這個問題不是很清楚,所以我想對於word='abcd'
你必須打印單詞: 'abcd', 'aabc', aaab'
等等。
我假設一個字母可以在不同的字母組合中出現多次(字母“a”、“b”、“c”、“d”的排列)。
在這種情況下嘗試下面的代碼:
def permutation(word):
counter = 1
for i in word:
for x in word:
for z in word:
for y in word:
print(f"{counter} - {i + x + z + y}")
counter += 1
permutation("abcd")
output 包含 4 個字母的 256 個字符串,這些字母是 4 個字母的 4^4 排列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.