Python | Scramble strings in list
Last Updated :
13 Apr, 2023
Sometimes, while working with different applications, we can come across a problem in which we require to shuffle all the strings in the list input we get. This kind of problem can particularly occur in gaming domain. Let's discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension + sample() + join() The combination of above functions can be used to solve this problem. In this, we need to disintegrate string into character list, scramble using sample(), rejoin them using join() and then remake list using list comprehension.
Python3
# Python3 code to demonstrate working of
# Scramble strings in list
# using list comprehension + sample() + join()
from random import sample
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# Scramble strings in list
# using list comprehension + sample() + join()
res = [''.join(sample(ele, len(ele))) for ele in test_list]
# printing result
print("Scrambled strings in lists are : " + str(res))
Output : The original list : ['gfg', 'is', 'best', 'for', 'geeks']
Scrambled strings in lists are : ['fgg', 'is', 'btse', 'rof', 'sgeke']
Time complexity: O(n), where n is the length of the numbers list. The list comprehension + sample() + join() have a time complexity of O(n)
Auxiliary Space: O(n),where n is the length of the numbers list.
Method #2 : Using list comprehension + shuffle() + join() This is similar to the above method. The only difference is that shuffle() is used to perform scramble task than using sample().
Python3
# Python3 code to demonstrate working of
# Scramble strings in list
# using list comprehension + shuffle() + join()
from random import shuffle
# Utility function
def perform_scramble(ele):
ele = list(ele)
shuffle(ele)
return ''.join(ele)
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# Scramble strings in list
# using list comprehension + shuffle() + join()
res = [perform_scramble(ele) for ele in test_list]
# printing result
print("Scrambled strings in lists are : " + str(res))
Output : The original list : ['gfg', 'is', 'best', 'for', 'geeks']
Scrambled strings in lists are : ['fgg', 'is', 'btse', 'rof', 'sgeke']
Using str.maketrans() and str.translate():
Approach:
In this approach, we will create a translation table using the str.maketrans() method and then apply it to each string using the str.translate() method.
Python3
import random
def scramble_strings(strings):
result = []
for s in strings:
table = str.maketrans(s, ''.join(random.sample(s, len(s))))
result.append(s.translate(table))
return result
strings = ['gfg', 'is', 'best', 'for', 'geeks']
scrambled = scramble_strings(strings)
print("The original list:", strings)
print("Scrambled strings in lists are:", scrambled)
OutputThe original list: ['gfg', 'is', 'best', 'for', 'geeks']
Scrambled strings in lists are: ['ggg', 'is', 'tbse', 'for', 'eeegk']
Time complexity: O(n * k) where n is the number of strings in the list and k is the average length of the strings.
Auxiliary Space: O(k) where k is the maximum length of the strings in the list.
METHOD 3:Using for.
APPROACH:
This Approach tells how to scramble the strings in a given list of strings by shuffling the characters in each string between the first and last characters while keeping the first and last characters of each string in their original position.
ALGORITHM:
1.Import the random module
2.Create an original list of strings
3.Create an empty list to store scrambled strings
4.Iterate over each string in the original list
a. Extract the characters between the first and last characters of the string
b. Shuffle the extracted characters using the shuffle() method from the random module
c. Combine the first character, shuffled characters, and the last character of the string
d. Append the scrambled string to the scrambled list
5.Print the scrambled list
Python3
import random
# Original list of strings
original_list = ['gfg', 'is', 'best', 'for', 'geeks']
# Empty list to store scrambled strings
scrambled_list = []
# Iterate over each string in the original list
for string in original_list:
# Scramble the characters between the first and last characters
middle_chars = list(string[1:-1])
random.shuffle(middle_chars)
# Combine the first, scrambled middle, and last characters
scrambled_string = string[0] + ''.join(middle_chars) + string[-1]
# Append the scrambled string to the list of scrambled strings
scrambled_list.append(scrambled_string)
# Print the scrambled list
print("Scrambled strings in list are:", scrambled_list)
OutputScrambled strings in list are: ['gfg', 'is', 'best', 'for', 'gkees']
Time complexity: O(n * k * log k), where n is the number of strings in the list and k is the maximum length of a string in the list. The shuffle operation takes O(k * log k) time complexity, and we perform it for each string in the list.
Auxiliary Space: O(n * k), where n is the number of strings in the list and k is the maximum length of a string in the list. We create a new string of length k for each string in the list.
Similar Reads
List of strings in Python A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Python - Reverse Range in String List Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
3 min read
Python | Split flatten String List Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python | Extract Score list of String Sometimes, while programming we can have a problem in which we dedicate to each character of alphabets a particular score and then according to string, extract only those score for further computations. This can have application in gaming domain. Let's discuss certain ways in which this task can be
3 min read
Python | Grouping similar substrings in list Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let's discuss certain ways in which this can be done.
7 min read
How to sort a list of strings in Python In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort().Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly.Pythona = ["banana", "apple", "cherry"] # Sorting list in place a.sort()
2 min read
Create a List of Strings in Python Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Python | Append String to list Sometimes, while working with data, we can have a problem in which we need to add elements to a container. The list can contain any type of data type. Let's discuss certain ways in Python in which we can perform string append operations in the list of integers.Example: Append String at the end of a
5 min read
Remove Duplicate Strings from a List in Python Removing duplicates helps in reducing redundancy and improving data consistency. In this article, we will explore various ways to do this. set() method converts the list into a set, which automatically removes duplicates because sets do not allow duplicate values.Pythona = ["Learn", "Python", "With"
3 min read
Reverse All Strings in String List in Python We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb'].Using For LoopWe can use a for loop to iterate over th
2 min read