1

I don't know if the title is apt, but for the time being this is my question:

I have entries in text file(which has 2 columns) in the following format:

Name     Time  

Santa    1.2
Jim      2.5
Santa    2.7
Santa    2.9

I should form a dictionary which has Name as the key, (Time, Count) as the value. In the above names, Santa repeated 3 times and the time difference of consecutive occurances is less than 2 seconds. So the Count value associated with that entry is 3. If such case occurs, that entry should be deleted from dictionary. Otherwise, count value should be zero (If the 2 occurances of Santa happened 2 seconds apart and 3rd occurance happened after 2 seconds, then count is reinitialized to zero for that entry).

Can this be implemented like this: Make the (Time, Count) as the list and make that list as the values to the keys? I am a newbie to Python, please excuse any mistakes.

The pseudocode is something like this:

Read line in the file:   
    if Santa is in dictionary:    
        time_difference = time from column 2 of the line - dictionary[Santa]  
        if(time_difference < 2):  
            Replace the old occurance with new one along with time  
            # If the previous count value associated with Santa = 1, add 1 to make it 2  
            Make the Count associated with Santa = count+1    
            if(count associated with Santa = 3):  
                delete the Santa entry    
        else:  
            Make count associated with Santa = 1      
    else:  
        Add Santa to dictionary along with its time and make associated count = 1
4

1 回答 1

1

EDIT: i just noticed you wanted to restart the count timer after 2 seconds of inactivity, i will post that fix in a moment.

EDIT2: okay, i added it. should be good to go!

not the cleanest code, but it gets the job done.

class dictholder():
    def __init__(self):
        self.dict = {}

    def add(self, name, time):
        if name in self.dict:
            if (abs(time) - abs(self.dict[name][0]) < 2):
                self.dict[name][1] += 1
                self.dict[name][0] = time
                if self.dict[name][1] == 3:
                    del self.dict[name]
        else:
            self.dict[name] = [time, 1]
        for item in self.dict:
            if (abs(time) - abs(self.dict[item][0]) > 2):
                self.dict[item][1] = 1

    def get(self):
        return self.dict

example:

d = dictholder()
d.add("Santa", 1.2)
d.add("Jim", 2.5)
d.add("Santa", 2.7)
d.add("Santa", 2.9)

print d.get()

>>> 
{'Jim': [2.5, 1]}
>>> 
于 2012-08-06T13:48:29.307 回答