new to python, help please !!
Tim Chase
python.list at tim.thechases.com
Wed Nov 11 12:06:55 EST 2015
On 2015-11-11 08:34, Anas Belemlih wrote:
> i am a beginning programmer, i am trying to write a simple code
> to compare two character sets in 2 seperate files. ( 2 hash value
> files basically) idea is: open both files, measure the length of
> the loop on.
>
> if the length doesn't match, == files do not match
>
> if length matchs, loop while comparing each character from each
> file if they match. please tell me what i am doing wrong ? i am
> using python 2.7
>
> **********************************
> hash1= open ("file1.md5", "r")
> line1 =hash1.read()
> hash2 = open("file2.md5","r")
> line2= hash2.read()
>
> number1 = len(line1)
> number2 = len(line2)
>
> #**************************
> i=0
> s1=line1[i]
> s2=line2[i]
> count = 0
>
> if number1 != number2:
> print " hash table not the same size"
> else:
> while count < number1:
> if s1 == s2:
> print " character", line1[i]," matchs"
> i=i+1
> count=count+1
> else
> print "Hash values corrupt"
Well, the immediate answer is that you don't update s1 or s2 inside
your loop. Also, the indent on "count=count+1" is wrong. Finally,
if the hashes don't match, you don't break out of your while loop.
That said, the pythonesque way of writing this would likely look
something much more like
with open("file1.md5") as a, open("file2.md5") as b:
for s1, s2 in zip(a, b):
if s1 != s2:
print("Files differ")
You can compare the strings to get the actual offset if you want, or
check the lengths if you really want a more verbatim translation of
your code:
with open("file1.md5") as a, open("file2.md5") as b:
for s1, s2 in zip(a, b):
if len(s1) != len(s2):
print("not the same size")
else:
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 == c2:
print(" character %s matches" % c1)
else:
print(" %r and %r differ at position %i" % (s1, s2, i))
-tkc
More information about the Python-list
mailing list