Nov-01-2018, 06:24 PM
I have an assignment where I need to test strings and only accept the strings that have the same two alternating characters throughout the string... i.e. if the characters were 'a' and 'b' I could only accept strings that are ababab or bababa. My code so far looks like this and I have no clue why it doesn't work or what I am doing wrong.
if string[0:len(string):2] != string[1:len(string):2]:
return string
in my mind, the above code means if the given string, starting at 0, and going the length of the string, every other character, does not equal the string, starting at 1, for the length of the string, and going every other character then it should have alternating characters for the entire length of the string, but it doesn't work.. It does return strings that alternate 'abababa', but also returns strings like 'aababababbbbb' as long as they have both letters it returns them. I am just extremely confused, clearly my logic on this isn't correct. Any guidance would be greatly appreciated!
if string[0:len(string):2] != string[1:len(string):2]:
return string
in my mind, the above code means if the given string, starting at 0, and going the length of the string, every other character, does not equal the string, starting at 1, for the length of the string, and going every other character then it should have alternating characters for the entire length of the string, but it doesn't work.. It does return strings that alternate 'abababa', but also returns strings like 'aababababbbbb' as long as they have both letters it returns them. I am just extremely confused, clearly my logic on this isn't correct. Any guidance would be greatly appreciated!