Home > Net >  Code for consecutive strings works but can't pass random tests
Code for consecutive strings works but can't pass random tests

Time:11-08

In this problem, I'm given an array(list) strarr of strings and an integer k. My task is to return the first longest string consisting of k consecutive strings taken in the array. My code passed all the sample tests from CodeWars but can't seem to pass the random tests.

Here's the link to the problem.

I did it in two days. I found the max consecutively combined string first. Here's the code for that.

strarr = []

def longest_consec(strarr, k):
    strarr.append('')
    length = len(strarr)
    cons_list = []
    end = k
    start = 0
    freq = -length/2
    final_string = []
    largest = max(strarr, key=len, default='')
    if k == 1:
        return largest
    elif 1 < k < length:
        while(freq <= 1):
            cons_list.append(strarr[start:end])
            start  = k-1
            end  = k-1
            freq  = 1
        for index in cons_list:
            final_string.append(''.join(index))
        return max(final_string, key=len, default='')  
    else:
        return ""

Since that didn't pass all the random tests, I compared the combined k strings on both sides of the single largest string. But, this way, the code doesn't account for the case when the single largest string is in the middle. Please help.

strarr = []

def longest_consec(strarr, k):
    strarr.append('')
    length = len(strarr)
    largest = max(strarr, key=len, default='')
    pos = int(strarr.index(largest))
    if k == 1:
        return largest
    elif 1 < k < length:
        prev_string = ''.join(strarr[pos 1-k:pos 1])
        next_string = ''.join(strarr[pos:pos k])
        if len(prev_string) >= len(next_string):
            res = prev_string
        else: 
            res = next_string
        return res
    else:
        return ""

print(longest_consec(["zone", "abigail", "theta", "form", "libe"], 2))

CodePudding user response:

Let's start from the first statement of your function:

if k == 1:
    while(p <= 1):
        b.append(strarr[j:i])
        j  = 1
        i  = 1
        p  = 1
    for w in b:
        q.append(''.join(w))
    return max(q, key=len)

Here q is finally equal strarr so you can shorten this code to:

if k == 1:
    return max(strarr, key=len)

I see that second statement's condition checks if k value is between 1 and length of string array inclusive:

elif k > 1 and k <= 2*a:
    ...

If you want no errors remove equality symbol, last element of every array has index lesser than its length (equal exactly length of it minus 1). Ceiling and division is not necessary in a definition, so you can shorten this:

a = ceil(len(strarr)/2)

into this:

a = len(strarr)

then your elif statement may look like below:

elif 1 < k < a:  # Same as (k > 1 and k < a)
    ...

again, I see you want to concatenate (add) the longest string to k next strings using this code:

while(p <= 1):
    b.append(strarr[j:i])
    j  = k-1
    i  = k-1
    p  = 1
for w in b:
    q.append(''.join(w))
return max(q, key=len)

the more clearer way of doing this:

longest = max(strarr, key=len)  # Longest string in array.
index = 0  # Index of the current item.
for string in strarr:
    # If current string is equal the longest one ...
    if string == longest:
        # Join 'k' strings from current index (longest string index).
        return ''.join(strarr[index:index   k])
    index  = 1  # Increase current index.

And the last statement which is:

elif k > 2*a or k<1:
    return ""

if all previous statements failed then value is invalid so you can instead write:

return ""  # Same as with else.

Now everything should work. I advice you learning the basics (especially lists, strings and slices), and please name your variables wisely so they are more readable.

CodePudding user response:

You can try this as well

l = ["zones", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"]
k = 2
def get_max(l, k):
  i = 0
  max_ = ""
  res = ""
  while i<(len(l)-k):
    start = "".join(l[i:i k])
    max_ = max(max_, start, key=len)
    if max_==start:
      res=l[i:i k]
    i =1
  return max_, res
get_max(l,k)

#output: ["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2 -> abigailtheta
#output: ["zones", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"],2 -> zonesabigail
  • Related