+ 7

why is this program do not give required output?

i write this program to print same result as printed by print(x.split()) https://code.sololearn.com/cSFHWoPnh47p/?ref=app

17th Mar 2019, 2:19 PM
Shobhit
Shobhit - avatar
4 odpowiedzi
+ 3
This is what you have: for i in range(len(x)): while i<len(x) and x[i]==' ': i+=1 while i<len(x) and x[i]!=' ': a+=x[i] i+=1 y.append(a) a="" Now, your for loop will iterate through the input anyway, so you don’t need: while i<len(x): i+=1 at all. But these could be useful as ‘if’ statements, so let’s change them to that and remove the ‘i<len(x)’ as we don’t need them. for i in range(len(x)): if x[i]==' ': i+=1 if [i]!=' ': a+=x[i] i+=1 y.append(a) a="" Now, your first if asks whether x[i] is a space. If it is, then we want to append the word we’ve found so far so y and then reset a. So let’s change that. for i in range(len(x)): if x[i]==' ': y.append(a) a = “” if [i]!=' ': a+=x[i] i+=1 y.append(a) a="" We have a problem, though, that with every iteration of your for loop, you’re resetting a with the statement a=“”, so we need to get rid of that. Your second if doesn’t need i+=1 for the same reason as earlier. So we’re nearly there. for i in range(len(x)): if x[i]==' ': y.append(a) a = “” if [i]!=' ': a+=x[i] y.append(a) The last problem is that a is being appended to y with every iteration too. Currently this code is only appending the word a to y when a space is encountered, but this means it won’t append the last word of the input. So we need this ‘y.append(a)’ statement after the for loop has finished. We can simply de-indent that line. for i in range(len(x)): if x[i]==' ': y.append(a) a = “” if [i]!=' ': a+=x[i] y.append(a) ...and there you have it. I think this is what you were going for and I hope you could understand my explanation. Edit to add: Demo https://code.sololearn.com/c5zuNTnkliDU/?ref=app
17th Mar 2019, 3:04 PM
Russ
Russ - avatar
+ 8
thanks
17th Mar 2019, 5:10 PM
Shobhit
Shobhit - avatar
+ 5
please solve them i am confused
17th Mar 2019, 2:24 PM
Shobhit
Shobhit - avatar
+ 1
it has some errors in syntax.... I've hinted.... check them. out
17th Mar 2019, 2:23 PM
Vintager
Vintager - avatar