Sunday, June 30, 2019

IslandT: Create a Python function to compare the end string

Hello friend, we will start a new Python project in the next chapter but before that let us solve another Python problem first in this article. This is one of the questions in codewars which I have solved today : Given a string and an end string, compare the end string part with the end part of the given string, if they match each other, then return true, otherwise return false. For example, if the given string is “Hello” and the end string is “ello” then the function will return true. If the given string is “World” and the end string is “rld!” the the function will return false.

The strategy of this function is to extract the last few words from the given string that match the length of the end string and then compare them one by one!

def solution(string, ending):

    endinglist = list(ending)
    stringlist = list(string)
    stringlist= stringlist[len(stringlist)-len(endinglist):] # the end part of the given string which matches the length of the end string
    
    while(len(endinglist) > 0):

        elem = endinglist.pop(0)
        elem_1 = stringlist.pop(0)
        if(elem != elem_1):
            return False
        
    return True

The program just goes through the while loop and if there is a wrong match then the loop will terminate and return False.

Well, what do you people think about the above code? Just like you, I am just starting to learn Python programming, if you have a better solution then do make sure everyone hear your voice by providing your better idea under the comment box below this post!

Beginning from the next chapter we will start a brand new Python project so make sure you subscribe to the rss feed under the Python category of this website, there is no harm to subscribe to other category as well because besides writing Python article I also write other topics as well! Go ahead and take a look at them!



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...