Python in Basic 6 (spoiler)

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

Python in Basic 6 (spoiler)

Post by droogans on Sun Jun 12, 2011 4:18 pm
([msg=58406]see Python in Basic 6 (spoiler)[/msg])

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
droogans
New User
New User
 
Posts: 2
Joined: Sun Jun 12, 2011 4:09 pm
Blog: View Blog (0)


Re: Python in Basic 6 (spoiler)

Post by mojo1948 on Sun Jun 12, 2011 6:44 pm
([msg=58423]see Re: Python in Basic 6 (spoiler)[/msg])

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)))])
Never stop learning.
User avatar
mojo1948
Experienced User
Experienced User
 
Posts: 60
Joined: Sun Jul 18, 2010 5:45 am
Blog: View Blog (0)


Re: Python in Basic 6 (spoiler)

Post by droogans on Mon Jun 13, 2011 8:54 am
([msg=58452]see Re: Python in Basic 6 (spoiler)[/msg])

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
droogans
New User
New User
 
Posts: 2
Joined: Sun Jun 12, 2011 4:09 pm
Blog: View Blog (0)


Re: Python in Basic 6 (spoiler)

Post by mojo1948 on Mon Jun 13, 2011 9:58 am
([msg=58454]see Re: Python in Basic 6 (spoiler)[/msg])

It's referred to as "list comprehension", it's part of Pythons implementation of functional style programming.
http://docs.python.org/howto/functional.html
Never stop learning.
User avatar
mojo1948
Experienced User
Experienced User
 
Posts: 60
Joined: Sun Jul 18, 2010 5:45 am
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests