আমাদের দুটি লিস্ট দেওয়া আছে: phrases যাতে কিছু নির্বাচিত ফ্রেজ রয়েছে এবং sentences যাতে বেশ কিছু বাক্য রয়েছে যেগুলো phrases-এর ফ্রেজগুলো থাকতে পারে বা নাও থাকতে পারে। আমাদের বের করতে হবে যে phrases-এর বিভিন্ন ফ্রেজগুলো sentences-এ কতবার আসে এবং সেগুলোকে উপস্থিতির সংখ্যা অনুযায়ী সর্ট করতে হবে। আমরা সর্টেড phrases লিস্ট রিটার্ন করব।
উদাহরণস্বরূপ, ইনপুট phrases = ['strong', 'durable', 'efficient'], sentences = ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient'] হলে আউটপুট হবে ['efficient', 'durable', 'strong']।
'efficient' ফ্রেজটি বাক্য ০, ২, এবং ৩-এ আসে। এর সবচেয়ে বেশি উপস্থিতি আছে, তাই আউটপুটের শুরুতে থাকে। 'durable' এবং 'strong' ফ্রেজগুলো যথাক্রমে বাক্য ০ এবং ১, এবং ১-এ আসে। তাই এগুলো পরবর্তী পজিশনে থাকে।
সমাধানের ধাপসমূহ
cnt := একটি নতুন ম্যাপphrases-এর প্রতিটিfeatureএর জন্য:cnt[feature] := 0
sentences-এর প্রতিটিresponseএর জন্য:p := response-এর শব্দগুলোর একটি লিস্টs := p-এর একটি সেটs-এর প্রতিটিiএর জন্য:যদি
icnt-এ থাকে, তবে:cnt[i] := cnt[i] + 1
res := cnt-এর সবkএর জন্য(k, cnt[k])জোড়া ধারণকারী একটি নতুন লিস্টres-কে কাউন্টkঅনুযায়ী সর্ট করুনকাউন্ট ভ্যালু
kছাড়াresলিস্ট রিটার্ন করুন
উদাহরণ
নিচের ইমপ্লিমেন্টেশনটি দেখুন ভালোভাবে বুঝার জন্য:
def solve(phrases, sentences):
cnt = {}
for feature in phrases:
cnt[feature] = 0
for response in sentences:
p = response.split()
s = set(p)
for i in s:
if i in cnt:
cnt[i] += 1
res = [[k, cnt[k]] for k in cnt]
res.sort(key=lambda x: (-x[1], phrases.index(x[0])))
return [i[0] for i in res]
print(solve(['strong', 'durable', 'efficient'],
['the product is durable and efficient',
'strong and durable',
'it is efficient',
'like it because it is efficient'])) ইনপুট
['strong', 'durable', 'efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']
আউটপুট
['efficient', 'durable', 'strong']