Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 11 Online
OpenStudy (anonymous):

in problem set 6, part 4, does anyone know a slick and easy way to get all the subsets for the elements in your hand?

OpenStudy (owlfred):

Hoot! You just asked your first question! Hang tight while I find people to answer it for you. You can thank people who give you good answers by clicking the 'Good Answer' button on the right!

OpenStudy (anonymous):

Here's what I did. may not be slick and easy, but it works. I use two other functions: bubbleSort and dict_to_string (included at the bottom) def pick_best_word_faster(hand, rearrange_dict): """ Return the highest scoring word from points_dict that can be made with the given hand. Return '.' if no words can be made with the given hand. hand: dictionary: (string -> int) """ max_score = 0 best_word = '.' # dict_to_string is a function I created to # convert a dictionary of letters to a string my_hand = dict_to_string(hand) for i in range(1, len(my_hand) + 1): S = list(itertools.combinations(my_hand,i)) for item in S: ordered_string = string.join(bubbleSort(list(item)), '') if ordered_string in rearrange_dict: temp_word = rearrange_dict[ordered_string][0] if points_dict[temp_word] > max_score: max_score = points_dict[temp_word] best_word = temp_word return best_word def bubbleSort(L): """returns a sorted list when passed the list, L""" swapped = True while swapped: swapped = False #print L for i in range(len(L) - 1): if L[i] > L[i+1]: temp = L[i] L[i] = L[i+1] L[i+1] = temp swapped = True return L def dict_to_string(dictionary): """ Returns a string consisting of all letters in dictionary """ list_of_letters = () list_pointer = 0 for letter in dictionary: if dictionary[letter] != 1: for i in range(0, dictionary[letter]): list_of_letters += (letter,) list_pointer += 1 else: list_of_letters += (letter,) list_pointer += 1 return string.join(list_of_letters, '')

OpenStudy (anonymous):

Thanks! itertools.combinations is exactly what I was missing... :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!