Winkleson here! I am currently learning Python when I got stuck on a problem. I’ve gotten to the point where I’m dizzy just thinking about it 😛 Anyways any help would be greatly appreciated! Thanks in advance!
Question:
Interlock
Create a function that takes two strings that are the same
length or within one character of the same length as parameters. It
should then take these two strings and interlock them, taking one
character from each string, interlocking them. If the strings are
different lengths, then the result should always start with the longer
string.
My Coding (sorry I’m a beginner and it’s not very Pythonic :P):
def interlock(s1, s2):
r = 0
l1 = []
l2 = []
inters = ''
for i in range(len(s1)):
l1.append(i)
for i in range(len(s2)):
l2.append(i)
if len(s2) == len(s1):
for i in range(len(s1)):
inters += ''.join(s1[i])
inters += ''.join(s2[i])
elif len(s1) < len(s2):
for i in range(len(s1)):
inters += ''.join(s2[i])
inters += ''.join(s1[i])
r = i
inters += ''.join(s2[r])
elif len(s2) < len(s1):
for i in range(len(s2)):
inters += ''.join(s1[i])
inters += ''.join(s2[i])
r = i
inters += ''.join(s1[r])
else:
pass
return inters
Results (what results I recieve):
___________________________________________________________________________________________
Call Expected Received Correct
interlock('shoe','cold') schooled schooled true
interlock('flat','etry') feltarty feltarty true
**interlock('ab','siy') saiby saibi false**
**interlock('abalone','hammer') ahbaamlmoenre ahbaamlmoenrn false**
interlock('','a') a a true
___________________________________________________________________________________________
The two bolder fields are where I am having the most issues. If I try to add in the last characters I get a mysterious out of range exception. Any ideas/solutions would be greatly appreciated! – Winkleson
P.s This is shorter than my normal posts… Usually I’ll give an (un)accurate idea on what I’m think I’m doing wrong and it drags on and on and on and on…. you get the idea. Anyways I probably broke my loops like an idiot. So… Goodluck!
THANKS
Thank you everyone who suggested ways to become a better programmer! I don’t get much time in a day to program so it’s great when so many people take time out of their day to suggest stuff. I love this website and it’s community 🙂
While others are showing you how to do this using itertools (which is a very useful exercise), this will hopefully demonstrate how to write your function to help you learn some basic programming:
I’ve purposefully kept a lot of the structure from your original code, only removing the pieces which are completely unnecessary (e.g. your excessive use of
str.join).