Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Keep the longest chains
#11
(Jul-03-2019, 03:32 PM)nilamo Wrote: Why isn't '7 8 9' the first chain in '7 8 9 45 16'?

It's really hard to help, when your output doesn't make sense. Help us to understand how you're coming up with what the output should be, otherwise we're just guessing at how to help.

Indeed it is an error on my part, '7 8 9' are well part of the second chain ['7 8 9 45 16', '7 8 9 45'] ...

My apologies, I'm getting lost too ...
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python code for Longest Common Subsequence Bolt 3 949 Sep-22-2023, 08:09 AM
Last Post: Bolt
  Python implementation of Longest Common Substring problem Bolt 0 555 Sep-17-2023, 08:31 PM
Last Post: Bolt
  longest palindromic subsequence DP solution bug usercat123 9 2,337 Feb-05-2022, 06:00 AM
Last Post: deanhystad
  Longest sequence of repeating integers in a numpy array Cricri 5 5,777 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