Pattern decoding

后端 未结 3 1777
情话喂你
情话喂你 2021-01-16 03:02

I need a little help in the following. I have this kind of datafile:

0 0    # <--- Group 1 -- 1 house (0) and 1 room (0)

0 0    # <--- Group 2 -- 2 ho         


        
3条回答
  •  鱼传尺愫
    2021-01-16 03:07

    I would first define a House class and a Group class:

    class House:
        def __init__(self, rooms):
            self.rooms = rooms
    
    
    class Group:
        def __init__(self, index, houses):
            self.index = index
            # houses.values() is a list with number of rooms for each house.
            self.houses = [House(houses[house_nr]) for house_nr in sorted(houses)]
    
        def __str__(self):
            return 'Group {}'.format(self.index)
    
        def __repr__(self):
            return 'Group {}'.format(self.index)
    

    Then parse the data into this hierarchical structure:

    with open('in.txt') as f:             
        groups = []
    
        # Variable to accumulate current group.
        group = collections.defaultdict(int)
    
        i = 1
        for line in f:
            if not line.strip():
                # Empty line found, create a new group.
                groups.append(Group(i, group))
                # Reset accumulator.
                group = collections.defaultdict(int)
                i += 1
                continue
    
            house_nr, room_nr = line.split()
            group[house_nr] += 1
        # Create the last group at EOF
        groups.append(Group(i, group))
    

    Then you can do stuff like this:

    found = filter(
        lambda g:
            len(g.houses) == 1 and # Group contains one house
            g.houses[0].rooms == 1, # First house contains one room
        groups)
    print(list(found)) # Prints [Group 1, Group 5, Group 6]
    
    found = filter(
        lambda g:
            len(g.houses) == 2 and # Group contains two houses
            g.houses[0].rooms == 3 and # First house contains three rooms
            g.houses[1].rooms == 2, # Second house contains two rooms
        groups)
    print(list(found)) # Prints [Group 2]
    

提交回复
热议问题