جواب «Same Bag, Different Meaning» چالش 5 از جلسهی 33
سؤال
نشان بده کیسهی کلمات ترتیب را گم میکند. تابع same_bag(a, b, vocab) بنویس که True برگرداند اگر دو جمله کیسهی یکسان داشته باشند. برنامه سه جفت را امتحان میکند؛ خروجی: True، False، True. (جفت سوم با علامت و حروف بزرگ فرق دارد ولی کیسهاش یکی است.)
راهنما
return bag(a, vocab) == bag(b, vocab).
یک جواب درست
def tokens(text):
clean = "".join(ch for ch in text.lower() if ch.isalpha() or ch == " ")
return clean.split()
def bag(sentence, vocab):
counts = [0] * len(vocab)
for word in tokens(sentence):
if word in vocab:
counts[vocab.index(word)] += 1
return counts
vocab = ['bit', 'cat', 'dog', 'likes', 'the']
def same_bag(a, b, vocab):
return bag(a, vocab) == bag(b, vocab)
print(same_bag("the dog bit the cat", "the cat bit the dog", vocab))
print(same_bag("the dog bit the cat", "the dog likes the cat", vocab))
print(same_bag("The Dog likes the cat!", "the cat likes the dog...", vocab))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن