Tuples

Received an email from HackerRank to solve a Tuples challenge:  https://www.hackerrank.com/challenges/python-tuples?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

If interested take a look at the requirements.

After reading the requirements, using the Spyder 3.1.0 IDE I came up with a solution which did not have a need for the first line from the Sample Input. The Sample input follows:

2 <== I did not know what to do with it

1 2

Following is the initial code as found in the challenge:

if __name__ == ‘__main__’:

n = int(input())

integer_list = map(int, input().split())

It seemed to me that one had to start from the above listed code and expand from there :o(

Following is the output from my code which I had to comment out several lines before submitting it:

9999999999 <== useless input

n: 9999999999

1 2 <== useful input

val: 1

val: 2

l: [1, 2]

type(t): <class ‘tuple’>

t: (1, 2)

v: 1

v: 2

t.__hash__(): 3713081631934410656

hash(t): 3713081631934410656

hash(tuple(integer_list)): 3527539

reenter elements: 1 2 <== one line solution

hash(tuple(map(int, input().split()))): 3713081631934410656

Following is the code (before editing) that I submitted as a solution:

if __name__ == ‘__main__’:   

    # **** number of elements (what for?) ****   

    n = int(input())

print(“n:”, n)

    # **** input values ****

    integer_list = map(int, input().split())

# **** traverse integer_list map populating list ****

l = []

for val in integer_list:

print(“val:”, val)

l.append(val)

print(“l:”, l)

print()

# **** create tuple from list  ****

t = tuple(l)

print(“type(t):”, type(t))

# **** testing ****

print(“t:”, t)

for v in t:

print(“v:”, v)

print()

# **** display the hash of tuple ****

print(“t.__hash__():”, t.__hash__())

print(“hash(t):”, hash(t))

# **** one liner, but … ****

print(“hash(tuple(integer_list)):”, hash(tuple(integer_list)))

print(flush=True)

print(“reenter elements: “, end=””)

print(“hash(tuple(map(int, input().split()))):”, hash(tuple(map(int, input().split()))))

My first step was to create an empty list. Then I traversed the integer_list map extracting the contents of the map an appending them to the list.

Next a tuple (keep in mind they are immutable) was created using the contents of the list. The hash of the tuple was then displayed twice. Both results are correct.

I then prompted to reenter the values (1 2) and directly processing them to obtain the same required result.

The [edited] code passed the two test cases :o)

If you have comments or questions in any post in this blog please send me a message. I will not use your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter: @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.