how to divide integer and take some part - python

I have a variable holding x length number, in real time I do not know x. I just want to get divide this value into two. For example;
variable holds a = 01029108219821082904444333322221111
I just want to take last 16 integers as a new number, like
b = 0 # initialization
b = doSomeOp (a)
b = 4444333322221111 # new value of b
How can I divide the integer ?

>>> a = 1029108219821082904444333322221111
>>> a % 10**16
4444333322221111
or, using string manipulation:
>>> int(str(a)[-16:])
4444333322221111
If you don't know the "length" of the number in advance, you can calculate it:
>>> import math
>>> a % 10 ** int(math.log10(a)/2)
4444333322221111
>>> int(str(a)[-int(math.log10(a)/2):])
4444333322221111
And, of course, for the "other half" of the number, it's
>>> a // 10 ** int(math.log10(a)/2) # Use a single / with Python 2
102910821982108290
EDIT:
If your actual question is "How can I divide a string in half", then it's
>>> a = "\x00*\x10\x01\x00\x13\xa2\x00#J\xfd\x15\xff\xfe\x00\x000013A200402D5DF9"
>>> half = len(a)//2
>>> front, back = a[:half], a[half:]
>>> front
'\x00*\x10\x01\x00\x13¢\x00#Jý\x15ÿþ\x00\x00'
>>> back
'0013A200402D5DF9'

One way to do this is:
b = int(str(a)[len(str(a))/2:])

I would just explot slices here by casting it to a string, taking a slice and convert it back to a number.
b = int(str(a)[-16:])

Related

Comparing two variables upto x decimal places

Let a = 1.11114
b = 1.11118
When I compare these two variables using the code below
if b <= a
I want the comparison to be done only up to 4 decimal places, such that a = b.
Can anyone help me with an efficient code?
Thank you!
To avoid rounding, you can multiply the number by power of 10 to cast to integer up to the decimal place you want to consider (to truncate the decimal part), and then divide by the same power to obtain the truncated float:
n = 4 # number of decimal digits you want to consider
a_truncated = int(a * 10**n)/10**n
See also Python setting Decimal Place range without rounding?
Possible duplicate of Truncate to three decimals in Python
Extract x digits with the power of 10^x and then divide by the same:
>>> import math
>>> def truncate(number, digits) -> float:
... stepper = 10.0 ** digits
... return math.trunc(stepper * number) / stepper
>>> a
1.11114
>>> b
1.11118
>>> truncate(a,4) == truncate(b,4)
True
Solution by #Erwin Mayer
You can look at whether their differences is close to 0 with an absolute tolerance of 1e-4 with math.isclose:
>>> import math
>>> math.isclose(a - b, 0, abs_tol=1e-4)
True
Use round() in-built function -
a = round(a,4) # 4 is no. of digits you want
b = round(b,4)
if a >= b :
... # Do stuff

How to set the number of decimal places in scientific notation?

I am working on python 2.7. I want to fix the number of decimal places in a number written in scientific notation like 1.32e6, but instead of using for example "%3f". I want to write something like:
n=3
"%.nf"
where n is the number of decimal places, but it can be changed from my application.
n = 4
print("{0:.{1}f}".format(1.987213,n))
n = 5
print("{0:.{1}f}".format(1.987213,n))
Output
1.9872
1.98721
i = 123456789
n = 3
print('{:.{n}e}'.format(i, n=n))
Output:
'1.235e+08'
You can try this,
>>> a = 10e6
>>> n = 2
>>> '%.{}f'.format(n) % a
'10000000.00'
Or cast to float,
>>> a = 10e6
>>> n = 2
>>> float('%.{}f'.format(n) % a)
10000000.0
If you want to return to scientific notation,
>>> a = 103.023232
>>> n = 3
>>> '%.{}E'.format(n) % a
'1.030E+02'
The old printf-style formatting operator supports this, though you'll probably want to use the newer format method.
>>> n = 3
>>> "%.*f" % (n, 3.14159)
'3.142'
When you use * as the precision, the value to use precedes the floating-point value in the tuple on the RHS.
Thank you every body for the answers. I tried the method of Ajay Dabas and that worked for me perfectly. This example is going to be used in a major (but easy) application. The complete code with the improved solution is:
enter code hereentrada_n= "Ingrese n:"
enter code heren= input (entrada_n)
enter code hereentrada_numero="Ingrese numero:"
enter code herenumero=input(entrada_numero)
enter code hereprint("{0:.{1}f}".format(numero,n))
enter code hereprint("{0:.{1}e}".format(numero,n))

Python 3 Removing All Decimal numbers from float but keep decimal

I wanted to create numbered bullet points.
Decided the way I wanted to do it was
Strip a float of all numbers behind the decimal, but keep the decimal.
Example:
2.0 would be 2.
3.14 would be 3.
Is there way to do it this way?
If so what would it look like?
Once again, Thanks in advance.
str(int(x)) + "."
Converting back to float would add a zero after the decimal, so it has to be left in string.
One way to do so would be to first use int to just obtain the integer part of the float. Then if you just want a number like 3. this is impossible without converting to string since 3. give 3.0. So perhaps convert the integer part to a string then concatenate a period of the form '3.'
An example:
In [1]: num = 3.14
In [2]: myint = int(num)
In [3]: myint
Out[3]: 3
In [4]: mystr = str(myint)
In [5]: mystr
Out[5]: '3'
In [6]: mystr += '.'
In [7]: mystr
Out[7]: '3.'
or in one step:
mystr = str(int(num)) + '.'
giving the output of '3.' given the input num = 3.14:
In [12]: mystr
Out[12]: '3.'

Python: How to convert a string of zeros and ones to binary [duplicate]

I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt()
255
Is there a way to do this in Python?
You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:
>>> int('11111111', 2)
255
Here is documentation for Python 2, and for Python 3.
Just type 0b11111111 in python interactive interface:
>>> 0b11111111
255
Another way to do this is by using the bitstring module:
>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255
Note that the unsigned integer (uint) is different from the signed integer (int):
>>> b.int
-1
Your question is really asking for the unsigned integer representation; this is an important distinction.
The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
If you wanna know what is happening behind the scene, then here you go.
class Binary():
def __init__(self, binNumber):
self._binNumber = binNumber
self._binNumber = self._binNumber[::-1]
self._binNumber = list(self._binNumber)
self._x = [1]
self._count = 1
self._change = 2
self._amount = 0
print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
self._number = number
for i in range (1, len (self._number)):
self._total = self._count * self._change
self._count = self._total
self._x.append(self._count)
self._deep = zip(self._number, self._x)
for self._k, self._v in self._deep:
if self._k == '1':
self._amount += self._v
return self._amount
mo = Binary('101111110')
Here's another concise way to do it not mentioned in any of the above answers:
>>> eval('0b' + '11111111')
255
Admittedly, it's probably not very fast, and it's a very very bad idea if the string is coming from something you don't have control over that could be malicious (such as user input), but for completeness' sake, it does work.
A recursive Python implementation:
def int2bin(n):
return int2bin(n >> 1) + [n & 1] if n > 1 else [1]
If you are using python3.6 or later you can use f-string to do the
conversion:
Binary to decimal:
>>> print(f'{0b1011010:#0}')
90
>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90
binary to octal hexa and etc.
>>> f'{0b1011010:#o}'
'0o132' # octal
>>> f'{0b1011010:#x}'
'0x5a' # hexadecimal
>>> f'{0b1011010:#0}'
'90' # decimal
Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal
:#0 -> converts to decimal as above example
Try changing left side of colon to have octal/hexadecimal/decimal.
For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.
def BitsToIntAFast(bits):
m,n = bits.shape
a = 2**np.arange(n)[::-1] # -1 reverses array of powers of 2 of same length as bits
return bits # a
For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'
int(bin(a), 2)
# 10
eval(bin(a))
# 10

Basic python arithmetic - division

I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 :
>>> count = friends.count()
>>> print count
1
>>> per_page = 2
>>> print per_page
2
>>> pages = math.ceil(count/per_pages)
>>> print pages
0.0
>>> pages = float(count/per_pages)
>>> print pages
0.0
What am I doing wrong, and why math.ceil gives float number instead of int ?
Python does integer division when both operands are integers, meaning that 1 / 2 is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you expect.
(I think this division behavior changes in Python 3.)
Integer division is the default of the / operator in Python < 3.0. This has behaviour that seems a little weird. It returns the dividend without a remainder.
>>> 10 / 3
3
If you're running Python 2.6+, try:
from __future__ import division
>>> 10 / 3
3.3333333333333335
If you're running a lower version of Python than this, you will need to convert at least one of the numerator or denominator to a float:
>>> 10 / float(3)
3.3333333333333335
Also, math.ceil always returns a float...
>>> import math
>>> help(math.ceil)
ceil(...)
ceil(x)
Return the ceiling of x as a float.
This is the smallest integral value >= x.
From Python documentation (math module):
math.ceil(x)
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
They're integers, so count/per_pages is zero before the functions ever get to do anything beyond that. I'm not a Python programmer really but I know that (count * 1.0) / pages will do what you want. There's probably a right way to do that however.
edit — yes see #mipadi's answer and float(x)
its because how you have it set up is performing the operation and then converting it to a float try
count = friends.count()
print count
per_page = float(2)
print per_page
pages = math.ceil(count/per_pages)
print pages
pages = count/per_pages
By converting either count or per_page to a float all of its future operations should be able to do divisions and end up with non whole numbers
>>> 10 / float(3)
3.3333333333333335
>>> #Or
>>> 10 / 3.0
3.3333333333333335
>>> #Python make any decimal number to float
>>> a = 3
>>> type(a)
<type 'int'>
>>> b = 3.0
>>> type(b)
<type 'float'>
>>>
The best solution maybe is to use from __future__ import division

Categories