Algorithm problem, python line, no idea

I have an algorithm problem with Python and strings.

My problem:

My function is supposed to sum the maximum values โ€‹โ€‹of the substring. For example:

ae-afi-re-fi -> 2+6+3+5=16
but 
ae-a-fi-re-fi -> 2-10+5+3+5=5

      

I am trying to use the string.count function and count the substring, but this method does not work. What would be the best way to do this in Python? Thanks in advance.

string = "aeafirefi"

      

Sum the values โ€‹โ€‹of the substrings.

+3


source to share


3 answers


In my solution, I will use the module permutations

from itertools

to list all the possible substring permutations that you specified in your question presented in a dict titled vals

. Then iterate over the input line and split the lines into all permutations found below. Then we sum the values โ€‹โ€‹of each permutation and finally get max.

PS: The key to this solution is the method get_sublists()

.

This is an example with some tests:

from itertools import permutations 

def get_sublists(a, perm_vals):
    # Find the sublists in the input string
    # Based on the permutations of the dict vals.keys()
    for k in perm_vals:
        if k in a:
            a = ''.join(a.split(k))
            # Yield the sublist if we found any
            yield k

def sum_sublists(a, sub, vals):
    # Join the sublist and compare it to the input string
    # Get the difference by lenght
    diff = len(a) - len(''.join(sub))
    # Sum the value of each sublist (on every permutation)
    return sub , sum(vals[k] for k in sub) - diff * 10

def get_max_sum_sublists(a, vals):
    # Get all the possible permutations
    perm_vals = permutations(vals.keys())
    # Remove duplicates if there is any
    sub = set(tuple(get_sublists(a, k)) for k in perm_vals)
    # Get the sum of each possible permutation
    aa = (sum_sublists(a, k, vals) for k in sub)
    # return the max of the above operation
    return max(aa, key= lambda x: x[1])


vals = {'ae': 2, 'qd': 3, 'qdd': 5, 'fir': 4, 'afi': 6, 're': 3, 'fi': 5}

# Test
a = "aeafirefi"
final, s = get_max_sum_sublists(a, vals)
print("Sublists: {}\nSum: {}".format(final, s))
print('----')
a = "aeafirefiqdd"
final, s = get_max_sum_sublists(a, vals)
print("Sublists: {}\nSum: {}".format(final, s))
print('----')
a = "aeafirefiqddks"
final, s = get_max_sum_sublists(a, vals)
print("Sublists: {}\nSum: {}".format(final, s))

      



Output:

Sublists: ('ae', 'afi', 're', 'fi')
Sum: 16
----
Sublists: ('afi', 'ae', 'qdd', 're', 'fi')
Sum: 21
----
Sublists: ('afi', 'ae', 'qdd', 're', 'fi')
Sum: 1

      

Please try this solution with as many input lines as you can, and feel free to comment if you find any wrong result.

0


source


Possibly a dictionary with: key = substring: value = value

So, if you have:
string = "aeafirefi"



first you look for the whole string in the dictionary, if you don't find it, you shorten the last letter so that you have "aeafiref" until you find a substring or you have a single letter.

then you will skip the letters used: for example, if you find "aeaf", you start over with = "iref".

0


source


Here's a brute force solution:

values_dict = {
    'ae': 2,
    'qd': 3,
    'qdd': 5,
    'fir': 4,
    'afi': 6,
    're': 3,
    'fi': 5
}

def get_value(x):
    return values_dict[x] if x in values_dict else -10

def next_tokens(s):
    """Returns possible tokens"""
    # Return any tokens in values_dict
    for x in values_dict.keys():
        if s.startswith(x):
            yield x

    # Return single character.
    yield s[0]

def permute(s, stack=[]):
    """Returns all possible variations"""

    if len(s) == 0:
        yield stack
        return

    for token in next_tokens(s):
        perms = permute(s[len(token):], stack + [token])
        for perm in perms:
            yield perm

def process_string(s):
    def process_tokens(tokens):
        return sum(map(get_value, tokens))

    return max(map(process_tokens, permute(s)))

print('Max: {}'.format(process_string('aeafirefi')))

      

0


source







All Articles