Python Forum
best way to implement algorithm
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
best way to implement algorithm
#3
Cheating with formatting. Sets are awkward to use in something like this. How do you get the count out of the set? A dictionary is a much better fit, and a counting dictionary does all the work. Just pretty up the output if required.
from collections import Counter

groups=[
    ["word1", "word2"],
    ["word1", "word2","word1"],
    ["word4", "word5","word4", "word5", "word2", "word3"]]

out = Counter([(a,b)  for group in groups for a, b in zip(group, group[1:])])
pairs = ', '.join(f'{{"{key[0]}", "{key[1]}", {value}}}' for key, value in out.items())
print(f'out = [{pairs}]')
Output:
out = [{"word1", "word2", 2}, {"word2", "word1", 1}, {"word4", "word5", 2}, {"word5", "word4", 1}, {"word5", "word2", 1}, {"word2", "word3", 1}]
hamidze likes this post
Reply


Messages In This Thread
best way to implement algorithm - by hamidze - Feb-27-2021, 11:37 AM
RE: best way to implement algorithm - by BashBedlam - Feb-27-2021, 04:05 PM
RE: best way to implement algorithm - by deanhystad - Feb-27-2021, 06:09 PM
RE: best way to implement algorithm - by hamidze - Feb-27-2021, 07:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Right way to implement interfaces yossiy123 1 1,403 May-12-2022, 10:31 AM
Last Post: Gribouillis
  Implement distancematrix to Held karp algorithm Robinjacobsson 1 1,958 Nov-01-2019, 09:24 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020