Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing a tuple not matching the expected value in python

Tags:

python-3.x

I am trying to solve the below problem:

Given an integer, n , and n space-separated integers as input, create a tuple, t , of those n integers. Then compute and print the result of hash(t).

I am using python 3. My code is

if __name__ == '__main__':
    n = int(input())
    integer_list = map(int, input().split())
    t = tuple(integer_list)
    print(hash(t))

The expected output is 3713081631934410656 but I am getting -3550055125485641917. I think my code is correct. Why am i getting a different output?

If I am using Pypy3, I am getting the correct output 3713081631934410656 but not with Python 3

like image 367
Debdeep Das Avatar asked Jun 03 '26 08:06

Debdeep Das


2 Answers

Python doesn't promise that tuple hashing will produce any particular output. There is no such thing as the "correct" output for hash(some_tuple). The tuple hash implementation is free to change, and it has changed in Python 3.8.

Your assignment was likely written for a different Python version than the one you're testing on, without consideration of the fact that the tuple hash algorithm is an implementation detail.

like image 72
user2357112 supports Monica Avatar answered Jun 06 '26 06:06

user2357112 supports Monica


This worked for me

Select Python 2

if __name__ == '__main__':
    n = int(raw_input())
    integer_list = map(int, raw_input().split())
    print hash(tuple(integer_list))
like image 30
Rodrigo Yanez Avatar answered Jun 06 '26 05:06

Rodrigo Yanez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!