Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Keep the longest chains
#12
So '7 8 9' is a root fragment of two different chains...

With that in mind, I'd recommend the following steps:
1) sort your list of chain-framents by length. The shortest ones are always the beginning of a chain, so they should be the first ones you process.
2) for each chain fragment, check if the beginning of the fragment matches any other complete fragment.
3) keep track of the chains in a dict, with the keys being the root of the fragment and the values being a dict of branching fragments that continue the chain.

You'll probably need to write a recursive function for step 2 that will find the deepest matching node.

After writing some helper functions, your code will probably look like:
fragments = [
    '1 2 3 4',
    '7 8 9 10 11 12',
    '4 5 2 1 8'
# etc
]

chains = {}
fragments.sort()
for fragment in fragments:
    match = find_root_fragment(fragment, chains)
    if match is None:
        match = chains
    match[fragment] = {}
Reply


Messages In This Thread
Keep the longest chains - by Amniote - Jul-03-2019, 08:57 AM
RE: Keep the longest chains - by perfringo - Jul-03-2019, 09:22 AM
RE: Keep the longest chains - by Amniote - Jul-03-2019, 01:24 PM
RE: Keep the longest chains - by SheeppOSU - Jul-03-2019, 01:47 PM
RE: Keep the longest chains - by perfringo - Jul-03-2019, 02:03 PM
RE: Keep the longest chains - by Amniote - Jul-03-2019, 03:12 PM
RE: Keep the longest chains - by perfringo - Jul-03-2019, 03:32 PM
RE: Keep the longest chains - by nilamo - Jul-03-2019, 03:19 PM
RE: Keep the longest chains - by Amniote - Jul-03-2019, 03:24 PM
RE: Keep the longest chains - by nilamo - Jul-03-2019, 03:32 PM
RE: Keep the longest chains - by Amniote - Jul-03-2019, 04:51 PM
RE: Keep the longest chains - by nilamo - Jul-03-2019, 05:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python code for Longest Common Subsequence Bolt 3 971 Sep-22-2023, 08:09 AM
Last Post: Bolt
  Python implementation of Longest Common Substring problem Bolt 0 575 Sep-17-2023, 08:31 PM
Last Post: Bolt
  longest palindromic subsequence DP solution bug usercat123 9 2,379 Feb-05-2022, 06:00 AM
Last Post: deanhystad
  Longest sequence of repeating integers in a numpy array Cricri 5 5,817 Jun-08-2020, 06:48 AM
Last Post: Cricri

Forum Jump:

User Panel Messages

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