66.4k views
1 vote
Design a Python3 function to compare every prefix of a string X to every element of string Y, if there is a match, place it in a python set, sort and reversely sort the set, and return the sorted and reversely sorted sets.

User Corey Ray
by
2.8k points

1 Answer

6 votes

Answer:

The function is as follows:

def compare_prefix(strX,strY):

prefix=set()

for i in range(len(strX)):

for j in range(i+1,len(strX)):

chk =strX[i:j+1]

if chk in strY:

prefix.add(chk)

sort_prefix = sorted(prefix)

rev_sort_prefix = sorted(prefix,reverse=True)

return(sort_prefix,rev_sort_prefix)

Step-by-step explanation:

This defines the function

def compare_prefix(strX,strY):

This creates an empty set, prefix

prefix=set()

This iterates through each character in strX

for i in range(len(strX)):

This iterates through every other character in strX

for j in range(i+1,len(strX)):

This gets the prefix of strX by concatenating strings from i to j + 1

chk =strX[i:j+1]

This checks if the prefix is in strY

if chk in strY:

If yes, the string is added to set prefix

prefix.add(chk)

This sorts prefix

sort_prefix = sorted(prefix)

This reverses the sorted prefix

rev_sort_prefix = sorted(prefix,reverse=True)

This returns the sorted and reversed prefix

return(sort_prefix,rev_sort_prefix)

User Colette
by
3.3k points