Python – Create acronyms from words
Last Updated :
15 Feb, 2023
Given a string, the task is to write a Python program to extract the acronym from that string.
Examples:
Input: Computer Science Engineering
Output: CSE
Input: geeks for geeks
Output: GFG
Input: Uttar pradesh
Output: UP
Approach 1:
The following steps are required:
- Take input as a string.
- Add the first letter of string to output.
- Iterate over the full string and add every next letter to space to output.
- Change the output to uppercase(required acronym).
Python3
def fxn(stng):
oupt = stng[ 0 ]
for i in range ( 1 , len (stng)):
if stng[i - 1 ] = = ' ' :
oupt + = stng[i]
oupt = oupt.upper()
return oupt
inpt1 = "Computer Science Engineering"
print (fxn(inpt1))
inpt1 = "geeks for geeks"
print (fxn(inpt1))
inpt1 = "Uttar pradesh"
print (fxn(inpt1))
|
Output:
CSE
GFG
UP
Time Complexity: O(n) -> looping once through string of length n.
Space Complexity: O(n) -> as space is required for storing individual characters of a string of length n.
Approach 2:
The following steps are required:
- Take input as a string.
- Split the words.
- Iterate over words and add the first letter to output.
- Change the output to uppercase(required acronym).
Python3
def fxn(stng):
lst = stng.split()
oupt = ""
for word in lst:
oupt + = word[ 0 ]
oupt = oupt.upper()
return oupt
inpt1 = "Computer Science Engineering"
print (fxn(inpt1))
inpt1 = "geeks for geeks"
print (fxn(inpt1))
inpt1 = "Uttar pradesh"
print (fxn(inpt1))
|
Output:
CSE
GFG
UP
Time Complexity: O(n) -> looping once through an array of length n.
Space Complexity: O(n) -> as space is required for storing individual characters of a string and an array of length n.
Approach 3: Using regex and reduce()
Here’s one approach using regular expressions (regex) to extract the first letter of each word and reduce function to concatenate them:
Python3
import re
from functools import reduce
def fxn(stng):
words = re.findall(r '\b\w' , stng)
acronym = reduce ( lambda x, y: x + y, [word[ 0 ].upper() for word in words])
return acronym
inpt1 = "Computer Science Engineering"
print (fxn(inpt1))
inpt1 = "geeks for geeks"
print (fxn(inpt1))
inpt1 = "Uttar pradesh"
print (fxn(inpt1))
|
Time Complexity: O(n) -> looping once through an array of length n.
Auxiliary Space: O(n) -> as space is required for storing individual characters of a string and an array of length n.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...