PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, June 27, 2022

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

 June 27, 2022     graph, list, numbers, python, python-3.x     No comments   

Issue

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("+-+-"))

Solution

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)))


Answered By - Alan Romualdo
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing