Skip to content

Instantly share code, notes, and snippets.

@xbns
Created December 15, 2020 17:24
Show Gist options
  • Save xbns/6eba7af077012ea8b5741f9cd1c77ade to your computer and use it in GitHub Desktop.
Save xbns/6eba7af077012ea8b5741f9cd1c77ade to your computer and use it in GitHub Desktop.
process user input #hackerrank
##
# my_array = list (map (int, input().strip().split())) [:I]
#
## driver variables to test
n = 3
my_array = ' 1 6 8 '
# 1. input() function - to get user input from STDIN
# comment the driver variable above and uncomment these 2 line if u need to test from STDIN
# n = int(input('Enter a number to denote the number of elements in your array:'))
# my_array = input('Enter your array of numbers here, space-separated:')
print('This is your original array:', my_array, type(my_array),'\n')
# 2. strip() function - to remove leading & trailing whitespaces
stripped_array = my_array.strip()
print('strip():', stripped_array, type(stripped_array),'\n') # 1 6 8 <class 'str'>
# 3. split() function - to convert the string into a list
split_array = stripped_array.split()
print('split():', split_array, type(split_array), '\n') # expected: ['1', '6', '8'] <class 'list'>
for j in range(n):
my_new_array = split_array[j]
print('This is one of our item of the original list:',my_new_array,type(my_new_array),'\n') # expected <class 'str'>
# 4. map() function - this does nothing here but only typecasting every element in our list to type 'int'
# syntax -> map(func, *iterables)
# takes 2 parameters, 1 - function to apply , 2 - data to apply to
# returns MAP OBJECT
# func = int -> we want to cast our "input" as integers, so int is the function to apply (parameter 1)
# *iterables = split_array -> our list above (iterable)
my_new_array = map(int, split_array)
print('Using map() function here to cast each of our item objects to integer',type(my_new_array),'\n') # expected "<class map> "
# 5. list() function - convert to list object
# Since our my_new_array(which contains now INTEGERS) returns a MAP OBJECT we need to typecast it to list
# so that we can traverse it
my_new_list = list(my_new_array)
print('Elements from map',my_new_list,type(my_new_list),'\n') # expected '<class 'list'>
# since we don't know the number of elements user gonna type
for i in range(n):
last_list = my_new_list[i]
print('This is one of our item of the final list:',last_list,type(last_list)) # expected '<class 'int'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment