-1

My goal is to get the values in the same index of two different lists (keyNum and stringNum) to add up and the sum to be in a new separate list (encNum). However, when I run the code, it doesn't fully run through the entire list. Here's the code:

def encrypt(key, string):
    letters = 'abcdefghijklmnopqrstuvwxyz'
    keyNum = []
    stringNum = []
    encNum = []
    for symbol in key:
        numKey = letters.find(symbol)
        keyNum.append(numKey)
    for symbol in string:
        numString = letters.find(symbol)
        stringNum.append(numString)
    for element in stringNum:
        a = keyNum.pop(0)
        b = stringNum.pop(0)
        c = a + b
        encNum.append(c)
        print keyNum
        print stringNum
        print encNum
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • You're not even using `element` here, so why loop over the elements of `stringNum` in the first place? If you want to do it this way, just do, say, `while stringNum:`, to loop until you've popped everything. – abarnert Apr 05 '18 at 23:36
  • But a better solution is to not pop in the first place. Just use the elements one by one, and then, if you really want to empty out the list at the end, you can del all of the elements at once, or del the whole list. Less code, harder to get wrong, and faster. – abarnert Apr 05 '18 at 23:37

1 Answers1

0

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.