Challenging way of counting entries of a file dynamically

2024/10/15 15:24:38

I am facing a strange question, which despite of trying many times, i am not able to find the logic and proper code to the problem.

I have a file in the format below:

aa:bb:cc dd:ee:ff 100  ---------->line1
aa:bb:cc dd:ee:ff 101  ---------->line2
dd:ee:ff aa:bb:cc 230  ---------->line3
dd:ee:ff aa:bb:cc 231  ---------->line4
dd:ee:ff aa:bb:cc 232  ---------->line5
aa:bb:cc dd:ee:ff 102  ---------->line6
aa:bb:cc dd:ee:ff 103  ---------->line7
aa:bb:cc dd:ee:ff 108  ---------->line8
dd:ee:ff aa:bb:cc 233  ---------->line9  
gg:hh:ii jj:kk:ll 450  ---------->line10
jj:kk:ll gg:hh:ii 600  ---------->line11

My program should read the file line by line. In the first line and second line, corresponding column1 and column2 values are equal. Third column is the sequence number which is not the same for any two lines.
Since line1 and line2 are same except, their sequence numbers differ by value of only 1, i should read those two lines first and write their count as 2 to an output file. If we observe, line 6 and line 7 are same as line 1 and line 2, having consecutive sequence numbers, but the line numbers line3, line4, line5 having different column 1 and column 2 entries came in between them. Hence lines(1&2) and lines(6&7) should not be grouped all together. So, in the output file, i should get result like 2 3 2 1 1 1 1. And one more thing is, lines 7 and 8 are differed by sequence number more than 1. Hence, line 8 should be counted as a separate entry, not together with lines 6 and 7 though lines 6,7,8 has same first two columns.
I hope most people understood the question. If not, i will clarify anything on the question.
As you can see this is a very complicated problem. I tried using dictionary as that is the only data structure i know, but no logic works. Please help me solve this problem.

Answer
with open("abc") as f:#read the first line and set the number from it as the value of `prev`num, col4 = next(f).rsplit(None,2)[-2:] #use `str.rsplit` for minimum splitsprev  = int(num)col4_prev = col4count = 1                               #initialize `count` to 1for lin in f:num, col4 = lin.rsplit(None,2)[-2:]num  = int(num)                    if num - prev == 1:             #if current `num` - `prev` == 1count+=1                        # increment `count` prev = num                      # set `prev` = `num`else:print count,col4_prev       #else print `count` or write it to a file count = 1                       #reset `count` to 1prev = num                      #set `prev` = `num`col4_prev = col4if num - prev != 1:print count,col4

output:

2 400
3 600
2 400
1 111
1 500
1 999
1 888

Where 'abc' contains:

aa:bb:cc dd:ee:ff 100 400
aa:bb:cc dd:ee:ff 101 400 
dd:ee:ff aa:bb:cc 230 600 
dd:ee:ff aa:bb:cc 231 600
dd:ee:ff aa:bb:cc 232 600
aa:bb:cc dd:ee:ff 102 400
aa:bb:cc dd:ee:ff 103 400
aa:bb:cc dd:ee:ff 108 111 
dd:ee:ff aa:bb:cc 233 500 
gg:hh:ii jj:kk:ll 450 999
jj:kk:ll gg:hh:ii 600 888 
https://en.xdnf.cn/q/117821.html

Related Q&A

NSException on import of matplotlib, kivy in OSX

Im working on some kivy code thats working fine on windows 10, but crashes on osx sierra, Ive isolated that the crash happens when I import kivy.core.window along side matplotlib: import matplotlib mat…

strange behavior with lamba: getattr(obj, x) inside a list [duplicate]

This question already has answers here:Creating functions (or lambdas) in a loop (or comprehension)(9 answers)Closed 11 years ago.In the following example:class A(object):passprop1 = 1prop2 = 2prop3 = …

Detect or Generate Regular Expression from String

I was wondering if there were any Python packages out there that detects a regular expression from a string. Conceptually this is easy enough to do but I wanted to see if there was anyone else who has …

Date regex python

I am trying to match dates in a string where the date is formatted as (month dd, yyyy). I am confused by what I see when I use my regex pattern below. It only matches strings that begin with a date. Wh…

Not able to install the python-module numpy

After hours of trying Im still not able to install numpy. I READ LOTS OF HINTS, ANSWERS USW. BUT IT DOESNT HELP. Furthermore I have windows 7, 32 bit, Python 27. What I did:download numpy-1.10.2.zi…

Windows Error: 32 when trying to rename file in python

Im trying to rename some PDF files using pyPdf and my code it seems to work fine until it reaches the rename sentence. The While/if block of code looks for the page number where string "This stri…

I dont quite understand the while loop in python

def AddSingleCard(self):symbols = [heart, diamond, club, spade]#newCardSign = newCardNumber, newCardSign = raw_input().split()try:newCardNumber = int(float(newCardNumber))except:newCardNumber, newCardS…

Adding a FileField to a custom SignupForm with django-allauth

I have the following custom SignupForm (simplified, works perfectly without my_file):class SignupForm(forms.Form):home_phone = forms.CharField(validators=[phone_regex], max_length=15)my_file = forms.Fi…

Checkbox to determine if an action is completed or not

I have a list of dictionaries of clients in a format like this:dict_list = [{Name of Business : Amazon, Contact Name : Jeff Bezos, Email : [email protected]}, {Name of Business : Microsoft, Contact Nam…

Python not concatenating string and unicode to link

When I append a Unicode string to the end of str, I can not click on the URL.Bad:base_url = https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&tit…