+ 3

Make this code compact

'''Write a program that takes in a string that contains a sentence, checks if the first letter of each word is the same as the last letter of the previous word. If the condition is met, output true, if not, output false. Casing does not matter. Sample Input: this string gets stuck Sample Output: true ''' string = input().split(" ") #print (string) list = [] for i in range(len(string)-1): letter = string[i][-1] if letter == string [i+1][0]: list.append("true") else: list.append("false") if all(i == "true" for i in list): print ("true") else: print ("false") I have already solved this codecoach challenge and the code I wrote has cleared all the tests. But I would love to see how you all write this code in a better way. As I am a newbie with no friends who code, This is only way I can see how other coders approach a problem. Thanks a lot!!

9th Jan 2021, 2:04 PM
CHANDAN ROY
CHANDAN ROY - avatar
7 ответов
+ 8
CHANDAN ROY I tried list comprehension but not sure if this will work since I dont know the details of the challenge. https://code.sololearn.com/cbK6hY5seAyR/?ref=app
9th Jan 2021, 2:25 PM
noteve
noteve - avatar
+ 7
probably instead of list of bools, just create 1 bool var and initialize it to true..whenever the chars are not same , set it to false and break else dont do anything..btw we are same..newbie and no friends xD
9th Jan 2021, 2:17 PM
durian
durian - avatar
+ 5
I would do a little edit: https://code.sololearn.com/c3a9A148a25a
9th Jan 2021, 2:23 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 5
a="this string gets stuck" Two ways I implemented it: 1. ______ list=[] for i,j in enumerate(a): if j==" ": if a[i-1]==a[i+1]: list.append(True) else: list.append(False) print("true" if all(list) else "false") 2. _______ print("true" if all([True if a[i-1]==a[i+1] else False for i,j in enumerate(a) if j==" "]) else "false")
9th Jan 2021, 2:32 PM
Abhay
Abhay - avatar
+ 4
What Lily mea said is a better way to do it which just didn't came to my mind at all!
9th Jan 2021, 2:34 PM
Abhay
Abhay - avatar
+ 3
You could iterate like for idx, word in enumerate(string): ... Instead of "true" you may append just True (bool) to your list. I would encourage you, not to name your list "list" because it overwrites list(), which could cause problems in a bigger program. Maybe you could break from the for-loop right when the condition is not met.
9th Jan 2021, 2:21 PM
Lisa
Lisa - avatar
+ 3
《 Nicko12 》 this is short and clean..python sure really have some sneaky short syntax 😅
9th Jan 2021, 2:35 PM
durian
durian - avatar