Python Program to Find Difference between Two Strings
In this tutorial, we will write a Python program to find the difference between the two given strings. This problem can be asked in the interview. Let's understand the problem statement and then we will approach to the solution.
Problem Statement -
There are two strings given s and t. String t is generated by random shuffling string s and then added one more character at any random position. We need to write a Python program that returns the letter added to t.
The following constraints should be followed -
Let's understand the following Python program.
In the above code, we defined the findThedifference() function that takes two strings as arguments. We used the list comprehension to convert the strings into list. Now, we iterate ls_s list, pick single element and remove that element to the second list ls_t. If all element removed from the second element, it means both given strings are same, otherwise return the first element of the second list.
Solution - 2
Let's see another solution of the problem.
In this tutorial, we used the sorted() method, which converts the string into a list of characters in a sorted manner. We created the two lists of strings and added an extra element as 0 to make the length equal; else, we will get the list index out of bounds. Now we iterated the t_list and checked if the s_list element is not equal to t_list; if the condition is matched, it returns that element.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week