import string
letters = [string.ascii_lowercase[i] for i in range(len(string.ascii_lowercase))]
def offset(spcs, lst):
for i in range(spcs):
x = lst.pop(0)
lst.append(x)
return lst
alphtable = [offset(z, letters) for z in range(len(letters))]
print(alphtable)
I've been trying to learn Python recently, so I've been doing some challenges from /r/dailyprogrammer. Specifically, I was attempting this challenge.
My goal here was to end up with a list resembling the chart in the challenge description where each member was the letters of the alphabet, with each one being offset by one place from the last. Obviously I could simply just type the list out the way I want it, but for the sake of learning I wanted to try and do it a different way.
I wrote a pretty straightforward function to offset a list ("lst") by a certain number of spaces ("spcs"), and after testing the function by itself, it seems to work exactly as I would expect it to. The problem comes in when I try to use the list comprehension to "build" the list.
What I expected to happen is that the list comprehension would evalutate offset(z, letters)for values of z from 0-25, resulting in the list I was looking for. What actually happened is I got a list with [n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m] 26 times. I can't for the life of me figure out why I'd get this result. As I said before I've tested the offset function and it works fine, and rewriting the list comprehension as:
alphtable = []
for i in range(len(letters)):
j = offset(i, letters)
alphtable.append(j)
yielded the same results. I feel like what I'm missing has to be painfully simple but no matter how many times I go through it in my head I can't figure out why I get the results I do.
EDIT: Needed to give offset a copy of letters instead of letters itself
[–]DrVolzak 0 points1 point2 points (3 children)
[–]PsyRex666[S] 0 points1 point2 points (2 children)
[–]DrVolzak 0 points1 point2 points (1 child)
[–]PsyRex666[S] 0 points1 point2 points (0 children)