I have this method:
def encode(message, rails):
result = ""
dataRails = []
activeRail = 0
# allocate multi-dimensional array...seems inefficient
for r in range(rails):
dataRails.append([])
# copy characters from message into one of the arrays, or .
for m in message:
count = 0
# for each rail either give it the character or a .
while count <= rails:
print("Count: ", str(count), " Active Rail:", str(activeRail))
if activeRail == count:
dataRails[activeRail][count] = m
else:
dataRails[activeRail][count] = "."
count += 1
activeRail += 1
if activeRail >= rails:
activeRail = 0
for r in dataRails:
print(r)
# ill calculate result once I get the above right
return result
Message is a string of text. Rails is a number. The encode method would be called like this:
encode('XOXOXOXOXOXOXOXOXO', 2)
In this case, I want to allocate my dataRails as 2 elements, each the same length as input message. I would replace elements in the arrays with either a letter from message or a ".".
But, it seems rather inefficient to use a loop to allocate dataRails.
When I run this, I get the following error:
dataRails[activeRail][count] = m
IndexError: list assignment index out of range
The print statement looks like valid index values:
Count: 0 Active Rail: 0
It feels like there are two problems with my multi-dimensional array. 1) allocation and 2) access.
If there is a duplicate question, please post a link. I searched through stackoverflow. Answers that seemed relevant relied on a library, which I did not want to use. I have just started learning python and want to learn the basics of python, not using libraries.
Are arrays really that difficult in python or did I make it more difficult than it needs to me?
Thanks Matt
Edit: Ultimately, if the message input was this "WE ARE DIS", the return of this method would be "WEERDSAI". I am working through a tutorial on exercism.io. I haven't completed the method yet. I am stuck on the array I defined.
dataRails = [[] for _ in range(rails)]... .apppend(m)whileand counters instead offorloops, multiple checks on one variable, and skipped string slices altogether. A simple Caesar cipher would be much shorter, so I'm not sure what you're trying to accomplish; the example has too many duplicate letters to be intuitive.appendcomments should get you to the next set of problems. :-)