Convert integer to binary in python and compare the bits - python

How to convert a int n into binary and test each bit of the resulting binary number?
I have just got the following after a lot of googling:
def check_bit_positions(n, p1, p2):
print int(str(n),2)
However i get an error invalid literal for int() with base 2. Let me know how can i get binary form of the input number and test each bit at position p1 and p2
EDIT:
binary = '{0:b}'.format(n)
if list(binary)[p1] == list(binary)[p2]:
print "true"
else:
print "false"
The above code works now, however how can i check for postions p1 and p2 from the end of the list?

Use bin() function:
>>> bin(5)
'0b101'
or str.format:
>>> '{0:04b}'.format(5)
'0101'

Here's a quick function I wrote to check the nth bit of a number:
def check_nth_bit(num, n):
return (num>>n)&1
Basically, you bitshift the number n times to the right, which would put the nth digit in the rightmost position, and by bitwise and-ing the new number with 1 (which is all 0's except for in the rightmost position), you can check if that bit is a 1 or a 0. So, you can call this function on num with p1 and p2 and compare the results.
EDIT: This will be p1 and p2 from the end of the number (least-significant bit), not the beginning.

You can use format:
>>> format(10, 'b')
'1010'
int is used to convert a number from any base to base 10, and you're trying to use it to convert an integer to binary which is wrong.
>>> int('1010', 2)
10
>>> int('20', 2)
Traceback (most recent call last):
File "<ipython-input-3-05fc7296a37e>", line 1, in <module>
int('20', 2)
ValueError: invalid literal for int() with base 2: '20'

Related

How to print a float in 5 significant digit scientific notation in Python/numpy? [duplicate]

I have a number like 2.32432432423e25 in python that is the result of a computation.
I want to round this to 3 decimal points to get the output:
2.324e25
I have tried to use:
x = 2.32432432423e25
number_rounded = round(x, 3)
But when I print number_rounded it outputs a number with the same format as x.
How do I limit the display of x to just 4 significant digits?
You'll need to use string formatting for this:
'{:0.3e}'.format(2.32432432423e25)
The reason is that round is for specifying the number of the digits after the ones place, which is not really relevant when your numbers are O(25).
If you want to use Python's f-string syntax introduced in Python 3.6, specify the format after the variable, separated by :, e.g.:
>>> res = 2.32432432423e25
>>> f'The result is {res:.3e}'
'The result is 2.324e+25'
I was looking for an answer to this and mostly found string answers. While that is typically the best way to handle this question (because floats are always rounded to their defined precision regardless), there are situations where you'd like to round a float to a given decimal precision (plus whatever float imprecision added on) and I couldn't find a good answer. Here's what I came up with, I believe it handles all the possible cases: input of zero, input < 1, input > 1 for both positive and negative numbers:
def precision_round(number, digits=3):
power = "{:e}".format(number).split('e')[1]
return round(number, -(int(power) - digits))
Building on top of #Josh Duran nice function/idea, here is the same func that can handle up-to 2-D arrays. Maybe someone can modify this for the ndarrays.
def precision_round(numbers, digits = 3):
'''
Parameters:
-----------
numbers : scalar, 1D , or 2D array(-like)
digits: number of digits after decimal point
Returns:
--------
out : same shape as numbers
'''
import numpy as np
numbers = np.asarray(np.atleast_2d(numbers))
out_array = np.zeros(numbers.shape) # the returning array
for dim0 in range(numbers.shape[0]):
powers = [int(F"{number:e}".split('e')[1]) for number in numbers[dim0, :]]
out_array[dim0, :] = [round(number, -(int(power) - digits))
for number, power in zip(numbers[dim0, :], powers)]
# returning the original shape of the `numbers`
if out_array.shape[0] == 1 and out_array.shape[1] == 1:
out_array = out_array[0, 0]
elif out_array.shape[0] == 1:
out_array = out_array[0, :]
return out_array

How can I print decimal till N in python?

t=int(input())
for _ in range(t):
N=int(input())
a,b=stdin.readline().split()
z=int(a)/int(b)
x='{0:.Nf}'.format(z)
print(x)
here I want to print N decimal places of z, but I am not getting the desired result. Instead I get an error.
String interpolation doesn't work that way. The format-specifier part of the string needs to be a part of the string already -- you can't interpolate into it as part of the format function that uses it.
To do what you want, you need to create the string that will format the fraction first, and then use that.
# e.g. N = 5
fstr = "{{0:.{0}f}}".format(N)
print(fstr)
The double-braces are to "escape" the braces, i.e. you're telling Python to use it as a literal { or } instead of interpreting it as a format-string.
This gives you
{0:.5f}
Then, use fstr
# e.g. z = 22 / 7
x = fstr.format(z)
print(x)
Which gives
3.14286
Or, you can use the round() function to round z to N decimal places and then print that
You're trying to parametrically control the width of your formatting string using N, which is type int, in the middle of a string. Look at this piece of code, that hard-codes the value to 3:
thisFloat = 0.12345678
'{0:.3f}'.format(thisFloat)
and compare with this additional code:
N = 3
fstring = '{0:.'+str(N)+'f}'
fstring.format(thisFloat)
Both produce the same output because in the second example, the int N has been cast to a string.
I think here, you would have to use the round() function.
t = int(input())
for _ in range(t):
N = int(input())
a, b = stdin.readline().split()
print(round(int(a)/int(b), N))

how to take an integer and use a fraction on it

def main():
name=input("Enter your name: ") #just write our name nothin important
print (name, "is Swag")
value1=int(input("enter a value: ")) #takes in the number without doubt
print(value1)
value2=float(int("Enter a fraction: ")) #heres our problem but what?
print(value2)
main()
just a simple program I am playing about with but It shows this error since you all might want to know:
I write for example 1/2 an this shows
Traceback (most recent call last):
File "C:\Users\waliu\Documents\Waliur Uni stuff\Information
systems\Python Programs\Samples\apparently fractions.py", line 8, in
<module>
main()
File "C:\Users\waliu\Documents\Waliur Uni stuff\Information
systems\Python Programs\Samples\apparently fractions.py", line 6, in main
value2=float(input("Enter a fraction: "))
ValueError: could not convert string to float: '1/2'
There's a fractions module in the standard library. It can parse a string containing a representation of a fraction.
from fractions import Fraction
s = input("Enter a fraction: ")
val = Fraction(s)
print(val, float(val))
demo
Enter a fraction: 3/8
3/8 0.375
Note that the string can't contain internal spaces, but it can have spaces before or after the data.
If you want to do calculations with fractions it's a good idea to not convert them to floats, since that loses precision. And since Fraction objects use Python integers for the numerator & denominator there's no limit to how accurate they can be (apart from RAM limitations). Here's a short demo:
a = Fraction('2/3')
b = Fraction(3, 4)
c = a**2 + b**2
print(c)
print(c**10)
output
145/144
4108469075197275390625/3833759992447475122176
python won't evaluate fractions, unless you're using eval (which is unsafe so I cannot recommend it). There are other expression evaluators like simpleeval, but in your case, if you're sure that a fraction is entered you could just split, convert to integer and divide:
>>> fraction = "1 / 2" # input("enter a fraction")
>>> f = [int(x) for x in fraction.split("/")]
>>> f[0]/f[1]
0.5
>>>
you could handle non-fractions by just checking len(f)==2, otherwise it's either a simple integer (if len(f)==1), or an error (if > 2).
one-liner using operator.truediv & passing the args directly:
operator.truediv(*(int(x) for x in fraction.split("/")))
(no syntax check possible here obviously)

Binary to Decimal (mathematics way)

If there is an binary number:10011100
It is 156 in decimal.
I want to use mathematics way to make binary to decimal.
For example:
binary: 10011100
the first number is 1: 2**7
the forth number is 1: 2**4
the fifth number is 1: 2**3
the sixth number is 1: 2**2
then 2**7+2**4+2**3+2**2 = 156
I think, I need to use string.find() method.
>>> my_str = '10011100'
>>> my_str = my_str[::-1]
>>> print(my_str)
00111001
>>> my_str.find('1')
2
>>>
I just can find the first '1'.
How to find all the index of '1'?
Why do you want to retrieve the indexes? You can simply iterate over the bits like this:
num = sum(2**i for i, bit in enumerate(my_str) if bit == '1')
Anyway, you can get the indexes like this if you prefer two separate steps:
indexes = [i for i, bit in enumerate(my_str) if bit == '1']
num = sum(2**i for i in indexes)
You may also check the built-in int() function that takes a base argument:
int(x[, base]) -> integer
In [1]: my_str = '10011100'
In [2]: int(my_str,2)
Out[2]: 156
Binary Number:
If you are considering why binary number has a base 2 always well the answer is a binary number is expressed in the base-2 because it uses only two symbols: typically "0" (zero) and "1" (one). eg 10011100 (only "zero" and "one" used)
If there is an binary number:10011100 It is 156 in decimal.
The Binary number here is 10011100 it always has a base 2 even if it is not written 10011100 is same as 10011100 base 2
Convert Binary to Decimal
We start from the most right number and move toward left
Multi the binary number with 2 that is the base and the power(^) keeps increasing by 1
(0*2^0)+(0*2^1)+(1*2^2)+(1*2^3)+(1*2^4)+(0*2^5)+(0*2^6)+(1*2^7)
=156
If you want to under stand more clearly here is a link
[https://www.mathwarehouse.com/non-decimal-bases/convert-binary-to-decimal.php?ref=driverlayer.com][1]

I don't understand what's going on in my return statements

I need help understanding whats going on in the function, especially the return statements. I know what the return statements do but not how they do it. I know that they format the string but I just don't understand how its being done. It would help if you guys take it step by step.
def intF(n, d, l=40):
s=str(n*10**l / d)
if len(s) < l:
return '0.{:0>{width}}'.format(s,width=l)
if len(s) > l:
return s[0:len(s)-l]+'.'+s[len(s)-l:]
return '0.'+s
Here's a line-by-line breakdown:
def intF(n, d, l=40):
Pretty obvious. n is a number, d is another number (the divisor) and l is the number of digits to print after the decimal point.
s=str(n*10**l / d)
This does something a bit unusual. Rather than relying on floating point arithmetic, this multiplies n by 10 ** l, i.e. by a 1 followed by l digits. That way the final result won't have any floating point error -- assuming d is always an integer. (But of course any remaining digits get truncated. Also, replace / with // in Python 3 to get the same behavior.)
At this point, s will be a string representation of a whole number -- again assuming d is an integer -- but it will have the same digits as the result of float(n) / d. So now we just have to insert the decimal point in the right place.
if len(s) < l:
return '0.{:0>{width}}'.format(s,width=l)
If the length of s is less than l, then we need to pad it and prepend a 0.. That's what this does. The {:0>{width}} field says to create a zero-padded field of width width, and insert a value into it on the right (>) side. Then s is passed in via format, and we have our result.
if len(s) > l:
return s[0:len(s)-l]+'.'+s[len(s)-l:]
If the length of a is greater than l, then we need to insert the decimal point in the correct spot. That's what this does. It removes the trailing l digits from s, appends a ., and then appends the remaining l digits.
return '0.'+s
The final possibility is that s is exactly l digits long. In that case, we don't need to do any padding; we can just prepend a 0 and a decimal point.
As a final note: if you pass anything but integers to this function, it will not work as expected. Consider this:
>>> intF(10, 10.1, 10)
'990.0990099.01'
Or this:
>>> intF(10.1, 10, 10)
'101.00000000.0'
The line s=str(n*10**l / d) converts the ratio n/d to an integer by multiplying it by 10**l to get l digits to the right of the decimal point.
After that it tests the number of digits in the result. If it's less than 'l', the ratio was less than 0.1. If it's greater than 'l', it's greater than or equal to 1.0. If it's in between, the ratio was between 0.1 and 1.0.
The expression '0.{:0>{width}}'.format(s,width=l) is a fancy way of putting a leading '0.' in front and filling in the necessary number of '0's to get it to l decimal points.
The expression s[0:len(s)-l]+'.'+s[len(s)-l:] just puts a decimal point in the middle of the string at the proper position.
You're creating a string based on the variables you've passed to the function. It then checks the length of the string, and if it's less than 1, returns with it's format, greater than 1, it's format, and as a fallback default for when it's 1 char in length, another format is returned.

Categories

Resources