Home > Software design >  Have two lists - for any whitespace in list 1, move element down in list 2 to match without removing
Have two lists - for any whitespace in list 1, move element down in list 2 to match without removing

Time:12-06

Need help on Vigenere cipher to generate the key from the keyword, looking to do this very simply after cyclical rotation to get the keyword the same len as message:

message = "i love my horse"

keyword = "mare"

list1 = ['i', ' ', 'l', 'o', 'v', 'e', ' ', 'm', 'y', ' ', 'h', 'o', 'r', 's', 'e']

list2 = ['m', 'a', 'r', 'e', 'm', 'a', 'r', 'e', 'm', 'a', 'r', 'e', 'm', 'a', 'r']

How can I match up the spacing of list 1 by moving index 1 of list 2 down without taking out the "a"? In other words, how can I push "right" every element of list 2 based on list 1 without removing the element itself?

Appreciate any help! Thank you so much!

CodePudding user response:

You can use itertools.cycle to generate the letters of the keyword repeatedly with the help of a list comprehension:

message = "i love my horse"
keyword = "mare"

from itertools import cycle

c = cycle(keyword)
list2 = [' ' if l == ' ' else next(c) for l in message]

Output:

['m', ' ', 'a', 'r', 'e', 'm', ' ', 'a', 'r', ' ', 'e', 'm', 'a', 'r', 'e']
  • Related