Algorithmic problems

Asked 2 years ago, Updated 2 years ago, 43 views

No matter how many hours I spent looking back at the logic and reworking the code, it wasn't wrong with my logic and code. If you press the scoring button on the site, you will see several failures. The problem is, if you accept a string of lowercase letters, and if you have neighboring alphabets in that string, you keep erasing them, and eventually you can erase all the alphabets, you return either 1 or 0. I've been looking at it for hours, but I don't know what's wrong Help me!

I solved it with this kind of logic. The source code is as follows:

// Enter your code here
def delString(s,i=0):
    while(True):
        try:
            if s[i] == s[i+1]:
                #Initially the same case
                if i==0:
                    s = s[2:]
                    s = delString(s)
                    break
                #Same case at the end
                elif i== len(s)-2:
                    s = s[:-2]
                    s = delString(s,i-2)
                    break
                #Same case in the middle
                else:
                    s = s[:i] + s[i+2:]
                    s = delString(s,i-1)
                    break
        except:
            break
        i +=1
    return s

python3 algorithm

2022-09-22 15:06

1 Answers

Regular expressions make writing more convenient.

import re

def solution(line):
    If line == ': # If blank, successful
        return 1
    else:    
        If re.search(r'(\w)\1', line): # Does the character pair exist?
            return solution (re.sub(r'\w)\1', '', line)) # Remove if present and repeat
        else: # 0 return if not present
            return 0


2022-09-22 15:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.