show me how to shuffle the string given the indices list in python

To shuffle a string based on a list of indices in Python, you can follow these steps:

  1. Import the random module.
  2. Convert the string into a list of characters.
  3. Create a new list to store the shuffled string.
  4. Iterate over the indices list and append the corresponding character from the original string to the new list.
  5. Convert the list back to a string.

Here's the code that implements this:

main.py
import random

def shuffle_string(string, indices):
    # Convert string into a list of characters
    char_list = list(string)
    
    # Create a new list to store the shuffled string
    shuffled_list = [None] * len(char_list)
    
    # Iterate over the indices list and append the corresponding character to the new list
    for i, index in enumerate(indices):
        shuffled_list[index] = char_list[i]
    
    # Convert the list back to a string
    shuffled_string = ''.join(shuffled_list)
    
    return shuffled_string

# Example usage
string = "hello"
indices = [3, 1, 4, 0, 2]
shuffled_string = shuffle_string(string, indices)
print(shuffled_string)  # Output: "ohell"
684 chars
24 lines

In this example, the original string is "hello" and the indices list specifies the positions to which each character should be shuffled. The shuffled string is "ohell".

related categories

gistlibby LogSnag