সমস্যা বিবরণ
একটি স্ট্রিং দেওয়া আছে। স্ট্রিং থেকে k সংখ্যক ক্যারেক্টার মুছে (অর্থাৎ len(str) - k দৈর্ঘ্যের সাবসিকোয়েন্স) বাকি সাবস্ট্রিংগুলো বের করতে হবে।
পদ্ধতি ১: লুপ এবং রিকার্শন (ব্যাকট্র্যাকিং)
রিকার্সিভ ফাংশন দিয়ে সব কোম্বিনেশন জেনারেট করুন।
res_list = []
def letterCombinations(s, t, start, end, index, k):
if index == k:
elem = ''.join(t[:k])
res_list.append(elem)
return
i = start
while i <= end and end - i + 1 >= k - index:
t[index] = s[i]
letterCombinations(s, t, i + 1, end, index + 1, k)
i += 1
stringA = 'Apple'
k = 1
temp = [0] * (len(stringA) - k)
letterCombinations(stringA, temp, 0, len(stringA) - 1, 0, len(stringA) - k)
print(set(res_list)) # {'pple', 'Aple', 'Appl', 'Appe'}
পদ্ধতি ২: itertools.combinations() ব্যবহার
itertools.combinations(stringA, len(stringA) - k) দিয়ে সরাসরি কোম্বিনেশন বের করুন।
from itertools import combinations
stringA = 'Apple'
k = 1
res = set([''.join(i) for i in combinations(stringA, len(stringA) - k)])
print(res) # {'Appl', 'Aple', 'Appe', 'pple'}