4.5k views
1 vote
You and your friend want to name the new dog on the street. You will pick the firstname and he will pick the lastname. However, turns out that both of you have faulty vocabularies. You only know certain english alphabets, and he knows certain other. Print all possible names that you and your friend can come up with given that you both use all the letters you know, exactly once, to form a name and you pick the first name and he picks the lastname. Use recursion for printing all the names. You must print all the names in lexicographically increasing order. Input Format The first line contains a string of the alphabets known by you, all distinct. The second line contains a string of the alphabets known by him, all distinct. *The first and the last name may contain common letters. The letters are only distinct within the names themselves. Output all the names in separate lines with a space in between the name and the surname. See the sample for a better understanding of the problem.

User Sigmund
by
8.2k points

1 Answer

2 votes

Answer:

Here's a Python code that uses recursion to generate and print all possible names you and your friend can come up with based on the alphabets you both know:

def generate_names(your_alphabets, friend_alphabets, name, last_name):

if len(name) == len(your_alphabets) and len(last_name) == len(friend_alphabets):

print(name + " " + last_name)

return

if len(name) < len(your_alphabets):

for char in your_alphabets:

if char not in name:

generate_names(your_alphabets, friend_alphabets, name + char, last_name)

if len(last_name) < len(friend_alphabets):

for char in friend_alphabets:

if char not in last_name:

generate_names(your_alphabets, friend_alphabets, name, last_name + char)

your_alphabets = input().strip()

friend_alphabets = input().strip()

generate_names(your_alphabets, friend_alphabets, "", "")

Step-by-step explanation:

You can input the alphabets known by you and your friend, and this code will generate and print all possible names in lexicographically increasing order, considering that each alphabet is used exactly once in the first name and last name.

User Chuckedw
by
7.7k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.