The skipping-items issue that you have described is due popping from stringNum
while also iterating over it in your third for-loop. In the first iteration of this loop, element = stringNum[0]
and in that same loop you then pop that item from the list. So in the next iteration element = stringNum[1]
, however, since the first item from the original list has been removed element
is actually equal to the stringNum[2]
from the original list, prior to the that for loop commencing.
The snippet below is an example of what happens when you pop from the left of a list while also iterating over it:
>>> some_list = [1, 2, 3, 4, 5, 6, 7]
>>> for item in some_list:
... print('Iterated item: {}'.format(item))
... print('Popped item: {}'.format(some_list.pop(0)))
...
Iterated item: 1
Popped item: 1
Iterated item: 3
Popped item: 2
Iterated item: 5
Popped item: 3
Iterated item: 7
Popped item: 4
If both key
and string
are the same length, like the description of your method implies, then you would be after something more like this for your third loop, which would is more appropriate than popping from the left while iterating over the same list:
for keyVal, strVal in zip(numKey, numString):
encNum.append(keyVal + strVal)
Or you could even combine all three loops into one:
for keyX, strX in zip(key, string):
keyVal = letters.find(keyX)
strVal = letters.find(strX)
encNum.append(keyVal + strVal)
However, neither of these will work if len(key) != len(string)
, and your re-implementation would then require some more thought.