Page 1 of 1

Python in Basic 6 (spoiler)

PostPosted: Sun Jun 12, 2011 4:18 pm
by droogans
I hate posting answers but honestly if you can use this you can look up the damn ascii chart.

Here's my question:

How can I dynamically append elements from a "for each in range(x)" sort of loop onto a string that has not yet been defined?

Example:

Code: Select all
encrypt = '5e9i=57m'

for each in range(len(encrypt)):
    pw += chr(ord(encrypt[each]) - each)

Traceback (most recent call last):
  File "<pyshell#154>", line 2, in <module>
    pw += chr(ord(encrypt[each]) - each)
NameError: name 'pw' is not defined


It worked once I went back and deliberately introduced pw


Code: Select all
pw = ''
for each in range(len(encrypt)):
    pw += chr(ord(encrypt[each]) - each)


Anyway, how can I avoid the pw = '' declaration? Is it possible?

Andrew

Re: Python in Basic 6 (spoiler)

PostPosted: Sun Jun 12, 2011 6:44 pm
by mojo1948
It's possible but defining pw is easier.
Code: Select all
encrypt = '5e9i=57m'
print ''.join([chr(x-y) for x,y in zip(map(ord,encrypt), range(0,len(encrypt)))])

Re: Python in Basic 6 (spoiler)

PostPosted: Mon Jun 13, 2011 8:54 am
by droogans
Mojo -

You read my mind. My first stab at this was to map the list before the chr(ord()) call, but I used .join(' ') at the end.

You print the call to join, then do your work... :idea: I used the for loop to bring in my use of join, which I see here as unneeded.

Thanks for showing me this. I will probably never use your exact approach, as it is highly unreadable, but masking string manipulation within a list was my goal...and will help me in the future. I'll probably come up with a technique that's a little more intuitive than what I see here.

+1 to you,

Andrew

Re: Python in Basic 6 (spoiler)

PostPosted: Mon Jun 13, 2011 9:58 am
by mojo1948
It's referred to as "list comprehension", it's part of Pythons implementation of functional style programming.
http://docs.python.org/howto/functional.html