[Tutor] question about the an exercise in <core python programing> (including the discription about the exercise)

Joel Goldstick joel.goldstick at gmail.com
Wed Jan 4 15:54:14 CET 2012


On Wed, Jan 4, 2012 at 9:36 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 04/01/12 14:13, David Palao wrote:
>>
>> Hi,
>> some hints:
>> 1) strings are iterables
>
>
> And so are files.... ;-)
>
>> 2) help(zip)
>> 3) help(enumerate)
>
>
>>    Write a program that compare the two files given by users. If the
>>    two files' content is equal, just print "equal". Else, print the
>>    rows And column number of the first different position.
>
>
> In pseudocode you could do:
>
> f1 = open(file1)
> f2 = open(file2)
> lineNum = 1
> while True:
>   line = f1.readline()
# I would change next line to this:
     line2 = f2.readline()    # this to have a name for each line for below
     if line != line2:
>   if line != f2.readline():
>        print lineNum, " : ", line

# in here I believe you need a bit more.  You now know the lines are
not equal, but the exercise requires the line number and column number
where the two lines differ
# To do that, you need to do something similar to what Alan has shown
    for i, c in enumerate(line):      #enumerate iterates over the
characters in line, and returns the index and the character
          if line2[i] != c:                  # line2[i] is the
character in the same position on the line as c from line
              print "The file differs at line %d, column %d" % lineNum, i
>        exit
>   else:
>       lineNum += 1
> print "equal"
>
>
> But there other approaches you could use.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 


Joel Goldstick


More information about the Tutor mailing list