'Index out of range when it should not
Hello guys im learning python and im trying to make a string that concentrates binary numbers together baseed on similarity from a list .. so ['1','0','0','0','0','1','1'] becomes '1 0000 11' .. I wrote something and ive been staring at the screen for an hour trying to find the mistake i made ., anyone have any idea why is s[i]+1 giving me an out of index error when it should not be entered anyway ? .
s=['1','1','0','0','0','0','1']
for i in range(len(s)) :
u=''
if i <= (len(s)-1):
if s[i]==s[i+1]:
u+=s[i]
elif s[i] != s[i+1]:
u+=(s[i]+' ')
elif i==len(s):
u+=s[i]
Solution 1:[1]
s=['1','1','0','0','0','0','1']
print("LENGTH: " + str(len(s)))
u=''
for i in range(len(s)) :
if i < len(s) - 1:
if s[i]==s[i+1]:
u+=s[i]
elif s[i] != s[i+1]:
u+=(s[i]+' ')
else:
u+=s[i]
print(u)
IIUC, with some minor changes, this does what you want.
output: 11 0000 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Josip Juros |