I am trying to take input as list of integers. Here is my attempted code
input_binary = int(list(input("enter a binary number: "))) # taking a user input as integers
Here is the error it is throwing
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Have any idea?
You can't convert a list into an integer (at least, not with int()), which is what you're trying to do. Instead, try doing things in the other order.
Say you want a list of 5 integers:
binary = []
for _ in range(5): # do the following 5 times
inp = int(input("enter a binary number: ")) # take user input as string, convert to int
binary.append(inp) # put that int into our list
If you want to have input "123456" and output [1,2,3,4,5,6]
input_string = [int(num) for num in input("enter a binary number: ")]
print(input_string)
Result:
enter a binary number: 123456
[1, 2, 3, 4, 5, 6]
Related
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.
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]
I'm doing this python exercise where the goal is for a user to key in an integer and the function should be able to re-arrange (descending) I decided to convert the integer first to a string so I can iterate from that and the result is stored in a list. But when i try to convert it back to integer it doesn't get converted.
as shown in my code below, i tried printing the type of my variables so that I would see if its getting converted.
def conversion(nums):
int_to_str = str(nums)
list_int = []
ans = []
for x in int_to_str:
list_int.append(x)
list_int.sort(reverse=True)
ans = list_int
print (type(ans))
print(ans)
ans = ''.join(list_int)
print(type(ans))
print(ans)
str_to_int = [int(x) for x in list_int] # LIST COMPREHENSION to convert
# string back to integer type
print(type(str_to_int))
print(str_to_int)
final = ''.join(str_to_int)
print(type(final))
print(final)
enter code here
<class 'list'>
['9', '5', '4', '2', '1', '0']
<class 'str'>
954210
<class 'list'>
[9, 5, 4, 2, 1, 0]
TypeError: sequence item 0: expected str instance, int found
if I understood your question, you are receiving an input (assuming string representation of some int) and you want to convert that input to a list of integers then reverse sort and return. if that is the case:
def reverse_numeric_input(x):
try:
if type(x) != str:
x=str(x)
lst=[int(i) for i in x]
lst.sort(reverse=True)
return "".join([str(i) for i in lst])
except Exception as e:
print("%s error coverting ur input caused by: %s" % (e.__class__.__name__, str(e)))
the problem in the code you posted lies in this line final = ''.join(str_to_int) when you call join, the joined items must be cast to str() first. hope that helps.
I have a list of integers (e. g. [1, 2, 3] and want to convert them to one string (e. g. "1, 2, 3"). Later I will convert the string back into a list of integers.
Is my solution pythonic enough or is there a much easier way?
# init values
int_list = [1, 2, 3]
# list of integers to string
string = str(int_list)[1:-1]
# string to list of integers
int_list = [int(i) for i in string.split(',')]
By the way: My first approach was to do exec("int_list = [" + str + "]"). But using exec is absolutly not recommended.
Use map:
a = [1, 2, 3]
b = list(map(str, a))
c = list(map(int, b))
EDIT: if you want only one string, then
a = [1, 2, 3]
b = ",".join(map(str, a))
c = list(map(int, b.split(",")))
EDIT2: you can also use this to convert the map to a list. I don't like it too much, but it's an option:
c = [*map(int, b.split(","))]
# to string
a = [1,2,3]
s = repr(a)
print(s)
# from string
import ast
print(ast.literal_eval(s))
Unlike eval, literal_eval "can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself."
There are other threads about turning strings inside a lists into different data types. I want to turn a string that is in the form of a lists into a lists. Like this: "[5,1,4,1]" = [5,1,4,1]
I need this because I am writing a program that requires the user to input a lists
Example of problem:
>>> x = input()
[3,4,1,5]
>>> x
'[3,4,1,5]'
>>> type(x)
<class 'str'>
If you mean evaluate python objects like this:
x = eval('[3,4,1,5]');
print (x);
print(type(x) is list)
[3, 4, 1, 5]
True
Use this with caution as it can execute anything user will input. Better use a parser to get native lists. Use JSON for input and parse it.
Use eval() for your purpose. eval() is used for converting code within a string to real code:
>>> mystring = '[3, 5, 1, 2, 3]'
>>> mylist = eval(mystring)
>>> mylist
[3, 5, 1, 2, 3]
>>> mystring = '{4: "hello", 2:"bye"}'
>>> eval(mystring)[4]
'hello'
>>>
Use exec() to actually run functions:
>>> while True:
... inp = raw_input('Enter your input: ')
... exec(inp)
...
Enter your input: print 'hello'
hello
Enter your input: x = 1
Enter your input: print x
1
Enter your input: import math
Enter your input: print math.sqrt(4)
2.0
In your scenario:
>>> x = input()
[3,4,1,5]
>>> x = eval(x)
>>> x
[3, 4, 1, 5]
>>> type(x)
<type 'list'>
>>>
Thanks for your input guys, but I would prefer not to eval() because it is unsafe.
Someone actually posted the answer that allowed me to solve this but then they deleted it. I am going to reposts that answer:
values = input("Enter values as lists here")
l1 = json.loads(values)
You can use ast.literal_eval for this purpose.
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the
following Python literal structures: strings, bytes, numbers, tuples,
lists, dicts, sets, booleans, and None.
This can be used for safely evaluating strings containing Python
expressions from untrusted sources without the need to parse the
values oneself.
>>> import ast
>>> val = ast.literal_eval('[1,2,3]')
>>> val
[1, 2, 3]
Just remember to check that it's actually a list:
>>> isinstance(val, list)
True