def count_preceding(str_number): number = [int(x) for x in list(str_number)] all_preceding_options = 0 for i, curr in enumerate(number): if DEBUG: print("{0}Position: {1}".format(' '*i, i)) full_sequence = number[i:] rem_sequence = number[i+1:] n = len(rem_sequence) full_digits = Multiset(full_sequence) rem_digits = Multiset(rem_sequence) preceding_options = 0 for digit in sorted(rem_digits.distinct_elements()): if digit < curr: # If this digit had been used first, how many # possibilities would there have been? new_digits = full_digits.copy() new_digits[digit] = new_digits[digit] - 1 up = unique_permutations(n, new_digits) if DEBUG: print("{0}Using {1} instead results in {2} options".format(' '*i, digit, up)) preceding_options = preceding_options + up else: break all_preceding_options = all_preceding_options + preceding_options return all_preceding_options
def load_VOC(dataset_folder): annotation_files = os.listdir( os.path.join(dataset_folder, conf.VOC_ANNOTATIONS)) images = [] classes = Multiset() for annotation in annotation_files: img = parse_annotation(dataset_folder, annotation) classes = classes.combine([o['class'] for o in img['objects']]) images.append(img) return images, list(classes.distinct_elements())
def _match_commutative_operation(subject_operands, pattern, substitution, constraints, matcher): subjects = Multiset(subject_operands) # type: Multiset if not pattern.constant <= subjects: return subjects -= pattern.constant rest_expr = pattern.rest + pattern.syntactic needed_length = (pattern.sequence_variable_min_length + pattern.fixed_variable_length + len(rest_expr) + pattern.wildcard_min_length) if len(subjects) < needed_length: return fixed_vars = Multiset(pattern.fixed_variables) # type: Multiset[str] for name, count in pattern.fixed_variables.items(): if name in substitution: replacement = substitution[name] if issubclass(pattern.operation, AssociativeOperation) and isinstance( replacement, pattern.operation): needed_count = Multiset(substitution[name]) # type: Multiset else: if not isinstance(replacement, Expression): return needed_count = Multiset({replacement: 1}) if count > 1: needed_count *= count if not needed_count <= subjects: return subjects -= needed_count del fixed_vars[name] factories = [ _fixed_expr_factory(e, constraints, matcher) for e in rest_expr ] if not issubclass(pattern.operation, AssociativeOperation): for name, count in fixed_vars.items(): min_count, symbol_type = pattern.fixed_variable_infos[name] factory = _fixed_var_iter_factory(name, count, min_count, symbol_type, constraints) factories.append(factory) if pattern.wildcard_fixed is True: factory = _fixed_var_iter_factory(None, 1, pattern.wildcard_min_length, None, constraints) factories.append(factory) else: for name, count in fixed_vars.items(): min_count, symbol_type = pattern.fixed_variable_infos[name] if symbol_type is not None: factory = _fixed_var_iter_factory(name, count, min_count, symbol_type, constraints) factories.append(factory) expr_counter = Multiset(subjects) # type: Multiset for rem_expr, substitution in generator_chain((expr_counter, substitution), *factories): sequence_vars = _variables_with_counts(pattern.sequence_variables, pattern.sequence_variable_infos) if issubclass(pattern.operation, AssociativeOperation): sequence_vars += _variables_with_counts( fixed_vars, pattern.fixed_variable_infos) if pattern.wildcard_fixed is True: sequence_vars += (VariableWithCount( None, 1, pattern.wildcard_min_length), ) if pattern.wildcard_fixed is False: sequence_vars += (VariableWithCount(None, 1, pattern.wildcard_min_length), ) for sequence_subst in commutative_sequence_variable_partition_iter( Multiset(rem_expr), sequence_vars): if issubclass(pattern.operation, AssociativeOperation): for v in fixed_vars.distinct_elements(): if v not in sequence_subst: continue l = pattern.fixed_variable_infos[v].min_count value = cast(Multiset, sequence_subst[v]) if len(value) > l: normal = Multiset(list(value)[:l - 1]) wrapped = pattern.operation(*(value - normal)) normal.add(wrapped) sequence_subst[v] = normal if l > 1 else iter( normal).next() else: assert len( value ) == 1 and l == 1, u"Fixed variables with length != 1 are not supported." sequence_subst[v] = iter(value).next() try: result = substitution.union(sequence_subst) except ValueError: pass else: for i in _check_constraints(result, constraints): yield i
def _execute_action(self, action_type, *args): # A private method that actually executes a chosen action. player = self.current_player if action_type == ActionType.TAKE_CAMELS: num_camels = self.play_area[CardType.CAMEL] if not num_camels: raise IllegalPlayError("There are no camels to take.") self.play_area[CardType.CAMEL] = 0 player.hand[CardType.CAMEL] += num_camels elif action_type == ActionType.TAKE_SINGLE: if player.cards_in_hand >= self.MAX_HANDSIZE: raise IllegalPlayError( "You already have {} cards in your hand.".format( self.MAX_HANDSIZE)) card_type_to_take = args[0] if card_type_to_take in self.play_area: self.play_area[card_type_to_take] -= 1 player.hand[card_type_to_take] += 1 else: raise IllegalPlayError( "There is no {} to take.".format(card_type_to_take)) elif action_type == ActionType.TAKE_MANY: card_types_to_take, card_types_to_give = Multiset( args[0]), Multiset(args[1]) if len(card_types_to_take) != len(card_types_to_give): raise ValueError if len(card_types_to_take) <= 1: raise IllegalPlayError( "You must exchange at least two cards from your hand and/or herd." ) # Cannot take camels this way. if CardType.CAMEL in card_types_to_take: raise IllegalPlayError("You cannot take camels this way.") # The same type of good cannot be both taken and surrendered. if card_types_to_take.distinct_elements() < card_types_to_give: raise IllegalPlayError( "You cannot surrender and take the same type of goods.") # The exchange must be legal. if card_types_to_take > self.play_area: raise IllegalPlayError( "Some of the cards you want to take are not in the market." ) if card_types_to_give > player.hand: raise IllegalPlayError( "Some of the cards you want to surrender are not in your hand and/or herd." ) # Exchange the cards. self.play_area -= card_types_to_take self.play_area += card_types_to_give player.hand -= card_types_to_give player.hand += card_types_to_take elif action_type == ActionType.SELL: card_type_to_sell, quantity_to_sell = args[0], args[1] if card_type_to_sell == CardType.CAMEL: raise IllegalPlayError("You cannot sell camels.") if quantity_to_sell == 0: raise IllegalPlayError("You cannot sell zero cards.") num_card = player.hand[card_type_to_sell] if num_card < quantity_to_sell: raise IllegalPlayError( "You cannot sell {} {} cards; you only have {}.".format( quantity_to_sell, card_type_to_sell, num_card)) if card_type_to_sell in self.PRECIOUS_GOODS and quantity_to_sell == 1: raise IllegalPlayError( "You cannot sell a single {}.".format(card_type_to_sell)) # Execute the sale in three parts. # 1) Remove cards from hand. player.hand[card_type_to_sell] -= quantity_to_sell # 2) Award goods tokens. for _ in range(quantity_to_sell): try: player.tokens.append(self.tokens[card_type_to_sell].pop()) except IndexError: # Sometimes the goods tokens are all gone; the seller simply doesn't get one. pass # 3) Award bonus token, if applicable. bonus_quantity = min(quantity_to_sell, 5) if bonus_quantity in self.bonuses: try: player.tokens.append(self.bonuses[bonus_quantity].pop()) except IndexError: # The rulebook doesn't account for the scenario where all the bonus tokens are gone, but by # extension with the above rule we can presume that the seller simply doesn't get one. pass else: raise ValueError("You have chosen an unrecognized action.")