jeudi 21 mars 2019

class 'int' instead of type 'int': string indices must be integers

I have a simple Python function where I'm swapping values in a string. I'm doing this by generating a pseudorandom integer, then swapping it with the next index or previous index to avoid out of bounds exceptions.

However, I am getting TypeError: string indices must be integers. When I add a print statement to check the type of the index that is generated by the secrets.randbelow() function, it returns class 'int', whereas I would expect type 'int'. Is this what's causing the error?

Function

import secrets as random


def shuffle_sequence(sequence):
    sequence_len = int(len(sequence))
    for x in range(0, sequence_len):
        swap_index = random.randbelow(sequence_len)
        next_index = 0
        if swap_index != sequence_len:
            next_index = swap_index + 1
        else:
            next_index = swap_index - 1
        sequence[swap_index, next_index] = sequence[next_index, swap_index]
        x += 1
    return sequence

I even adding an int conversion to the first line of the function hoping that would help, but it's returning the same class of int, which is expected.

To clarify, sequence is a string of letters, numbers, and symbols.




Aucun commentaire:

Enregistrer un commentaire