We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

- Practice
- Python
- Basic Data Types
- Tuples
- Discussions

# Tuples

# Tuples

+ 82 comments Here is how I broke this down:

- We need to read the first line of input to get it out of the way (it can be used to write a parser for the next line, but it isn't useful)

n = raw_input()

- Read in the second line -- this is just a single string ex. '1 2 3 4'

input_line = raw_input()

- Split the string by whitespace into a list

input_list = input_line.split()

- Note: This is a list of
**strings**ex. ['1', '2', '3', '4'] But we want a list of**integers**ex. [1, 2, 3, 4]- We need to convert the list elements from strings to ints

- [Simple] Option 1 (since we know the number of elements, n):

for i in xrange(n): input_list[i] = int(input_list[i])

- [Simple] Option 2 (if we are ignoring the first input line for some reason):

for i in xrange(len(input_list)): input_list[i] = int(input_list[i])

- [More Advanced] Option 3:

input_list = map(int, input_list)

- [More Advanced] Option 4 (List composition):

input_list = [int(x) for x in input_list]

Now

`input_list`

looks like this: [1, 2, 3, 4]- We need to convert our list of ints to a tuple of ints (as a list is not hashable, but a tuple is)

t = tuple(input_list)

- print the result

print hash(t)

### Other Optimizations (Not necessary for credit here):

- If the first input line == '0' then bail, there isn't anything interesting to parse
- Call strip() on the input to remove trailing and leading whitespace.

raw_input().strip()

- These commands can obviously be combined

+ 8 comments two line code

`raw_input() print hash(tuple(map(int, raw_input().strip().split(" "))))`

+ 4 comments I think I could have solved this particular problem without really needing to know how many numbers are going to be in the second line.

Let's say we only have numbers as the input:

`1 2`

`numbers = raw_input().strip().split() for i in range(len(numbers)): numbers[i] = int(numbers[i]) T = tuple(numbers) print hash(T)`

Am I missing something? Edit: I just learned that I can use map to convert all the strings in a list to integers! No need of that for loop too!

+ 1 comment why we have used map here?

+ 1 comment print(input()==0 or hash(tuple(map(int, input().split()))))

Load more conversations

Sort 792 Discussions, By:

Please Login in order to post a comment