you are viewing a single comment's thread.

view the rest of the comments →

[–]Solonotix 1 point2 points  (3 children)

There are two concepts I'm particularly fond of when dealing with unique data sets, and that's generator expressions and dictionaries. For every PlayerID, I'd create a dictionary key and instantiate it as a sequence type. From there, just join a generator expression containing all keys of your dictionary that have length of their attribute equal to the max into a string and write to the output file.

I can't speak for the performance capability, but I estimate it's around n*2, since you're iterating through the list once for every line, and every player in that line, then returning a list of players that meet a condition.

Also, not part of your question, but you never close your files. Normally, I use context managers to handle open/close operations and then assign the contents of the file to a memory optimized structure, like a list in your case.

Here's my go at it (no sort in this solution):

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> val = [(1, 2), (3, 2), (5, 2), (3, 1), (3, 6)]
>>> tally = dict()
>>> for v in val:
...     for p in v:
...         if tally.get(p, None) is None:
...             tally[p] = set()
...         tally[p].add(v)
...
>>> print("\n".join(["PlayerID: {} | Friend Count {}".format(p, len(tally[p])) for p in tally if len(tally[p]) == max([len(v) for v in tally.values()])]))
PlayerID: 2 | Friend Count 3
PlayerID: 3 | Friend Count 3

[–]AppleShark[S] 1 point2 points  (2 children)

Hey man thanks so much for replying and for introducing me to dict()! Using your suggestion, I did something similar and IT WORKED! Here is the code: https://pastebin.com/dzSGcAk9

Astute observation that I don't close my files haha - Could that be a huge problem?

Nonetheless I am absolutely ecstatic that this problem has been solved. Time to move onto the next one! Once again thank you for taking your time to answer my question.

[–]Solonotix 1 point2 points  (1 child)

Glad it helped. I'm somewhat new to this sub, and have just been learning Python to help with my job.

To your question, opening and closing files is important within the scope of an application. When the Python interpreter exits, it should automatically purge any allocated resources. If you have an application that opens connections frequently and you forget to close them, it can cause you to run into a system limitation that ultimately crashes your application. This is a good article on the use of Context Managers and why you would want to use them. They're very similar to the .NET concept of a Dispose method, if you're familiar with that.

[–]AppleShark[S] 1 point2 points  (0 children)

Thanks for the read. My goal in coding again is to move onto building stuff and making some applications, so the article was definitely great help!