I would like to write my own Python function (i.e. without using any other non base Python functions) to compare the characters in two strings in the following way.
If the letter in position
i
of string 1 is the same as the letter in positioni
of string 2 then"Green"
is returnedIf the letter in position
i
of string 1 is the same as the letter in position[i-1]
or[i 1]
of string 2 then"Blue"
is returnedIf the letter in position
i
of string 1 is not the same as the letters in position[i-1]
,i
or[i 1]
of string 2 then"White"
is returned
The final output of the function should be a tuple of the "Green"
/ "Blue"
/ "White"
output for each letter.
For example, if we call the function letter_comparison
and write:
def letter_comparison(string1, string2):
.....
letter_comparison("chain", "chant")
would return "Green"
, "Green"
, "Green"
, "White"
, "Blue"
.
Any ideas would be appreciated.
CodePudding user response:
In this way, the function still works depending on the length of the words. I have divided it into two functions for convenience.
def Test(word1,word2,pos):
if word1[pos] == word2[pos]:
return "Green"
elif (pos < (len(word1)-2)) and (word1[pos] == word2[pos 1]):
return "Blue"
elif (pos>0) and (word1[pos] == word2[pos-1]):
return "Blue"
else:
return "White"
def letter_comparison(test1, test2):
risultato = []
if len(test1) < len(test2):
for count, char in enumerate(test1):
risultato.append(Test(test1, test2, count))
else:
for count, char in enumerate(test2):
risultato.append(Test(test1, test2, count))
return risultato
CodePudding user response:
Have you tried using a for
loop?
def letter_comparison(string1, string2):
myList = []
if len(string1) != len(string2):
return
for i in range(len(string1)):
try:
l2p = string2[i 1]
except:
l2p = None
try:
l2m = string2[i-1]
except:
l2m = None
if string1[i] == string2[i]:
myList.append("Green")
elif string1[i] == l2p or string1[i] == l2m:
myList.append("Blue")
else:
myList.append("White")
return myList
otherList = letter_comparison("chain", "chant")
print(otherList)
Otherwise, the question was pretty clear and you did a good job.