+ 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
4 Respostas
+ 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
+ 8
thanks
+ 5
please solve them i am confused
+ 1
it has some errors in syntax.... I've hinted.... check them. out