Search code examples
pythonstringsequences

Mysterious python behaviour


Im trying to write a quick script to output a sequence. The sequence begins is as follows: 1,11,21,1211,111221,312211... starts with 1, then as 1 1 the second term is 11, as two 1s third term is then 21's ect.

I have written a script below which outputs the terms in this sequence. It outputs the correct next term when the input_string is 1, ie 11. But ALL terms after then output as 11 too..... if I manually set the input to 11, then all the terms are calculated correctly.

This makes no sense, as with the initial input of "1" my total_sequence[0] variable will be "1", giving the correct output of "11". The next term will then have total_sequence[1] as its input, which is "11" i.e. the last iterations output. But this gives "11" as its output. If I directly put "11" in as the total_sequence[1] term instead of referencing total_sequence[1] ( which = "11") then the correct output is then given.

So basically why is input_string = "11" different to output[1] where output = ["1","11"]?

input_string= "1"
N=5
total_sequence = [input_string]

for i in xrange(0,N,1):    
    N_counter = int(0)
    previous_char = ""
    output_string = ""
    character_index = int(1)

    #loop through each character in the current sequence term
    for current_char in total_sequence[i]:
        #if first character
        if  character_index == 1:
            N_counter = 1
        #if last character
        if character_index == len(input_string):
            if current_char == previous_char:
                N_counter = N_counter + 1

            if current_char != previous_char:
                if previous_char!="":
                    output_string  = output_string + str( N_counter ) + str( previous_char )
                N_counter = int( 1 )    
            output_string  = output_string + str( N_counter ) + str( current_char )

        #if neither first nor last character
        if character_index != 1 and character_index != len(input_string) :
            if current_char == previous_char:
                N_counter = N_counter + 1

            if current_char != previous_char:
                output_string  = output_string + str( N_counter ) + str( previous_char )
                N_counter = int( 1 )

        character_index = character_index + 1
        previous_char = current_char

    total_sequence.append( output_string)  

print total_sequence

Solution

  • You are using input_string in the body of your loop, but that is never changed, it is always the very first string, in your example "1".

    Probably changing the first line of the inner loop with:

    input_string = total_sequence[i]
    for current_char in input_string:
    

    should be enough, but I didn't test it.