0

I am trying to generate a Vigenère Cipher Table and store it as an array where each row on the table is an individual list entry inside of the list vCipherChart. Ideally vCipherChart would output:

[["A","B","C"...],["B","C","D"...] ... ["Z","A","B"...]]

However when I run my code it returns:

[["Z","A","B"...],["Z","A","B"...] ... ["Z","A","B"...]]

I am unsure what is causing this, as I am appending the new list entries generated by cycleAlphabet to the variable vCipherChart. Any help would be much appreciated!

    import array

    def cycleAlphabet(alphabet):
        newLastEntry = alphabet[0]
        alphabet.remove(newLastEntry)
        alphabet.append(newLastEntry)
        return alphabet
    
    def generateCipherChart():
        vCipherChart = [["A","B","C","D","E","F","G","H","I","J","K","L","M",
                         "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]]
        i = 0
        while i < 25:
            alphabet = vCipherChart[i]
            newAlphabet = cycleAlphabet(alphabet)
            vCipherChart.append(newAlphabet)
            i+=1
        return vCipherChart

print(generateCipherChart())
Serris
  • 1
  • 1
  • 5
    `newAlphabet` is **not** new, you only have one inner list and you keep mutating it and filling the outer list with multiple references to it. – jonrsharpe Jun 22 '22 at 10:21
  • Why did you `import array`? It is never used. You are using Python ***lists***, not arrays... – Tomerikoo Jun 22 '22 at 11:17

1 Answers1

0

I would deal with the problem like this:

  • Would pass the alphabet and i to the cycleAlphabet function: def cycleAlphabet(vCipherChart, i):
  • Treat each line as addition of two lines: alphabet = vCipherChart[i:] + vCipherChart[:i]
  • I wouldn't use i = 0, it's not pythonic, better use for and enumerate() for each letter in the alphabet: for i, _ in enumerate(vCipherChart):
  • Would create a new list for the cypher instead of using the alphabet.

The code would look something like this:

def cycleAlphabet(vCipherChart, i):
    alphabet = vCipherChart[i:] + vCipherChart[:i]
    return alphabet


def generateCipherChart():
    vCipherChart = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
                   "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    newAlphabet = []
    for i, _ in enumerate(vCipherChart):
        lew_line = cycleAlphabet(vCipherChart, i)
        newAlphabet.append(lew_line)
    return newAlphabet


print(generateCipherChart())

With list comprehension it could be made into:

def cycleAlphabet(vCipherChart, i):
    alphabet = vCipherChart[i:] + vCipherChart[:i]
    return alphabet


def generateCipherChart():
    vCipherChart = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
                   "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    newAlphabet = [cycleAlphabet(vCypherChart, i) for i, _ in enumerate(vCypherChart)]
    return newAlphabet


print(generateCipherChart())