Reputation: 3163
I am trying to solve through a challenge where I have to reorder the letters in string s in the order it appears on string t. For example:
For s = "weather" and t = "therapyw", the output should be
sortByString(s, t) = "theeraw";
For s = "good" and t = "odg", the output should be
sortByString(s, t) = "oodg".
This is my code:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.insert(i, t_list[i])
return ''.join(output)
It works for all cases except if the same letter exists more than once.
s: "weather"
t: "therapyw"
Output:
"theraw"
Expected Output:
"theeraw"
How can I handle this situation in my code above? What am I missing? I appreciate all help but instead of just blurting out the answer, I would like to know what I'm doing wrong.
Upvotes: 0
Views: 60
Reputation: 953
2 steps:
a. create a sorted list of characters in s and their order in t using index()
b. use zip(* to extract the sorted list of characters
s = "weather"
t = "therapy"
a = sorted([(t.index(c),c) for c in s])
b = ''.join(list(zip(*a))[1])
print(b)
Output:
theeraw
Upvotes: 0
Reputation: 304
Use enumerate and turn your string into a dict
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
orderdict = {char: index for index, char in enumerate(t_list)}
output = sorted(list('weather'),key=orderdict.get)
return ''.join(output)
This will allow repeated values
>>> sortByString('weather',"therapyw")
'theeraw'
Just add the element number of times it appear in s
to the output
def sortByString(s,t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.append(t_list[i]*s_list.count(t_list[i]))
return ''.join(output)
>>> sortByString('weather',"therapyw")
'theeraw'
Upvotes: 0
Reputation: 147166
The issue with your current code is that it only adds one copy of each character in t
to output
, regardless of how many times it occurs in s
. You can work around that by looping over the count
of that character in s
and appending to output
for each count:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
for _ in range(s_list.count(t_list[i])):
output.append(t_list[i])
return ''.join(output)
print(sortByString('weather',"therapyw"))
print(sortByString('good',"odg"))
Output:
theeraw
oodg
You can simplify the loop by just adding copies of a list with the current character according to the count of the character in s
:
for c in t_list:
output = output + [c] * s_list.count(c)
Upvotes: 1