[Tutor] A dictionary question

dn PyTutor at DancesWithMice.info
Sat Nov 13 00:45:26 EST 2021


On 13/11/2021 18.04, Phil wrote:
> Thank you for taking the time to look at this.
> 
> I'd like to find the number of pairs in the rows list of sets. The pair
> sets are {7, 3} and {4, 6} because they appear twice each. I'd also like
> to have count_dict dictionary show the two rows where the sets were
> found. What I have is this:
> 
> {'row': 5, 'count': 2, 'set': {4, 6}}
> 
> Which shows the last row, the count and the set found. I'd like the
> dictionary to also show where the other set {4, 6} was found which is
> row 1.
...

> for i in range(len(set_list)):
>     count = 0
>     for j in range(6):
>         if set_list[i].issubset(rows[j]):
>             found_set = set_list[i]
>             count += 1
>             count_dict['row'] = j 
>             count_dict['count'] = count
>             count_dict['set'] = found_set
> 
>     if count == 2:
>         print(set_list[i], ' is in row ',count, ' times')
>         print(count_dict)


What a ghastly exercise. Is it homework?

Note that "count_dict['row'] = j" only allows for one set-location to be
noted. Accordingly, change the value of the dictionary to be a list.
Sometimes the list will only be one item long - which seems like a
waste. However, when the counter goes to 2 (or more), then the list will
contain multiple items.

Declare the list at the same time as the count is reset.

Append the set-location to the list whenever a 'hit' is noted.

The last print() will then look something like:

{'row': [1, 5], 'count': 2, 'set': {4, 6}}


Once you've got that working (and not before - "make it work before you
make it better!", you'll realise that the counter is unnecessary because
the length of the list yields the same information!
-- 
Regards,
=dn


More information about the Tutor mailing list