473,545 Members | 529 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I could use some help making this Python code run faster using only Python code.

I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return s

def scrambleFile(fn ame,action=1):
if (path.exists(fn ame)):
try:
f = open(fname, "r")
toks = fname.split('.' )
while (len(toks) 2):
toks.pop()
fname = '.'.join(toks)
if (action == 1):
_fname = fname + '.scrambled'
elif (action == 0):
_fname = fname + '.descrambled'
if (path.exists(_f name)):
os.remove(_fnam e)
ff = open(_fname, "w+")
if (action == 1):
for l in f:
ff.write(scramb leLine(l))
elif (action == 0):
for l in f:
ff.write(descra mbleLine(l))
except Exception, details:
print 'ERROR :: (%s)' % details
finally:
f.close()
ff.close()
else:
print 'WARNING :: Missing file "%s" - cannot continue.' % fname

Sep 20 '07 #1
23 2505
On Sep 20, 10:59 pm, Python Maniac <raych...@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return s
...
Well, scrambleLine will remove line-endings, so when you're
descrambling
you'll be processing the entire file at once. This is particularly bad
because of the way your functions work, adding a character at a time
to
s.

Probably your easiest bet is to iterate over the file using read(N)
for some small N rather than doing a line at a time. Something like:

process_bytes = (descrambleLine , scrambleLine)[action]
while 1:
r = f.read(16)
if not r: break
ff.write(proces s_bytes(r))

In general, rather than building strings by starting with an empty
string and repeatedly adding to it, you should use ''.join(...)

For instance...
def descrambleLine( line):
return ''.join(chr(ord (c) & 0x7f) for c in line)

def scrambleLine(li ne):
return ''.join(chr(ord (c) | 0x80) for c in line)

It's less code, more readable and faster!

--
Paul Hankin

Sep 20 '07 #2
Python Maniac schrieb:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return s
These might benefit from using a lookup-dictionary that maps ord(c) to
the outcome of the operation. Actually, it becomes twice as fast:

import time

lt = {}
for i in xrange(255):
lt[chr(i)] = chr(i | 0x80)

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def scrambleLineLU( line):
s = ''
for c in line:
s += lt[c]
return s
if __name__ == "__main__":
line = "abcdefghijklmn op" * 1000000
start = time.time()
scrambleLine(li ne)
print time.time() - start

start = time.time()
scrambleLineLU( line)
print time.time() - start

Diez

Sep 20 '07 #3
On 9/20/07, Python Maniac <ra******@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.
Well, you could save some time by not applying the scramble one line
at a time (that is if you don't mind losing the line endings in the
scrambled version). For that to be effective though, you probably want
to open in binary mode. Also, your scramble can be written using list
comprehension.

Expand|Select|Wrap|Line Numbers
  1. def scramble(s, key=0x80):
  2. return ''.join([chr(ord(c) ^ key) for c in s])
  3.  
  4. output = scramble(f.read())
  5.  
If you use xor (^) as above, you can use the same method for scramble
as descramble (running it again with the same key will descramble) and
you can use an arbitrary key. Though, with 255 combinations, it isn't
very strong encryption.

If you want stronger encryption you can use the following AESish algorithm:

Expand|Select|Wrap|Line Numbers
  1. import random
  2. def scramble(s, key):
  3. random.seed(key)
  4. return ''.join([chr(ord(c) ^ random.randint(0,255)) for c in s])
  5.  
This allows you to use much larger keys, but with a similar effect.
Still not strong enough to be unbreakable, but much better than the
origional. It is strong enough that someone knowing how you scrambled
it will have trouble unscrambling it even if they don't know the key.

Matt
Sep 20 '07 #4
On 20/09/2007, Python Maniac <ra******@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return ''.join( [chr(ord(c) & 0x7f) for c in line] )

def scrambleFile(fn ame,action=1):
if (path.exists(fn ame)):
try:
f = open(fname, "r")
toks = fname.split('.' )
while (len(toks) 2):
toks.pop()
fname = '.'.join(toks)
if (action == 1):
_fname = fname + '.scrambled'
elif (action == 0):
_fname = fname + '.descrambled'
if (path.exists(_f name)):
os.remove(_fnam e)
ff = open(_fname, "w+")
if (action == 1):
for l in f:
ff.write(scramb leLine(l))
elif (action == 0):
for l in f:
ff.write(descra mbleLine(l))
except Exception, details:
print 'ERROR :: (%s)' % details
finally:
f.close()
ff.close()
else:
print 'WARNING :: Missing file "%s" - cannot continue.' % fname

--

def scrambleLine(li ne):
return ''.join( [chr(ord(c) | 0x80) for c in line] )

def descrambleLine( line):
return ''.join( [chr(ord(c) & 0x7f) for c in line] )

def scrambleFile(fn ame,action=1):
try:
f = open(fname, "r")
fname = '.'.join(fname. split('.')[:2])
if action:
_fname = fname + '.scrambled'
else:
_fname = fname + '.descrambled'
ff = open(_fname, "w")
if action:
ff.write('\r\n. join([scrambleLine(l) for l in f ]))
else :
ff.write('\r\n. join([descrambleLine( l) for l in f ]))
f.close()
ff.close()
except Exception, details:
print 'ERROR :: (%s)' % details

HTH :)
Sep 20 '07 #5
On 21/09/2007, Tim Williams <td*******@gmai l.comwrote:
On 20/09/2007, Python Maniac <ra******@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return ''.join( [chr(ord(c) & 0x7f) for c in line] )

def scrambleFile(fn ame,action=1):
if (path.exists(fn ame)):
try:
f = open(fname, "r")
toks = fname.split('.' )
while (len(toks) 2):
toks.pop()
fname = '.'.join(toks)
if (action == 1):
_fname = fname + '.scrambled'
elif (action == 0):
_fname = fname + '.descrambled'
if (path.exists(_f name)):
os.remove(_fnam e)
ff = open(_fname, "w+")
if (action == 1):
for l in f:
ff.write(scramb leLine(l))
elif (action == 0):
for l in f:
ff.write(descra mbleLine(l))
except Exception, details:
print 'ERROR :: (%s)' % details
finally:
f.close()
ff.close()
else:
print 'WARNING :: Missing file "%s" - cannot continue.' % fname

--


def scrambleLine(li ne):
return ''.join( [chr(ord(c) | 0x80) for c in line] )

def descrambleLine( line):
return ''.join( [chr(ord(c) & 0x7f) for c in line] )

def scrambleFile(fn ame,action=1):
try:
f = open(fname, "r")
fname = '.'.join(fname. split('.')[:2])
if action:
_fname = fname + '.scrambled'
else:
_fname = fname + '.descrambled'
ff = open(_fname, "w")
if action:
ff.write('\r\n. join([scrambleLine(l) for l in f ]))
else :
ff.write('\r\n. join([descrambleLine( l) for l in f ]))
f.close()
ff.close()
except Exception, details:
print 'ERROR :: (%s)' % details

HTH :)
or maybe even this:

Apologies for the self-reply, its late here !
(a couple of typos fixed too! )

def scrambleFile(fn ame,action=1):
try:
f = open(fname, "r")
fname = '.'.join(fname. split('.')[:2])
if action:
ff = open(fname + '.scrambled', "w")
ff.write('\r\n' .join([scrambleLine(l) for l in f ]))
else :
ff = open(fname + '.descrambled', "w")
ff.write('\r\n' .join([descrambleLine( l) for l in f ]))
f.close()
ff.close()

except Exception, details:
print 'ERROR :: (%s)' % details

:)
Sep 20 '07 #6
On Sep 20, 3:57 pm, "Matt McCredie" <mccre...@gmail .comwrote:
On 9/20/07, Python Maniac <raych...@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

Well, you could save some time by not applying the scramble one line
at a time (that is if you don't mind losing the line endings in the
scrambled version). For that to be effective though, you probably want
to open in binary mode. Also, your scramble can be written using list
comprehension.

Expand|Select|Wrap|Line Numbers
  1. def scramble(s, key=0x80):
  2.    return ''.join([chr(ord(c) ^ key) for c in s])
  3. output = scramble(f.read())
  4.  

If you use xor (^) as above, you can use the same method for scramble
as descramble (running it again with the same key will descramble) and
you can use an arbitrary key. Though, with 255 combinations, it isn't
very strong encryption.

If you want stronger encryption you can use the following AESish algorithm:

Expand|Select|Wrap|Line Numbers
  1. import random
  2. def scramble(s, key):
  3.     random.seed(key)
  4.     return ''.join([chr(ord(c) ^ random.randint(0,255)) for c in s])
  5.  

This allows you to use much larger keys, but with a similar effect.
Still not strong enough to be unbreakable, but much better than the
origional. It is strong enough that someone knowing how you scrambled
it will have trouble unscrambling it even if they don't know the key.

Matt
So far I like what was said in this reply however my ultimate goal is
to allow the scramble method to be more than what is shown above.

I considered using XOR however XOR only works for the case shown above
where the scramble method simply sets or removes the MSB.

What I want to be able to do is set or reset the MSB in addition to
performing a series of additional steps without negatively impacting
performance for the later cases when the MSB is not the only technique
being employed.

Hopefully this sheds more light on the goal I have in mind.

BTW - My original code is able to scramble a 20 MB file in roughly 40
secs using a Dell E6600 2.4 GHz. When I began writing the code for
this problem my best runtime was about 65 secs so I know I was heading
in the right direction.

I was about to begin the process of using the D Language and pyd to
gain better performance but then I thought I might also take this
opportunity to learn something about Python before delving into D.
Obviously I could simply code the whole process using D but that
defeats the purpose for using Python in the first place and so I would
tend to limit my low-level coding to the task of scrammbling each line
of text.

The ironic thing about this exorcise was the fact that the
optimization techniques that worked for Python caused the Ruby version
I coded to decrease performance. It seems Ruby has some definite
ideas about what it feels is optimal that it ain't got much to do with
what I would consider to be traditional optimization techniques where
Ruby is concerned. For instance, Ruby felt the putc method was less
optimal than the write method which makes no sense to me but that's
life with Ruby.

Sep 20 '07 #7
On Sep 20, 5:46 pm, Paul Hankin <paul.han...@gm ail.comwrote:
On Sep 20, 10:59 pm, Python Maniac <raych...@hotma il.comwrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.
def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s
def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return s
...

Well, scrambleLine will remove line-endings, so when you're
descrambling
you'll be processing the entire file at once. This is particularly bad
because of the way your functions work, adding a character at a time
to
s.

Probably your easiest bet is to iterate over the file using read(N)
for some small N rather than doing a line at a time. Something like:

process_bytes = (descrambleLine , scrambleLine)[action]
while 1:
r = f.read(16)
if not r: break
ff.write(proces s_bytes(r))

In general, rather than building strings by starting with an empty
string and repeatedly adding to it, you should use ''.join(...)

For instance...
def descrambleLine( line):
return ''.join(chr(ord (c) & 0x7f) for c in line)

def scrambleLine(li ne):
return ''.join(chr(ord (c) | 0x80) for c in line)

It's less code, more readable and faster!
I would have thought that also from what I've heard here.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def scrambleLine1(l ine):
return ''.join([chr(ord(c) | 0x80) for c in line])

if __name__=='__ma in__':
from timeit import Timer
t = Timer("scramble Line('abcdefghi jklmnopqrstuvwx yz')", "from
__main__ import scrambleLine")
print t.timeit()

## scrambleLine
## 13.0013366039
## 12.9461998318
##
## scrambleLine1
## 14.4514098748
## 14.3594400695

How come it's not? Then I noticed you don't have brackets in
the join statement. So I tried without them and got

## 17.6010847978
## 17.6111472418

Am I doing something wrong?
>
--
Paul Hankin

Sep 20 '07 #8
Python Maniac wrote:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.

def scrambleLine(li ne):
s = ''
for c in line:
s += chr(ord(c) | 0x80)
return s

def descrambleLine( line):
s = ''
for c in line:
s += chr(ord(c) & 0x7f)
return s
Try using str.translate instead - it's usually much faster than a pure python loop:
>>scramble = "".join(chr (c | 0x80) for c in range(256))
"source text".translate (scramble)
'\xf3\xef\xf5\x f2\xe3\xe5\xa0\ xf4\xe5\xf8\xf4 '
>>descramble = "".join(chr (c & 0x7F) for c in range(256))
'\xf3\xef\xf5 \xf2\xe3\xe5\xa 0\xf4\xe5\xf8\x f4'.translate(d escramble)
'source text'
>>>
You might then do the translation inline e.g., untested:
def scrambleFile(fn ame,action=1):
translators = {0: descramble, 1: scramble} # defined as above
try:
translation_act ion = translators[action]
except KeyError:
raise ValueError("act ion must be 0 or 1")
if (path.exists(fn ame)):
....
....
for line in f:
ff.write(line.t ranslate(transl ation_action))
....

HTH
Michael

Sep 20 '07 #9
Python Maniac <ra******@hotma il.comwrites:
I am new to Python however I would like some feedback from those who
know more about Python than I do at this time.
Use the array module and do 32-bit or 64-bit operations with it.
See http://nightsong.com/phr/crypto/p3.py for a more serious
encryption module written that way.
Sep 20 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
3108
by: rhmd | last post by:
Just found Python and I love it. What an elegant language! I would like to use it for various applications, but the mathematical calculations are way too slow (a million sines 8 seconds in Python vs. 2 seconds in Excel VBA), so was thinking of learning enough C++ to do the number crunching in C++ and integrating the C++ routines with Python....
6
2043
by: Tony C | last post by:
I'm writing a python program which uses regular expressions, but I'm totally new to regexps. I've got Kuchling's "Regexp HOWTO", "Mastering Regular Expresions" by Oreilly, and have access to online stuff too. But I would like to find a mailing list or newsgroup where I can ask questions about regexps (when things don't work), not...
114
9696
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
3
5166
by: Steve | last post by:
Hi, I have a nice little script that works well displaying images on my website. It's a script where if you clik a thumbnail image a pop up window opens that contains a larger version of the same image. What I would like to create is a link that can be clicked on to close the window that contains the larger image. This would make it easier...
90
4319
by: Ben Finney | last post by:
Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making immutable instances? -- \ "Love is the triumph of imagination over intelligence." -- |
15
2333
by: Claudio Grondi | last post by:
Let's consider a test source code given at the very end of this posting. The question is if Python allows somehow access to the bytes of the representation of a long integer or integer in computers memory? Or does Python hide such implementation details that deep, that there is no way to get down to them? The test code below shows, that...
118
6609
by: 63q2o4i02 | last post by:
Hi, I've been thinking about Python vs. Lisp. I've been learning Python the past few months and like it very much. A few years ago I had an AI class where we had to use Lisp, and I absolutely hated it, having learned C++ a few years prior. They didn't teach Lisp at all and instead expected us to learn on our own. I wasn't aware I had to...
0
1173
by: kuwanger | last post by:
I've been working on some python code to have an open source apack compression (http://www.ibsensoftware.com/products_aPACK.html is a link to the original proprietary version). Just to clarify the legality of all of this, from decompressor source written by Dwedit in arm/thumb assembly I ended up writing unapack.c and then unapack.py...
55
2893
by: sturlamolden | last post by:
I have recently been playing with a kd-tree for solving the "post office problem" in a 12-dimensional space. This is pure cpu bound number crunching, a task for which I suspected Python to be inefficient. My prototype in Python 2.5 using NumPy required 0.41 seconds to construct the tree from 50,000 samples. Unfortunately, searching it felt...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7416
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.