2

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

2
  • print out integer_list and t to confirm your code actually does what you intended Commented Jul 26, 2021 at 5:35
  • Yes, I tried that. In fact the first thing I did was to ensure that the integer_list and t are right. The values are correct. When I give 2 and 1 2, the integer_list is which is a map object, after converting to list the value is [1,2] the t which is a tuple, prints (1,2) I also tried printing hash((1,2)) and it prints -3550055125485641917 Commented Jul 26, 2021 at 9:09

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are solving a hacker rank tuple problem, use the coding language Pypy3, and the output will be correct. Use the below code

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

1 Comment

if name == 'main': n = int(input()) integer_list = map(int, input().split()) print(hash(tuple(integer_list))) i am using the same code yet it is giving wrong ans
-1

I had the same problem, so it was necessary to first make the list and then convert it to a tuple only at the time of printing.

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

3 Comments

t isn't a list in the first place (unless you are using Python 2), but an instance of the type map which tuple iterates over to create the tuple you hash.
(The only difference between your code and the code in the original question is that you passed the resulting tuple directly to hash, rather than assigning it to a name first.)
The submission does not answer the OP question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.