As others have said, 32-bit versions of numpy still support 64-bit dtypes. But if you really need to convert to int32, you can use the astype function:
>>> import numpy as np
>>> x = np.array([1,2,3], dtype=np.int64)
>>> x
array([1, 2, 3])
>>> x.dtype
dtype('int64')
>>> y = x.astype(np.int32)
>>> y
array([1, 2, 3], dtype=int32)
Answer from jterrace on Stack OverflowIf the result should be an integer, you should use operator.floordiv, i.e. a // b, not a / b 1:
from operator import add, sub, mul, floordiv, mod
op = {'+': add, '-': sub, '*': mul, '/': floordiv, '%': mod}
for i in range(int(input())):
znak, *nums = input().split()
print(opznak))
By the way, the code above does exactly the same as yours, but it's around two times shorter!
How?
- why check if
znakis equal to something with tons ofif/elsestatements, if you could put all the math operators in a dictionaryop, and get the operator you need withop[znak]? - you're on Python 3, so you can use that nice
a, *b = iterablesyntax which extracts the first item ofiterableintoaand puts other items into a listb, which looks super nice - each
op[znak]is a function that accepts two arguments, so you convertnumsto integers withmap(int, nums)and then pass them as separate arguments with the asterisk:*map(int, nums) - last, but not least, why use this C-style
whileloop index incrementing if there's the Pythonic way to do it - withrange(start, stop, [step])? - finally, you don't really need the variable
n, so you can plug it intorangeright away
Pssst, dude, feeling in need of some craziness? Take a look at how you can squeeze all this into two lines:
from operator import*
sum(0for _ in map(print,((lambda znak,*nums:{'+':add,'-':sub,'*':mul,'/':floordiv,'%':mod}znak))(*input().split())for _ in range(int(input())))))
Or only one line:
sum(0for _ in map(print,((lambda znak,*nums:{'+':lambda a,b:a+b,'-':lambda a,b:a-b,'*':lambda a,b:a*b,'/':lambda a,b:a//b,'%':lambda a,b:a%b}znak))(*input().split())for _ in range(int(input())))))
These work exactly as the first version. Now, this is just for fun, to show how powerful Python is and how messy it can be. Don't try this at home :D
1 True division vs Floor division: 1 / 10 == 0.1, but 1 // 10 == 0.
A simple solution: The idea is to split input charter into tokens preserving their orders . in our case tokens are operators and numbers so it very simple using regular expressions. [+-/*] match any of those operators or any number of digits using \d+
n = input()
import re
while n>0:
expression = input()
operator,num1,num2 = re.findall('[+-/*]|\d+',expression)
if operator == '+': print(int(num1) + int (num2))
if operator == '-': print(int(num1) - int (num2))
if operator == '*': print(int(num1) * int (num2))
if operator == '%': print(int(num1) % int (num2))
if operator == '/': print(int(num1) // int (num2))
n = n - 1
python - How to convert signed 32-bit int to unsigned 32-bit int? - Stack Overflow
[beginner] How to best convert a 64bit integer to a 32 bit float
Combine byte values to a 32bib int
Converting hex to uint32
How do you convert a list of integers to a single string in Python?
You can use the join() method combined with map() to convert each integer to a string and concatenate them.
int_list = [1, 2, 3, 4]
result = ''.join(map(str, int_list))
print(result) # Output: '1234'
What happens if you try to convert a non-numeric string to an integer in Python?
A ValueError will be raised indicating that the string is not a valid integer.
int('abc') # Raises ValueError: invalid literal for int() with base 10: 'abc'
Can you convert a set to a list in Python? How?
Yes, you can convert a set to a list using the list() function.
a_set = {1, 2, 3}
a_list = list(a_set)
print(a_list) # Output: [1, 2, 3]
Not sure if it's "nicer" or not...
import ctypes
def int32_to_uint32(i):
return ctypes.c_uint32(i).value
using numpy for example:
import numpy
result = numpy.uint32( numpy.int32(myval) )
or even on arrays,
arr = numpy.array(range(10))
result = numpy.uint32( numpy.int32(arr) )
I was trying numpy for matrix calculations and I used it to solve simultaneous eqns.
I have a matrix, `answer` with desired values shown as:
[[4.] [2.] [5.]]
I realise that the dots are because the actual values are a float, so I tried `answer.tolist()`
This gives me:
[[3.9999999999999987], [1.9999999999999996], [4.999999999999998]]
In my program, I want to convert this to an integer, however using Python's `int()` function means it becomes: 3, 1, 4
I also tried using `.astype()` to convert to an int:
answer.astype(int,casting='same_kind'))
but I get:
TypeError: Cannot cast array data from dtype('float64') to dtype('int32') according to the rule 'same_kind'
I am sure importing the ceiling/floor function from `math` would solve this, but I am aware that some results may end up being normal decimals of maybe 4dp, rather than .999999 or .111111 recurring, so rounding isn't the best option
Any advice on the best way of converting?
Please help me with data type conversion. I have binary file which I read as bytes. I am able to convert data into hex and decimal but unable to convert into unsigned int 32.
def convert(i):
return int(bin(i+2**32)[-32:])
print convert(1)
print convert(32)
print convert(100)
print convert(-1)
print type(convert(1))
outputs
00000000000000000000000000000001
00000000000000000000000000100000
00000000000000000000000001100100
11111111111111111111111111111111
<type 'long'>
bin(1)[2:].zfill(32)
'00000000000000000000000000000001'
'{:032b}'.format(n) where n is an integer. If the binary representation is greater than 32 digits it will expand as necessary:
>>> '{:032b}'.format(100)
'00000000000000000000000001100100'
>>> '{:032b}'.format(8589934591)
'111111111111111111111111111111111'
>>> '{:032b}'.format(8589934591 + 1)
'1000000000000000000000000000000000' # N.B. this is 33 digits long
You can just left or right shift integer and convert it to string for display if you need.
>>> 1<<1
2
>>> "{:032b}".format(2)
'00000000000000000000000000000010'
>>>
or if you just need a binary you can consider bin
>>> bin(4)
'0b100'