How to take input in array in python 3 - python

I was trying to pass input into an array but it throws an error.
I already defined the value type in the array. I assigned the array with 'i' and also passed the int type value.
>>> import array as arr
>>> a = arr.array('i', [int(input())])
print(a)
Here's the error that I'm getting:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a = arr.array('i', [int(input())])
ValueError: invalid literal for int() with base 10: 'print(a)'

You're typing this into a REPL environment, so each time you type a line, it runs (more or less), so when you enter the line:
a = arr.array('i', [int(input())])
The line after that is expecting the input for input, not the next line of code. Because you then type print(a) you're passing the value "print(a)" to int, essentially:
a = arr.array('i', [int("print(a)")])
Obviously "print(a)" is not a base 10 number so int is failing because "p" is not a character in base 10 (the digits 0 to 9 are the only valid digits).
To resolve this you need to pass a value for the input before continuing with your code:
>>> import array as arr
>>> a = arr.array('i', [int(input())])
5
>>> print(a)
array('i', [5])

Related

getting space separated input in python

I am trying to get space separated inputs. while the first method works completely fine, the second method throws an error saying:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
what is wrong with the second method?
Method 1:
x = [int(j) for j in input().split()]
Method 2:
x = [j for j in int(input().split())]
Because you are using split() to a string which will return a list, then you are passing this list to int() that's why you are getting error. for changing datatype of list you need to use map() as below or first approach of your's.
Try Below code
x = [j for j in map(int,input().split())]

format value that could be number and/or string in python 3

Is there a concise way of formatting a number, that on occasion can also be a string?
The number would normally be a float, but occasionally it's also denoted as the string "n/a".
I would like to format the float with a fixed number of decimals, but print the entire string in case it is not a number.
For instance:
var=3.145623
print("This is {0:.2f}".format(var))
>>>This is 3.14
,but
var = "n/a"
print("This is {0:.2f}".format(var))
>>> File "<stdin>", line 1, in <module>
>>> ValueError: Unknown format code 'f' for object of type 'str'
I am not surprised by the ValueError, but wonder if there is a concise way around it, ideally without an explicit if-statement.
Indeed, the f format specifier only works on actual float values. You can't avoid having to special-case your n/a value.
You can format the float separately, and conditionally, then interpolate the result into the larger template:
var_formatted = format(var, '.2f') if var != 'n/a' else var
print("This is {0:4}".format(var_formatted))
If you are really averse to if, you can use exception handling too:
try:
var_formatted = format(var, '.2f')
except ValueError:
var_formatted = 'n/a'
print("This is {0:4}".format(var_formatted))
Another option would be for you to wrap the value in a class with a __format__ method:
class OptionalFloat(object):
def __init__(self, value):
self.value = value
def __format__(self, fmt):
try:
return self.value.__format__(fmt)
except ValueError:
return self.value
print("This is {0:.2f}".format(OptionalFloat(var)))
This moves the requirement to detect the type into another class method, keeping your output code a little cleaner and free of all those pesky conditionals or exception handlers:
>>> var = 3.145623
>>> print("This is {0:.2f}".format(OptionalFloat(var)))
This is 3.15
>>> var = 'n/a'
>>> print("This is {0:.2f}".format(OptionalFloat(var)))
This is n/a
Python supports not-a-number as float('nan') and it may be more useful than the string "n/a" in your code. It works with formatting and produces more sane results than a string if you use it in computations.
NaN:
>>> n = float('nan')
>>> n
nan
>>> "{0:.2f}".format(n)
'nan'
>>> n == 3
False
>>> n * 2
nan
>>> n < 5
False
String:
>>> n = 'n/a'
>>> "{0:.2f}".format(n)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
>>> n == 3
False
>>> n * 2
'n/an/a'
>>> n < 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < int()
maybe something like this
str = "{0:.2f}".format(var) if isinstance(var, float) else var
print(str)

Python list types

This is quite a weird/silly question so if anyone as a better title name, please request an edit.
I've created a function that returns the product of numbers in a list.
When testing this function, I tried lists that that included intergers and reals(floats), such as items = [1,2.0,3,4.0]
Function:
items = [1.0, 2, 3.0, 10, "a"]
def mult1(items):
total = 1
for i in items:
total = total * i
return total
print mult1(items)
This function above works with items being [1.0, 2, 3.0, 10] and the output of that particular list being 60.0.
I've studied Standard ML where you can only generally have a list of a particular type (I'm sure there's code out there that somehow makes my statement irrelevant), so intrigued to find out what would happen if I entered a string as a list item, I did, and got an error (I expected to get an error because you can't multiply a string with a number).
However, the error I received has confused me:
TypeError: can't multiply sequence by non-int of type 'float'
This error has confused me. I understand that a string cannot be multiplied, but does this also suggest that all of the items in the list are considered a float despite some looking like integers?
I thought that the error should suggest it cannot compute a type that is not a float or not an integer, but to me (probably wrong) it seems like it's suggesting that it can't multiply the list by a a type that is not an integer that is also not of type float?
To me this sounds like each element has two types, integer and float.
You're getting this error because you are (perhaps unintentionally) multiplying a sequence (list, str, tuple) by a float.
>>> a = [1, 2]
>>> a * 2
[1, 2, 1, 2]
>>> a * 2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>>
This error occurs because you can actually multiply some non-number types by ints, but not by floats. So if your product function looks something like:
def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
return prod
and your list looks like this : l = ['this string',3,2.0]
then your iterations will show the following:
>>> def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
print(prod)
return prod
>>> l = ['this string',3,2.0]
>>> product(l)
this stringthis stringthis string
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
product(l)
File "<pyshell#67>", line 4, in product
prod *= x
TypeError: can't multiply sequence by non-int of type 'float'
note that the first iteration is allowed because str*int is a valid expression (so is list*int and tup*int etc) and so prod is still valid but is a STRING, not an int or float. then when you DO try to do a str*float expression, the TypeError will occur.
You can multiply a string but only by an int, you see the error as you are trying to multiply a string by a float:
In [7]: "foo" * 2
Out[7]: 'foofoo'
In [8]: "foo" * 2.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-3128e6ce951c> in <module>()
----> 1 "foo" * 2.
TypeError: can't multiply sequence by non-int of type 'float'
In your particular case you are trying to multiply a from your list by a float:
[1.0, 2, 3.0, 10, "a"]
^
error
Total starts out an int but when you multiply an int by a float you get a float so total = total * 1.0 -> 1.0:
In [9]: 1 * 1.0
Out[9]: 1.0

Cast to int not working in Python

I'm trying to store a time value in an array, but it gives me an error every time, even when I try to cast the float into an int. Here is the portion of my code:
EndTimes = [0,0,0,0]
...
EndTimes[TakenSlots] = int(time.time() + n)
But it just gives this error:
[error] TypeError ( list indices must be integers )
[error] --- Traceback --- error source first
line: module ( function ) statement
44: main ( craftTime ) EndTimes[TakenSlots] = tempInt
I tried this code just to see what it thought the value was:
tempInt = int(time.time() + n)
print tempInt
EndTimes[TakenSlots] = tempInt
And it just outputted 1412046180 (no decimal places, which seems like it should be an int)
Does anyone know what's happening? Is it a problem with the int() or the type of array I'm using? Thanks in advance!
This occurs because the list index ( list[index] = value ) must be an integer. It is probable that TakenSlots is not an int.
>>> l = [1,2,3]
>>> l[1.3] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float

Reading in integer from stdin in Python

I have the following piece of code where I take in an integer n from stdin, convert it to binary, reverse the binary string, then convert back to integer and output it.
import sys
def reversebinary():
n = str(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()
However, I'm getting this error:
Traceback (most recent call last):
File "reversebinary.py", line 18, in <module>
reversebinary()
File "reversebinary.py", line 14, in reversebinary
bin_n = bin(n)[2:]
TypeError: 'str' object cannot be interpreted as an index
I'm unsure what the problem is.
You are passing a string to the bin() function:
>>> bin('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an index
Give it a integer instead:
>>> bin(10)
'0b1010'
by turning the raw_input() result to int():
n = int(raw_input())
Tip: you can easily reverse a string by giving it a negative slice stride:
>>> 'forward'[::-1]
'drawrof'
so you can simplify your function to:
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = bin_n[::-1]
return int(revbin, 2)
or even:
def reversebinary():
n = int(raw_input())
return int(bin(n)[:1:-1], 2)
You want to convert the input to an integer not a string - it's already a string. So this line:
n = str(raw_input())
should be something like this:
n = int(raw_input())
It is raw input, i.e. a string but you need an int:
bin_n = bin(int(n))
bin takes integer as parameter and you are putting string there, you must convert to integer:
import sys
def reversebinary():
n = int(raw_input())
bin_n = bin(n)[2:]
revbin = "".join(list(reversed(bin_n)))
return int(str(revbin),2)
reversebinary()

Categories