Skip to content
Advertisement

How can I generate the smallest sequence of adjacent and distinct numbers?

For example, I would like a function that, given the symbols of + or – (ascending and descending), makes the smallest sequence of no more than 8 digits distinct and adjacent numbers

examples of inputs:

my_function("---")
output: 4321

my_function("-+-")
output: 2143

my_function("+-+-")
output: 13254

as i am trying:

def my_function(sequence):
    result=[]
    values = list(range(1, len(sequence)+2))
    print(values)
    for i in sequence:
        if(i == "-"):
            print(values[-1])
            result.append(values[-1])
            values.pop(-1)
        else:
            result.append(values[0])
            values.pop(0)

    result.append(values[0])
    return result
    
print(my_function("+-+-"))

Advertisement

Answer

Solution:

def my_function(sequence):
    result = []
    sequence = list(sequence)
    values = list(range(1, len(sequence)+2))
    contDescending, contAscending= 0, 0
    last=""
    for i, ordem in enumerate(sequence):
        last = ordem if i == 0 else last
        if(ordem!=last):
            last=ordem
            if(contAscending>0):
                for j in range(contAscending):
                    result.append(values[0])
                    values.pop(0)
            if(contDescending>0):
                for k in range(contDescending):
                    result.append(values[contDescending-k])
                    values.pop(contDescending-k)
            contDescending, contAscending= 0, 0

        contDescending+=1 if ordem == "-" else contDescending
        contAscending+=1 if ordem == "+" else contAscending 

        if(i == len(sequence)-1):
            if(contAscending>0):
                for j in range(contAscending):
                    result.append(values[0])
                    values.pop(0)

            if(contDescending>0):
                for k in range(contDescending):
                    result.append(values[contDescending-k])
                    values.pop(contDescending-k)
            
            contDescending, contAscending= 0, 0
            result.append(values[0])
    return int("".join(map(str, result)))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement