I want to know if there is any way to differentiate a whole number from any other output only using maths, eg if you have the number 5 I would like to convert that into the number 0 using equations, however, the number 5.4342 would output the number -1
(What i am trying to do is very hard to put into words so i can clear up any questions)
Use type() to check if it's an integer or a float. In python, it's usually best to do it this way.
Mathematically, if you allow integer divisions, you could use this:
def isInt(n): return 0**(n-n//1)-1
isInt(5) # 0
isInt(5.4342) # -1.0
If can also work with a modulo:
def isInt(n): return 0**(n%1)-1
Related
Is there a built-in python function to count bit flip in a binary string? The question I am trying to solve is given a binary string of arbitrary length, how can I return the number of bit flips of the string. For example, the bit flip number of '01101' is 3, and '1110011' is 2, etc.
The way I can come up with to solve this problem is to use a for loop and a counter. However, that seems too lengthy. Is there a way I can do that faster? Or is there a built-in function in python that allows me to do that directly? Thanks for the help!
There is a very fast way to do that without any explicit loops and only using Python builtins: you can convert the string to a binary number, then detect all the bit flips using a XOR-based integer tricks and then convert the integer back to a string to count the number of bit flips. Here is the code:
# Convert the binary string `s` to an integer: "01101" -> 0b01101
n = int(s, 2)
# Build a binary mask to skip the most significant bit of n: 0b01101 -> 0b01111
mask = (1 << (len(s)-1)) - 1
# Check if the ith bit of n is different from the (i+1)th bit of n using a bit-wise XOR:
# 0b01101 & 0b01111 -> 0b1101 (discard the first bit)
# 0b01101 >> 1 -> 0b0110
# 0b1101 ^ 0b0110 -> 0b1011
bitFlips = (n & mask) ^ (n >> 1)
# Convert the integer back to a string and count the bit flips: 0b1011 -> "0b1011" -> 3
flipCount = bin(bitFlips).count('1')
This trick is much faster than other methods since integer operations are very optimized compare to a loop-based interpreted codes or the ones working on iterables. Here are performance results for a string of size 1000 on my machine:
ljdyer's solution: 96 us x1.0
Karl's solution: 39 us x2.5
This solution: 4 us x24.0
If you are working with short bounded strings, then there are even faster ways to count the number of bits set in an integer.
Don't know about a built in function, but here's a one-liner:
bit_flip_count = len([x for x in range(1, len(x0)) if x0[x] != x0[x-1]])
Given a sequence of values, you can find the number of times that the value changes by grouping contiguous values and then counting the groups. There will be one more group than the number of changes (since the elements before the first change are also in a group). (Of course, for an empty sequence, this gives you a result of -1; you may want to handle this case separately.)
Grouping in Python is built-in, via the standard library itertools.groupby. This tool only considers contiguous groups, which is often a drawback (if you want to make a histogram, for example, you have to sort the data first) but in our case is exactly what we want. The overall interface of this tool is a bit complex, but in our case we can use it simply:
from itertools import groupby
def changes_in(sequence):
return len(list(groupby(sequence))) - 1
This is a very specific question, but despite a large number of online resources I cannot seem to find a function which does what I want. Assume I have an arbitrary float, say for example "2.". I want to convert the float into the following format:
'2.000000E+000'
That is to say: 8 digits before the exponential, and 3 digits (four counting the sign) after the exponential. There are a few functions which almost (but not quite) yield the desired output. Using
"%.6e" %float(2)
yields the output
'2.000000e+00'
Which permits me to specify how many digits I have to before the exponential, but not after - it always gives me two digits. The function numpy.format_float_scientific, on the other hand:
numpy.format_float_scientific(2.0000000000, exp_digits=3,precision=6)
Out[30]: '2.e+000'
permits me to specify the number of digits after the exponential, but not before. I would like to do both. Do you know how I could achieve this?
You can try with unique to False for numpy:
numpy.format_float_scientific(2.0000000000, unique=False, exp_digits=3,precision=6)
Output:
'2.000000e+000'
I want to write a function that takes in 2 values and calculates whether the division is an integer, but i am having trouble handling the case when say 5.1 and 0.1 is entered as the result is not 51 as expected.
def(a,b):
return a/b.is_integer()
An alternative version i tried, to convert the values to decimals as well but still have the same issue.:
def(a,b):
return Decimal(a)%Decimal(b) == 0
This a problem of arithmetic precision in python (and other languages that use floating-point in computers), you could do one of two things in those case, the first case is assuming that it will be some limits and deal with it, or the second case is to use a specialized library that tries to deal with those problems.
A good compromise could be to use limited precision in your divisor, for example you could assume that any divisor b in your function could be a number with max 3 digits of precision, from like 5.999 or 0.001, then you could first multiply dividend a and divisor b by 1000 and try to do the division there
Let's rewrite your function (and assume you are using Python 3)
def is_division_integer(a, b):
a = 1000*a
b = 1000*b
d = a/b
if type(d) == int:
return True
return d.is_integer()
The other alternative could be using a library like numpy, mpmath or others but probably you don't need them for general simple cases.
I'm trying to write a program that can determine an integer A as such as there are no prime numbers between A and A+100 ...
Unfortunately, with my mediocre Python skills, this is all I managed to write:
for A in range (1,1000000):
if is_prime(n)==False in range (A,A+3):
print(A)
As you can see, I first tried to get it working with an interval of only 2 consecutive composite numbers. I also used a (working) function "is_prime" that determines if an integer is prime or not.
You can start yelling at me for my incompetence !
I recommend a sieve-style operation for performance reasons. Create a list of X numbers, mark all primes, then look for an unbroken sequence of composite numbers.
You're in the right ballpark. Just gotta finish the rest of the list comprehension.
for A in range (1,1000000):
if all(is_prime(n)==False for n in range (A,A+3)):
print(A)
style nitpick: not is_prime(n) would be preferable to is_prime(n) == False.
It prints diga and digb but doesnt work with c! Any help? It's supposed to be a Denary to Binary converter but only 1-64, once i've cracked the code will increase this! Thanks so much
denaryno=int(input("Write a number from 1-64 "))
if 64%denaryno > 0:
diga=0
remaindera=(64%denaryno)
if 32/denaryno<1:
digb=1
remainderb=(denaryno%32)
else:
digb =0
if 16/remainderb<1:
digc=1
remainderc=(denaryno%16)
else:
digc=0
if 8/remainderc<1:
digd=1
remainderd=(denaryno%8)
else:
digd=0
if 4/remainderd<1:
dige=1
remaindere=(denary%4)
else:
dige=0
if 2/remaindere<1:
digf=1
remainderf=(denary%2)
else:
digf=0
if 1/remainderf<1:
digg=1
remainderg=(denary%1)
else:
digg=0
print (str(diga)+str(digb))
You only set digc in one of the top if/else statement. If 32/denaryno<1 is True, you don't set digc at all.
Set digc at the top of the function (to 0 or whatever else you want it to be). This applies to all the digit variables, digd, dige, etc.
What you really should do, instead, is use a list of digits, and append either a 0 or a 1 to that list every time you divide the number by a factor.
You may want to take a look at the divmod() function; it returns both the quotient and the remainder. You could also do with some looping here to slash the number of if statements needed here:
number = int(input("Write a number from 1-64 "))
digits = []
factor = 64
while number:
quotient, number = divmod(number, factor)
digits.append(quotient)
factor //= 2
print(''.join(map(str, digits)))
Wow that was a lot of work, you don't have to do all that.
def bin_convert(x, count=8):
return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
here are the functions comprising this one from easy->important
str() returns a string
range() is a way to get a list from 1 number to another. Written like this range(count-1, -1, -1) counts backwards.
"".join() is a way to take an iterable and put the pieces together.
map() is a way to take a function and apply it to an iterable.
lambda is a way to write a function in 1 line. I was being lazy and could have written another def func_name(y) and it would have worked just as well.
>> is a way to shift bits. (which I believe understanding this one is the key component to understanding your problem)