Decimal to Binary and consecutive 1's count - python-3.x

So, I was given this question where have to enter two numbers and find the binary representation of all the numbers between them and we have to check if there is consecutive 1's in the binary form, if present then skip otherwise print it.
I have tried this much I have created the required list of binary representation but now how to iterate over every number and check for that 1's possibility??
n = int(input())
m = int(input())
str=[]
for i in range(n+1,m):
x = bin(i)
str.append(x)
print(str)
Here is the output
3
7
['0b100', '0b101', '0b110']

So something like this:
def solve(a, b):
result = []
for x in range(a, b):
binary_str = bin(x)
if '11' not in binary_str:
result.append(binary_str)
return result
a = int(input())
b = int(input())
r = solve(a, b)
print(r) # ['0b100', '0b101']
Note that bin does not return binary but a binary representation (i.e. a string).
A slightly less efficient (because bin() is called twice) solution but shorter:
def solve(a, b):
return [bin(x) for x in range(a, b) if '11' not in bin(x)]
print(*solve(int(input()), int(input()))) # 0b100 0b101

Related

Python 3, any better/cleaner way to write these functions that use for loops?

I'm trying to write code in the most simplest and cleanest way possible. I've found a few ways to shorten and simplify my code through functions that I've never seen before or through using other methods. I'd like to expand my knowledge on writing code using various (but simple) methods, and also expand my function 'vocabulary'.
Here are the functions:
1. Perfect number:
If a number's divisors' sum is equal to the number itself, it is a perfect number. We dont count the number itself as a divisor. E.g. 6's divisors are 1, 2, 3. The sum of the divisors is 6. Therefore 6 is a perfect number.
def perfect_number(num):
if type(num) != int or num < 0:
return None
divisors = []
total = 0
for x in range(num):
if num % (x+1) == 0:
if num != x+1:
divisors += [x+1]
for x in divisors:
total += x
if total == num:
return True
return False
2. Pattern:
A function that takes a positive integer and prints a pattern as follows:
pattern(1): '#-'
pattern(2): '#-#--'
pattern(5): '#-#--#---#----#-----'
def pattern(num):
if type(num) != int or num < 0:
return None
output = ''
for x in range(num):
output += '#'+('-'*(x+1))
return output
3. Reversed Numbers:
A function that takes 2 integers. It goes through every number in the range between those 2 numbers, if one of those numbers is a palindrome (the same thing backwards e.g. 151 is a 'palindrome'), it will increase a variable by 1. That variable is then returned.
invert_number(num) returns the opposite of num as an integer.
def reversed_numbers(low, high):
output = 0
for x in range(low,high+1):
if invert_number(x) == x:
output += 1
return output
It is assumed that low is lower than high.
If I broke a rule or if this doesnt fit here, please tell me where I can post it/how I can improve. Thanks :)

power (a, n) in PYTHON

POwer in Python. How to write code to display a ^ n using funсtion?
why doesn't this code working?
a = int(input())
n = int(input())
def power(a, n):
for i in range (n):
a=1
a *= n
print(power (a, n))
Few errors:
Changing a will lose your power parameter, use result (or something else).
Move setting result = 1 outside your loop to do so once.
Multiply by a not by n.
Use return to return a value from the function
def power(a, n):
result = 1 # 1 + 2
for _ in range (n):
result *= a # 3
return result # 4
Style notes:
Setting/mutating a parameter is considered bad practice (unless explicitly needed), even if it is immutable as is here.
If you're not going to use the loop variable, you can let the reader know by using the conventional _ to indicate it (_ is a legal variable name, but it is conventional to use it when not needing the variable).
Tip: you can simple use a**n
It doesn't work because your function doesn't return the end value. Add return a to the end of the function.
ALSO:
That is not how a to the power of n is is calculated.
A proper solution:
def power(a,n):
pow_a = a
if n is 0:
return 1
for _ in range(n-1): # Substracting 1 from the input variable n
pow_a *= a # because n==2 means a*a already.
return pow_a
and if you want to be really cool, recursion is the way:
def power_recursive(a,n):
if n is 0:
return 1
elif n is 1:
return a
else:
a *= power_recursive(a,n-1)
return a

Memory Error in Python Primality Testing program

def repeated(m, result, a, s, d):
check = True
r = 0
while r <= s - 1:
if result == m - 1:
check = False
return check
result = (result ** 2) % m
r = r + 1
return check
I need to write a primality testing python program to test very large numbers, like at least 100-digit numbers. The code above is part of the code for Miller Rabin deterministic primality test for repeated squaring. It works really slow for large numbers. How can I speed it up? It is for a project. Thanks!
your problem is probably the (result ** 2) % m, use the 3 argument version of pow that do the same but more efficiently because the algorithm use is the Modular exponentiation and that is much better than first doing x**n and then calculate its modulo. this way you are guaranty to never have a number bigger than m while if you do (x**n) % m you can have that x**n is very much bigger than m that may be the cause your problems
Also no need for the check variable and you don't use a.
Also as you go from 0 to s-1, better use range
def repeated(m, result, s, d):
for r in range(s):
if result == m - 1:
return False
result = pow(result, 2, m )
return True
Now for this part of the test
if
you need a, d, s, and n this is how I would do it
def mr_check(n,a,s,d):
result = pow(a,d,n)
if result == 1 :
return False
for r in range(s):
result = pow(result,2,n)
if result == n-1:
return False
return True

k way merge sort divide and conquer

from math import ceil
def merge(all_lst):
sorted_lst = []
while all_lst:
min_value,index = all_lst[0][0],0
for lst in all_lst:
if lst[0]<min_value:
min_value = lst[0]
index = all_lst.index(lst)
sorted_lst.append(min_value)
all_lst[index].pop(0)
if not all_lst[index]:
all_lst.remove(all_lst[index])
return sorted_lst
def merge_sort(lst, k):
def split(lst):
split_lst = []
j = ceil(len(lst)/k) if len(lst)>=k else 1
for i in range(0,len(lst),j):
split_lst.append(lst[i:i+j])
return split_lst
lst=split(lst)
if len(lst[0])==1:
return lst
else:
for i in range(len(lst)):
lst[i]=merge(merge_sort(lst[i],k))
return merge(lst)
Above is my code for k-way merge sort. Basically what it does is split the list into k smaller list by calling the split function until each sublist in the list is a single element. Then the list containing sublists will be merged into one single list.
My code works fine when splitting is done twice. (eg.[3,6,8,5,2,1,4,7] -> [3,6,8],[5,2,1],[4,7] -> [3],[6],[8],[5],[2],[1],[4],[7]). But when the splitting is done more than twice, (eg,[3,6,8,5,2,1,4,7] -> [3,6,8,5],[2,1,4,7] -> [3,6],[8,5],[2,1],[4,7] -> [3],[6],[8],[5],[2],[1],[4],[7]), the code will fail. Can anyone help find me find out what goes wrong in my code? Thanks in advance.
I believe the problem you're having is that merge_sort sometimes returns a flattened list and other times returns a list of lists. You should probably return a flat list in all cases. There's some other cruft: You don't need split to be its own function, since you only call it the one time.
Here's a greatly simplified version of your code:
def merge_sort(lst, k):
if len(lst) == 1: # simpler base case
return lst
j = ceil(len(lst)/k) # no need to check for k < len(lst) (ceil handles it)
#split and recursively sort in one step
lst = [merge_sort(lst[i:i+j], k) for i in range(0, len(lst), j)]
return merge(lst) # always return a merged list (never a list of lists)

python3: How to get logical complement (negation) of a binary number, eg. '010' => '101'?

Maybe I'm missing something but I can't find a straightforward way to accomplish this simple task. When I go to negate a binary number through the "~" operator it returns a negative number due to the two's complement:
>>> bin(~0b100010) # this won't return '0b011101'
'-0b100011'
What about if I just want to switch 0s into 1s and vice-versa, like in classic logical complement?
>>> bin(0b111111 ^ 0b100010)
'0b11101'
>>>
YOU's answer as a function:
def complement(n):
size = len(format(n, 'b'))
comp = n ^ ((1 << size) - 1)
return '0b{0:0{1}b}'.format(comp, size)
>>> complement(0b100010)
'0b011101'
I made it preserve the bit length of the original. The int constructor doesn't care about the leading zeros:
>>> complement(0b1111111100000000)
'0b0000000011111111'
>> int(complement(0b1111111100000000), 2)
255
Ultra nasty:
>>> '0b' + ''.join('10'[int(x)] for x in format(0b100010,'b')).lstrip('0')
'0b11101'
Here's another couple of functions that returns the complement of a number I came out with.
A one-liner:
def complement(c):
return c ^ int('1'*len(format(c, 'b')), 2)
A more mathematical way:
def complement(c):
n=0
for b in format(c, 'b'): n=n<<1|int(b)^1
return n
Moreover, one-linerizing this last one with functools (such baroque):
def complement(c):
return functools.reduce( lambda x,y: x<<1|y, [ int(b)^1 for b in format(c, 'b') ])
Finally, a uselessly nerdish variant of the first one that uses math.log to count the binary digits:
def complement(c):
c ^ int('1' * math.floor(math.log((c|1)<<1, 2)), 2)
Another function more a 'Hack' for complementing a Integer. You can use the same logic for complementing binary. Wonder why I did not come across python external libs that can do same. The next ver of Python should take care of this in built-ins
def complement(x):
b = bin(x)[2:]
c= []
for num in b:
if num == '1': c.append('0')
elif num == '0': c.append('1')
cat = ''.join(c)
res = int(cat, 2)
return print(res)

Resources