What does int(n) for n mean? - python-3.x

In order to put the input into a list:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Can someone explain what does 'int(n) for n in' mean?
How do I improve this question?

The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Given your code:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Lets say you run the code provided, you get a prompt for input:
Enter numbers: 10 8 25 33
Now what happens is, Python's input() function returns a string, as documented here:
https://docs.python.org/3/library/functions.html#input
So the code has now essentially become this:
numbersList = [int(n) for n in "10 8 25 33".split()]
Now the split() function returns an array of elements from a string delimited by a given character, as strings.
https://www.pythonforbeginners.com/dictionary/python-split
So now your code becomes:
numbersList = [int(n) for n in ["10", "8", "25", "33"]]
This code is now the equivalent of:
numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
numberList.append(int(n))
The int(n) method converts the argument n from a string to an int and returns the int.
https://docs.python.org/3/library/functions.html#int

For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']
int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.

let us try to understand this list comprehension expression though a simple piece of code which means the same thing.
nums = input('Enter numbers: ') # suppose 5 1 3 6
nums = nums.split() # it turns it to ['5', '1', '3', '6']
numbersList = [] # this is list in which the expression is written
for n in nums: # this will iterate in the nums.
number = int(n) # number will be converted from '5' to 5
numbersList.append(number) # add it to the list
print(numbersList) # [5, 1, 3, 6]

Related

How to take two inputs in one line separated by space in python

So I am practicing in hacker earth and I have to take two inputs in a single line separated by space.
The below code is what I used:
x, y = [x for x in input("Enter two value: ").split()]
It is supposed to take input that looks like '2 5'
And it is returning an error:
Execution failed
ValueError : not enough values to unpack (expected 2, got 1)
Stack Trace:
Traceback (most recent call last):
File "/tmp/165461120/user_code.py", line 13, in
x, y = [x for x in input("Enter two value: ").split()]
ValueError: not enough values to unpack (expected 2, got 1)
What I think I understood is that it is giving two values as a single string. If so how do I take separate them and convert them into integers?
To take two inputs
x, y = input("Enter two value: ").split()
This should do the trick. To convert to int you can do it seprately on the both x and y.
Or better way is to use a map function
x, y = map(int, input().split())
For your case, only typecasting is remaining, so that splitted numbers becomes int. So, just you have to add
x, y = [int(x) for x in input("Enter two value: ").split()]
Alternatively, For taking 2 inputs in single line, you can use map also
x, y = map(int, input().split())
This is happening because Hacker Earth, in almost all cases, gives its input line by line.
In almost all cases, the inputs are of the form below.
1
2 3 4
5
6 7 8
This will differ on problem by problem basis and needs to be personalized for each problem.
You are getting the error not enough values to unpack because Hacker Earth is giving only a single input, and you are expecting 2. If it had been more than 2, then the error would have been too many values to unpack.
In all probability its because you are trying to input the number of test cases, which is the first input, and a single number input, in most hacker earth problems.
Process-01 : using list comprehension
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
numbers = [int(num) for num in strings if len(num)>0] # [1, 2, 3, 4, 5]
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = [ int(num) for num in input().split(' ') if len(num)>0 ]
print(numbers)
Process-02 : using filter and map function
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
strings = list(filter(lambda x :len(x)>0 ,strings))
numbers = list(map(int,strings)) # convert each string to int
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = list(map(int,filter(lambda x : len(x)>0,input().split(' '))))
print(numbers)
In [20]: a,b = raw_input().split()
12 12.2
In [21]: a = int(a)
Out[21]: 12
In [22]: b = float(b)
Out[22]: 12.2
You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners.

How to convert an integer into a roman numeral?

I'm having trouble to make an integer into roman numeral for having an ouptut of integer with square brackets (I'm pretty sure it's a list, but what I want is to have an integer) and I couldn't find solution why I'm having 'None' on 'rom' value.
I'm using python3.
roman.py
#!/usr/bin/env python3
import sys
def numToRom(number):
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
num = sys.argv[1:]
rom = numToRom(num)
print(num, " is ", rom)
$ ./roman.py 2
Old output:
['2'] is None
Desired output:
2 is II
Your problem stems from the fact that you're passing a list with a character inside to your function. And that function expects an integer (if number in range(0, 9)), so you need to convert it to the right integer.
import sys
def numToRom(number):
if type(number) is list: # If you know your number might be a list with only one str(value)
number = int(number[0])
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
That will work specifically for your use case, if number is of the form ['{some digit}]. If you want to get fancier, you could use recursion to return a list with the roman number of each number in a list, like so:
def numToRom(number):
if type(number) is list:
rom = []
for value in number:
rom.append(numToRom(int(value)))
return rom
else:
rom = ["", "I", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
if number in range(0, 9):
result = rom[number]
return result
>>> num = ['2', '3', '5']
>>> numToRom(num)
['2', '3', '5'] is ['III', 'IV', 'VI']
Note that this function works even if the values inside the input list are not characters, but normal integers.
>>> num = [2, 3, 5]
>>> rom = numToRom(num)
[2, 3, 5] is ['III', 'IV', 'VI']
pip install roman
import roman
print(roman.toRoman(int(input())))

Converting string into list of every two numbers in string

A string = 1 2 3 4
Program should return = [[1,2],[3,4]]
in python
I want the string to be converted into a list of every two element from string
You could go for something very simple such as:
s = "10 2 3 4 5 6 7 8"
l = []
i = 0
list_split_str = s.split() # splitting the string according to spaces
while i < len(s) - 1:
l.append([s[i], s[i + 1]])
i += 2
This should output:
[['10', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
You could also do something a little more complex like this in a two-liner:
list_split = s.split() # stripping spaces from the string
l = [[a, b] for a, b in zip(list_split[0::2], list_split[1::2])]
The slice here means that the first list starts at index zero and has a step of two and so is equal to [10, 3, 5, ...]. The second means it starts at index 1 and has a step of two and so is equal to [2, 4, 6, ...]. So we iterate over the first list for the values of a and the second for those of b.
zip returns a list of tuples of the elements of each list. In this case, [('10', '2'), ('3', '4'), ('5', '6'), ...]. It allows us to group the elements of the lists two by two and iterate over them as such.
This also works on lists with odd lengths.
For example, with s = "10 2 3 4 5 6 7 ", the above code would output:
[['10', '2'], ['3', '4'], ['5', '6']]
disregarding the 7 since it doesn't have a buddy.
here is the solution if the numbers exact length is divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
if len(num) % 2 == 0:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
return templist
print(every_two_number('1 2 3 4'))
you can remove the if condition and enclosed the code in try and except if you want your string to still be convert even if the number of your list is not divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
try:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
except:
pass
return templist
print(every_two_number('1 2 3 4 5'))

how do i remove comma in the list using for loop?

I have this code:
a = []
num = input('Enter numbers *Separate by using commas:')
for i in num:
a.append(i)
print(a)
and I get this:
Enter numbers *Separate by using commas:1,2,3
['1', ',', '2', ',', '3']
how do I remove the comma?..and I need to use the for loop...thanks
You can use this (by default prevents "," to enter in your array in the first place and functional for multi-digit numbers as you pointed out)-
a = []
num = input('Enter numbers *Separate by using commas:')
num = num.split(",") #splits the input string with "," delimiter
for i in num:
a.append(i)
print(a)

How to insert a String as Integer to a List in Python

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]
Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.
Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful
You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Resources