Python - Sequence Assignment to Words
Last Updated :
16 May, 2023
Given a String of words, assign an index to each word.
Input : test_str = 'geeksforgeeks is best'
Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'}
Explanation : Index assigned to each word.
Input : test_str = 'geeksforgeeks best'
Output : {0: 'geeksforgeeks', 1: 'best'}
Explanation : Index assigned to each word.
Method #1: Using enumerate() + dict() + split()
In this, we first perform task of split() and then add index component to map each word with index using enumerate().
Python3
# Python3 code to demonstrate working of
# Sequence Assignment to Words
# Using split() + enumerate() + dict()
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# using dict() to convert result in idx:word manner
res = dict(enumerate(test_str.split()))
# printing result
print("The Assigned Sequence : " + str(res))
OutputThe original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}
Method #2: Using zip() + count() + dict()
In this, the count() component renders the index logic and pairing of each word to index is done using zip().
Python3
# Python3 code to demonstrate working of
# Sequence Assignment to Words
# Using zip() + count() + dict()
from itertools import count
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# using dict() to convert result in idx:word manner
# count() from itertools used for this task
res = dict(zip(count(), test_str.split()))
# printing result
print("The Assigned Sequence : " + str(res))
OutputThe original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach #3: Dictionary comprehension
Split the input string into words using the split() function. Create a dictionary comprehension to assign a sequence number to each word using the word indices as keys and the words as values.
Step-by-step approach:
- Split the input string into words using the split() function and store the resulting list in a variable called words.
- Create a new dictionary using a dictionary comprehension.
- Iterate over the indices of the words list using the range() function
- For each index i, add a new key-value pair to the dictionary where the key is i and the value is the word at index i.
- Print the resulting dictionary.
Python3
test_str = 'geeksforgeeks is best'
words = test_str.split()
result = {i: words[i] for i in range(len(words))}
print(result)
Output{0: 'geeksforgeeks', 1: 'is', 2: 'best'}
Time Complexity: O(n), where n is the number of words in the input string. The split() function has a time complexity of O(n), and the dictionary comprehension iterates over the indices of the words list once.
Space Complexity: O(n), where n is the number of words in the input string. The space complexity is dominated by the resulting dictionary, which has n key-value pairs.
Approach #4: Using list comprehension:
Step-by-step approach:
- Initialize the input string test_str.
- Split the string into a list of words using the split() method.
- Initialize an iterator using the count() function from the itertools module.
- Use the zip() function to combine the iterator with the list of words and create a tuple for each word with its corresponding index.
- Use the dict() function to convert the tuples into a dictionary with the index as the key and the word as the value.
- Print the resulting dictionary.
Python3
# Python3 code to demonstrate working of
# Sequence Assignment to Words
# Using list comprehension
# initializing string
test_str = 'geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# using list comprehension to convert result in idx:word manner
res = {idx: word for idx, word in enumerate(test_str.split())}
# printing result
print("The Assigned Sequence : " + str(res))
#This code is contributed by Rayudu.
OutputThe original string is : geeksforgeeks is best for geeks
The Assigned Sequence : {0: 'geeksforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of words in the input string. This is because the split() method takes O(n) time to split the string into words, and the zip() function takes O(n) time to create tuples for each word. The dict() function takes O(n) time to create the dictionary.
Auxiliary Space:
The space complexity of this algorithm is O(n), where n is the number of words in the input string. This is because the split() method creates a new list of words with length n, and the resulting dictionary also has n key-value pairs. The iterator created using the count() function takes up a constant amount of space.
Method #5: Use a for loop and a dictionary to store the index and corresponding word.
Step-by-step approach:
- Initialize an empty dictionary res_dict to store the index and corresponding word pairs.
- Split the input string test_str into a list of words using the split() function and assign it to word_list.
- Loop through the word_list using a for loop and enumerate() function to get the index and corresponding word at each iteration.
- Add each index and word pair to the res_dict dictionary using the index as the key and the word as the value.
- Print the res_dict dictionary to show the assigned sequence.
Python3
# initializing string
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
# using for loop and dictionary to assign sequence
res_dict = {}
word_list = test_str.split()
for idx, word in enumerate(word_list):
res_dict[idx] = word
# printing result
print("The Assigned Sequence : " + str(res_dict))
OutputThe original string is : geeksforgeeks is best for geeks
The Assigned Sequence : {0: 'geeksforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}
Time complexity: O(n) where n is the number of words in the input string.
Auxiliary space: O(n) to store the dictionary of index and word pairs.
Similar Reads
Python program to count words in a sentence
In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence.Pythons = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_count) Output5 Explanat
2 min read
Python - Print the last word in a sentence
Printing the last word in a sentence involves extracting the final word , often done by splitting the sentence into words or traversing the string from the end.Using split() methodsplit() method divides the string into words using spaces, making it easy to access the last word by retrieving the last
3 min read
Split a sentence into list of words in Python
When working with text in Python, we often need to break down a sentence into individual words. This task is easy to accomplish in Python using different methods. The simplest way is by using split(), but more complex tasks can be handled with regular expressions or list comprehension. Depending on
2 min read
Python - Words Lengths in String
We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6].Using List
2 min read
Python program to sort Palindrome Words in a Sentence
Given a string S representing a sentence, the task is to reorder all the palindromic words present in the sentence in sorted order. Examples: Input: S = "Please refer to the madam to know the level"Output: Please level to the madam to know the referExplanation: Here "refer", "madam", "level" are the
5 min read
Python - Move Word to Rear end
Sometimes, while working with Python strings, we can have a problem in which we need to find a word and move it to the end of the string. This can have application in many domains, including day-day programming and school programming. Let's discuss certain ways in which this task can be performed. M
6 min read
Python - Maximum Scoring word
Given a String, the task is to write a Python program to compute maximum scoring words i.e words made of characters with a maximum positional summation. Examples: Input : test_str = 'geeks must use geeksforgeeks for cs knowledge'Output : geeksforgeeksExplanation : Sum of characters positional values
5 min read
Python - Add Space between Potential Words
Given list of Strings, task is to add a space before sequence which begin with capital letters. Input : test_list = ["gfgBest", "forGeeks", "andComputerScienceStudents"] Output : ['gfg Best', 'for Geeks', 'and Computer Science Students'] Explanation : Words segregated by Capitals. Input : test_list
7 min read
Python - Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
2 min read
Replace multiple words with K - Python
We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K".Using List ComprehensionThis is the most efficient
4 min read