3 ms·
Naïve Python3 is not as fast as Numpy, but pretty elegant: def main(filename): d = open(filename, 'rb').read() result = sum(d) % 256 print(
by okso 12y ago
Naïve Python3 is not as fast as Numpy, but pretty elegant:
def main(filename):
d = open(filename, 'rb').read()
result = sum(d) % 256
print("The answer is: ", result)
- jdiez17 12y agoNote that sum(d) will generate a huge number, possibly using lots of memory and processing power. A better option would be: def main(filename): d = open(filename, 'rb').read() result = reduce(lambda i, j: (i + j) % 256, d) print("The answer is: ", result) Note how this is similar to the squaring algorithm used in cryptography: http://en.wikipedia.org/wiki/Exponentiation_by_squaring http://en.wikipedia.org/wiki/Exponentiation_by_squaring
- zokier 12y agowouldn't you need at least 2^55 byte (36 petabytes) size file to go over 64bit integer 'sum' variable? I think such limitation is far preferable to an extra modulo operation for each and every byte. Not sure though how python does its integers, so the threshold for using bignum might be lower.
- zokier 12y agowouldn't you need at least 2^55 byte (36 petabytes) size file to go over 64bit integer 'sum' variable? I think such limitation is far preferable to an extra modulo operation for each and every byte. Not sure though how python does its integers, so the threshold for using bignum might be lower.
- okso 12y agoThat approach would be very well adapted to a low-level language such as C with the risk of overflow. Python handles long integers transparently, and the overhead of managing the lambda function and additional variables in Python is probably much more time consuming than handling a long integer.