[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: handling lists in perl

On Wed 19 Dec 2018 at 16:53:44 (+0000), Andy Smith wrote:
> On Wed, Dec 19, 2018 at 09:23:59AM +0000, mick crane wrote:
> > just to be a bit clearer.
> > given a list A of *unique* numbers
> > and a list B of possible pairings find which pairs you can make from the
> > list A.
> > 6 can pair with 100 and 15 can pair with 100 but they cannot both be
> > in the list of possible pairings because there is only one 100.
> You don't have two lists though; you have a list and a hash. By
> using the correct Perl terminology it will become a lot clearer what
> you want to achieve.
> You have a LIST of numbers.
> You have a HASH that contains KEYS and VALUES.

I don't think the "pairs" form a hash/dictionary; I think they're just
ordered pairs of numbers, better expressed as a tuple. (Sorry to use
python jargon; I stopped using perl in the last millennium.) So we
have a list of tuples and a list of numbers.

> Do you want to match the KEYS from the HASH with the numbers in the
> LIST, or the VALUES from the HASH with the numbers from the LIST?
> And do you want to return what was matched or the KEYS of what was
> matched?
> Since the HASH can have multiple instances of the same VALUE but
> with different KEYS, if you are matching the VALUE against something
> what do you want to do when there is more than one instance of the
> same VALUE?
> You saying, "a list B of possible pairings find which pairs you can
> make from the list A" doesn't help when B is actually a hash,
> because hashes have keys and values, so we don't know if you mean to
> "make pairings" with the key or the value, nor is it entirely clear
> what "make a pairing" means. We can guess you mean "is equal to"
> once we know which thing you want it to be equal to, but it's still
> a guess. Why make us guess? Just say "check for equality" or
> something if that is what you mean. :)

I assume that for two numbers in the second list to be selected, both
have to match the two members of an individual tuple. As the tuples
are ordered, I would assume that they are to be tested in the order

As dictionary lookups are fast, I would convert the second list into
a dictionary: the number as the dictionary key and the number of
occurrences as the dictionary value. (Although the problem states
that the second list shouldn't have duplicates, this method checks
whether this is indeed the case.)

Scanning the list of tuples in order, it's now quick to see if both
members are in the dictionary and, if so, decrement their values or
delete. What survives of the dictionary keys is the unmatched numbers;
the matched pairs can be added to a list, individually or as tuples.


Reply to: