def jumbled( word_list, n ): """ Create an anagram of n strings randomly chosen from word_list. The jumble is enough to create any one of the selected words, but duplicates between words are merged (see letterbag). Args: word_list: non-empty list of strings n: 1 <= n <= len(word_list), number of words to jumble together. Returns: A jumbled string with the property that any of the selected strings from word_list can be formed. The result should be the smallest jumble with this property (i.e., duplicates between words have been removed). """ selected = random.sample(word_list, n) bag = LetterBag("") for word in selected: bag.merge( LetterBag(word) ) letters = list(bag.as_string()) print("Letters: {}".format(letters)) random.shuffle(letters) result = "".join(letters) return result
def jumbled(word_list, n): """ Create an anagram of n strings randomly chosen from word_list. The jumble is enough to create any one of the selected words, but duplicates between words are merged (see letterbag). Args: word_list: non-empty list of strings n: 1 <= n <= len(word_list), number of words to jumble together. Returns: A jumbled string with the property that any of the selected strings from word_list can be formed. The result should be the smallest jumble with this property (i.e., duplicates between words have been removed). """ # Create the anagram selected = random.sample(word_list, n) bag = LetterBag("") for word in selected: bag.merge(LetterBag(word)) letters = list(bag.as_string()) print("Letters: {}".format(letters)) random.shuffle(letters) result = "".join(letters) return result
def test_advanced_merge(): """ Examples using more advanced cases from class. """ capital_bag = LetterBag("A") lc_bag = LetterBag("a") empty_bag1 = LetterBag("") empty_bag2 = LetterBag("") assert capital_bag.merge(lc_bag).as_string() == "Aa" assert empty_bag1.merge(empty_bag2).as_string() == ""
def test_merge_unchaged(): """ Calling merge on a bag with a bag whose characters are already contained in the calling bag should not change its contents """ bag_a = LetterBag("abcde") bag_b = LetterBag("ae") bag_a_str = bag_a.as_string() bag_a.merge(bag_b) assert bag_a.as_string() == bag_a_str
def test_simple_merge(): bag_abbc = LetterBag("abbc") bag_abccd = LetterBag("abccd") bag_abbc.merge(bag_abccd) assert bag_abbc.as_string() == "abbccd"
def test_self_merge(): bag_ab = LetterBag("ab") bag_ab2 = LetterBag("ab") bag_ab.merge(bag_ab2) assert bag_ab.as_string() == "ab"
def test_empty_merge(): bag_abcddef = LetterBag("abcddef") bag_empty = LetterBag("") bag_abcddef.merge(bag_empty) assert bag_abcddef.as_string() == "abcddef"