[Tutor] A dictionary question

Phil phillor9 at gmail.com
Fri Nov 19 00:00:53 EST 2021


> The collections.Counter behaves like a dictionary.  Same methods
> should work.  So, try something like these basic loops that take
> advantage of the items() method.
>
>    c = Counter({(4, 6): 2, (3, 4): 1, (3, 6): 1})
>    
>    # -- loop through all of the key, value items in the dict-like object
>    for k, v in c.items():
>        print( k, v)
>
>    # -- same but only print where the counter for that entry is 2
>    for k, v in c.items():
>        if v == 2:
>            print( k, v)

Thank you Martin that solved that problem, however, it hasn't help me 
solve the original problem. I've spent a week or more on this and I 
don't seem to be getting anywhere. I'm now wondering if I really need to 
use a dictionary and if I'm really attacking this problem correctly.

The problem is, given a list of sets find a pair of numbers that occur 
in the same row and in no other set in that row.

row = [{7,3},{5},{4,6,8},{7,8},{1},{9,3},{7,9},{4,6,3},{2}]

The pair in this set is {4, 6}. This is an easy one to solve because 
neither the 4 nor the 6 is in any other set. My clumsy code gave me the 
correct answer but it fails if the 4 or the 6 is repeated in another row 
set.

There is no solution for the follow row because there is no unique pair:

row = [{5},{6},{3},{4,7,5},{1,2,4,5},{1,7,5},{1,2,4,7,9},{8},{1,2,4,7,9}]

I just had a bright idea while I'm typing this and the following code 
almost offer a complete solution:

row = [{7,3},{5},{4,6,8},{7,8},{1},{9,3},{7,9},{4,6,3},{2}]

number_list = []
row_list = []

for r in range(9):
     for i in range(1, 10):
         if i in row[r] and len(row[r]) > 2:
             number_list.append(i)
             row_list.append(r)

for i in range(len(number_list)):
     print(number_list[i], end=' ')

print()

for i in range(len(row_list)):
     print(row_list[i], end=' ')

At this point I have:

4 6 8 3 4 6
2 2 2 7 7 7

What I need to do now is feed this result into a function that returns 
the  tuple (4, 6). This is just for my own education and is not homework.

I expect to have Internet access the day after tomorrow and in the 
meantime I will see if I can massage this code further towards a solution.

-- 

Regards,
Phil



More information about the Tutor mailing list