0

Suppose I ask the user to input two strings. I want to find out if the smaller string is a substring of the larger one. I'm not allowed to use the contains() command or any other shortcuts.

I tried putting the both into different lists:

def strtolist(sub_string, string):
    subl=[]
    for i in sub_string:
        subl.append(i)
    print('subl', subl)
    strl=[]
    for e in string:
        strl.append(e)
    print('str', strl)

sub_string = 'App'
string = 'Application'

strtolist(sub_string, string)

Any suggestion on what to do next?

Roberto Caboni
  • 6,078
  • 10
  • 19
  • 34

1 Answers1

0

You don't need to make lists. Just loop over the long string and check if the substring exists at each position.

long_string = "This is a long string"
short_string = "a long"
short_len = len(short_string)
for i in range(len(long_string) - short_len):
    if long_string[i:i+short_len] == short_string:
        print("substring found at index", i)
        break
else:
    print("Substring not found")

The loop iterates over the indexes of the characters in long_string. At each index, it gets the substring starting at that index and containing short_len characters. So when i == 5, it gets the substring from 5 to 10, i.e. 'is a l'. It compares that substring to the string we're searching for, and if it matches it prints the success message and breaks out of the loop.

The else: block is run at the end of the loop if it finished normally without breaking out. If we get there, we never found a matching substring.

Barmar
  • 596,455
  • 48
  • 393
  • 495