[Tutor] function won't import from module

Javier Ruere javier at ruere.com.ar
Tue Aug 9 08:22:32 CEST 2005


Dick Moores wrote:
> I have a bunch of functions I've collected in one script, "mycalc.py", 
> which I use as a module, "mycalc". The last one I wrote, cmpSeq() is as 
> follows:
>
[code]
>
> In a script, cmpSeq() works fine. For example followed by
>
[example]
>
> The output is:
> 
[output]
> 
> cmpSeq() is now copy-pasted into mycalc.py, but is not useable there:
> 
[example]
> 
> which produces:
> 
[Traceback]
>
> However, other functions in mycalc work fine. For example:
> 
[example]
> 
> That may have been a bit long-winded; if so, I apologize.

  Not at all! :)
  I couldn't reproduce the error. The problem is not in the given code then. Use PyChecker or PyLint to aid you find the problem.

  Other comments:

Instead of:

     for index in range(len(shorterOrEqualSequence)):
         if seq1[index] != seq2[index]:
             prints...
             break

     if index == len(shorterOrEqualSequence)-1:
         print "sequences are identical thru end of shorter sequence at index", index

this could be used:

     for index in range(len(shorterOrEqualSequence)):
         if seq1[index] != seq2[index]:
             prints...
             break
     else:
         print "sequences are identical thru end of shorter sequence at index", index

And instead of:

     if len(seq1) >= len(seq2):
         shorterOrEqualSequence = seq2
     else:
         shorterOrEqualSequence = seq1

     for index in range(len(shorterOrEqualSequence)):
         etc.

this could be used:

     for index in xrange(min(len(seq1), len(seq2))):
         etc.

The main loop, I would write it like this:

     from itertools import izip, count

     def cmpSeq(seq1, seq2):
          """
          find first index at which two sequences differ
          """
          if seq1 == seq2:
              print "Sequences are identical, and of length %d" % len(seq1)
              return None

          for i, ca, cb in izip(count(), seq1, seq2):
              if ca != cb:
                  print "sequences first differ at index", index
                  print "seq1[%d] = %s" % (index, seq1[index])
                  print "seq2[%d] = %s" % (index, seq2[index])
                  break
          else:
              print "sequences are identical thru end of shorter sequence at index", i


Javier



More information about the Tutor mailing list