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

145 views Asked by At

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.

2

There are 2 answers

0
Mohamadali Mahmoodpour On

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
0
najeem On

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'