Sorting array of strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Sorting array of strings

Hello I want to sort a array containing strings such that the last letter of the string is the first letter of the next string in python. Eg: ['abcd' , cba', ' def'] output ['cba', 'abcd','def']

19th Sep 2020, 1:44 PM
Varshith
Varshith - avatar
4 Answers
+ 5
I don't think that this can be done with sorting. It looks like a similra task from LeetCode named ? destination. paths = [["London","New York"],["Lima","Sao Paulo"],["New York","Lima"]] task description is: You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
19th Sep 2020, 3:24 PM
Lothar
Lothar - avatar
+ 3
['abc','sdf','qwe'] what will be the output? Also show your attempt.
19th Sep 2020, 2:02 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 1
Hai Samsil Arefeen I have not done but i think this problem can be solved by nested for loop . The output for this testcase ['abc','sdf','qwe'] is -1
19th Sep 2020, 2:14 PM
Varshith
Varshith - avatar
+ 1
Hello guys I am sorry i have not entered the question properly in that question they will give the two inputs the first one is array and the second one is the string to start with. The first word means where to start Here is the code array=list(input().split()) first_word=input().strip() result=[] result.append(first_word) count=0 for _ in range(len(array)): for i in array: if i[0]==result[count][-1]: result.append(i) array.remove(i) count+=1 if result: print(*result) else: print(-1) Eg:1) Array=['abcd' , cba', ' def'] first_word='cba' Output cba abcd def 2) Array=['abcd' , cba', ' def'] first_word='abcd' output abcd def
19th Sep 2020, 4:34 PM
Varshith
Varshith - avatar