Home > Software engineering >  How to make a random, reverse acronym (Backronym) in Python from a given list?
How to make a random, reverse acronym (Backronym) in Python from a given list?

Time:08-11

Suppose we have a name:
x='STAR'

and a list:
y=['super', 'sunny', 'talented', 'arrogant', 'apple', 'razor', 'rhyme']

How do we get an output like this -

S for Super
T for Talented
A for Apple
R for razor

where all the words are picked up randomly from list y.

CodePudding user response:

You can use a combination of list and dict:

given an example :

y=['super', 'sunny', 'talented', 'arrogant', 'apple', 'razor', 'rhyme']

x = ''.join(list(dict.fromkeys(x[0].upper() for x in y)))
print(x)
>>> STAR

CodePudding user response:

Here's one way.

from random import choice
x = "STAR"
y=['super', 'sunny', 'talented', 'arrogant', 'apple', 'razor', 'rhyme']

t = ""
for c in x:
    y_filtered = [i for i in y if i[0].lower() == c.lower()]
    t  = f"{c.upper()} for {choice(y_filtered)} "
print(t.strip())
# 'S for sunny T for talented A for arrogant R for rhyme'
  • Related