Convert a number to binary in Python - python-3.x

Given a non-negative integer n, write a function to_binary/ToBinary which returns that number in a binary format.
This is my code but some tests don't pass.
I appreciate it if you help me fix my code:
def to_binary(n):
string = ""
if n > 2:
string = string + str(n % 2)
x = n // 2
while x >= 2:
i = x % 2
string = string + str(i)
x = x // 2
string = string + str(1)
l = len(string)
string[l::-1]
return int(string)
else:
if n == 1:
return 1
if n == 2:
return 10

Few points to note.
Changing the concatenation logic will generate the string in reverse. You won't have to reverse it in the end.
In [10]: s = ''
In [11]: for i in range(5):
...: s = s + str(i)
...:
In [12]: s
Out[12]: '01234'
In [13]: s = ''
In [14]: for i in range(5):
...: s = str(i) + s # add the existing string after i
...:
In [15]: s
Out[15]: '43210'
You don't require a different logic for numbers less than 2. You shouldn't have to hardcode anything unless you're using recursion. In which case, hardcoding is simply the base case.
You are not reversing the string at all.
s[::-1]
This does not reverse a string in-place. Strings in python are immutable. What you can do is,
s = s[::-1]
Not providing the limits in a slice syntax is the same as providing start and end values (0 and length). You don't have to explicitly write s[len(s)::-1].
Your logic is almost correct. Just remove everything and keep the while loop and the code will work.
def to_bin(x):
if x == 0:
return '0'
b = ''
while x > 0:
b = str(x%2) + b
x //= 2
return b
There are of course several ways to do this without writing code just by using the builtin features of python.

You could try the implementing the mathematical method of converting bases into Python. Every number can be expressed as the sum of the powers of a base. For binary, base 2, this would be N*2**n + ... + A*2**3 + B*2**2 + C*2**1 + D*2**0. The hardest part is finding N, but from there we can use divmod to solve for the other variables.
def get_highest_power(num, base=2):
n = 0
while True:
if base**(n+1) >= num:
break
n += 1
return n
def solve_for_coefficients(num, power, base=2):
coefficients = []
for p in range(power, -1, -1):
coef, num = divmod(num, base**p)
coefficients.append(coef)
return coefficients
leading_power = get_highest_power(1000)
coefficients = solve_for_coefficients(1000, leading_power)
In order to get the base conversion, just use something like int(''.join([str(i) for i in coefficients])). This method works for all bases less than 10, since bases after ten require letters (but then again, you could use look at the items in coefficients to get the letters).

If you just want to solve the problem "number to binary string", you could use simple python:
def to_binary(n):
return "{:b}".format(n)

Simply use bin() instead.
def to_binary(n):
return(bin(n)[2:])
to_binary(6)
'110'

Related

name 'count' is not defined in python

I have this code in python and I am trying to make a counter for the iteration of the binary search (yeah I know it is incomplete...), but I am stuck with the variable inside the function, when i try to print the variable count I get this error
name 'count' is not defined in python
can someone explain why i get this error?
import csv
def binarySearch(arr, l, r, x):
count=0
while l <= r:
mid = int(l + (r - l) / 2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
arr=[]
for row in reader:
if row ["Publication date (standardised)"] != "":
arr.append(int(row["Publication date (standardised)"])) #create list for searching
list.sort(arr) #list must be sorted to work
#print (arr)
x = 1850 #year to search
# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
found = False
if result != -1:
found = True
print(found)
print(count)
I think it's because you defined count in binarySearch but try to use it outside of the method. Try using a global variable (define it outside of binarySearch), it should work.
You can return count as well.
For example:
def myFunc():
x = 5
y = 10
return x,y
a, b = myFunc()
print(a)
print(b)
This will be:
5
10
Note that, I could have written x, y = myFunc(). These x and y are not the same as the ones inside myFunc(). The latter are local to the function.
In your code, you can return your local count variable:
return mid, count #(A)
return -1, count #(A)
And get its value by:
result, count = binarySearch(arr, 0, len(arr)-1, x) #(B)
Again, these two count variables, (A) and (B) are different variables with different scopes.
See, for instance:
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Alternatively, if a global variable, as suggested in the other answer, suits you best, you can see an example of its usage in the link.

Why is my python function not working properly when I call it recursively?

I'm doing a question from a previous Waterloo ccc competition (https://cemc.uwaterloo.ca/contests/computing/2020/ccc/juniorEF.pdf problem J5)
and my code isn't working the way I expected
Here's the sample input I'm using:
3
4
3 10 8 14
1 11 12 12
6 2 3 9
Here's my code so far
y_size = int(input())
x_size = int(input())
mat = []
"ok".split()
for i in range(y_size):
row = input().split()
mat.append(row)
pos_list = [[0, 0]]
current_num = int(mat[0][0])
a = 0
def canEscape():
global a
global mat
global pos_list
global current_num
end = y_size * x_size
if y_size -1 * x_size -1 == current_num:
return True
for i in range(y_size):
print("______")
for j in range(x_size):
v = (i + 1) * (j + 1)
print(v)
print(current_num)
if v == current_num:
print("ok")
if v == end:
print("ok")
a += 1
current_num = mat[i][j]
pos_list.append([i, j])
canEscape()
pos_list.pop(-1)
a -= 1
current_num = mat[pos_list[a][0]][pos_list[a][1]]
canEscape()
The problem I'm having is that I expect if v == current_num: to be true when I call it again. Both current_num and v are equal to 8 but the code seems to carry on with the for-in loop and break, without entering the if statement. I've made the output print v followed by current_num for every iteration of the for loop to try and figure out the problem but it seems that both variables == 8 so I really don't know what I did wrong. Did I make a silly mistake or did I structure my whole program wrong?
I'm having trouble following what your program is doing at all. This problem involves integer factoring, and I do not see where you're factoring integers. You definitely are not understanding that aspect of the problem.
When you calculate what cells you can go to you look at the value of your current cell. Lets say it is 6. 6 has the factors 1, 2, 3, and 6 because all of those numbers can be multiplied by another number to equal 6. So, you can go to the cells (1, 6), (6, 1), (2, 3), and (3, 2), because those are the pairs of numbers that can be multiplied together to equal 6.
Also, you never convert the lines of input into integers. When you append to the matrix, you are appending a list of strings that happen to be numbers. You must convert those into integers.
Anyways, this program will solve the problem. I copy and pasted the factoring algorithm from other threads:
n_rows = int(input())
n_cols = int(input())
mat = []
for i in range(n_rows):
mat.append(list(map(lambda x: int(x), input().split()))) # Convert input strings to integers.
def reduce(f, l):
# This is just needed for the factoring function
# It's not relevant to the problem
r = None
for e in l:
if r is None:
r = e
else:
r = f(r, e)
return r
def factors(n):
# An efficient function for calculating factors.
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def get_pairs(items):
for i in range(len(items) // 2):
yield (items[i],items[len(items) - 1 - i]) # use yield to save memory
if(len(items) % 2 != 0): # This is for square numbers.
n = items[len(items) // 2]
yield (n,n)
checked_numbers = set()
def isPath(r=1, c=1):
# check if the testing row or column is to large.
if r > n_rows or c > n_cols:
return False
y = r - 1
x = c - 1
n = mat[y][x]
# If we've already checked a number with a certain value we dont need to check it again.
if n in checked_numbers:
return False
checked_numbers.add(n)
# Check if we've reached the exit.
if(r == n_rows and c == n_cols):
return True
# Calculate the factors of the number, and then find all valid pairs with those factors.
pairs = get_pairs(sorted(list(factors(n))))
# Remember to check each pair with both combinations of every pair of factors.
# If any of the pairs lead to the exit then we return true.
return any([isPath(pair[0], pair[1]) or isPath(pair[1], pair[0]) for pair in pairs])
if isPath():
print("yes");
else:
print("no");
This works and it is fast. However, it if you are limited on memory and/or have a large data input size your program could easily run out of memory. I think it is likely that this will happen with some of the testing inputs but I'm not sure.. It is surely possible to write this program in a way that would use a fraction of the memory, perhaps by converting the factors function to a function that uses iterators, as well as converting the get_pairs function to somehow iterate as well.
I would imagine that this solution solves most of the testing inputs they have but will not solve the ones towards the end, because they will be very large and it will run out of memory.

iteration over a sequence with an implicit type in Python 3.6

I am trying to iterate over a sequence of numbers. I have this:
from itertools import islice, count
handle = int(input("Please enter a number:")
handler = str(handle)
parameter = []
for i in handler:
parameter.append(i)
print(parameter) #This was for debugging
revised = parameter(count(1[2])) #I'm not sure I'm using the correct syntax here, the purpose is to make revised == parameter[0] and parameter[2]
Ultimately, what I am trying to achieve is to take a sequence of numbers or two, and compare them. For instance, if i[0] == i[1] + i [2] I want to return True, or for that matter if i[0] == i[1] - i[2]. I want the program to iterate over the entire sequence, checking for these types of associations, for instance, 23156 would == true because 2*3 = 6, 2+3 = 5, 5+1 = 6, 2+3+1=6; etc. It's strictly for my own purposes, just trying to make a toy.
When I utilize
revised = parameter(count(1[2])
I am getting an error that says builtins. TYPEERROR, type int is not subscriptable but I explicitly turned the integer input into a string.
Albeit unclear, what you have attempted to describe is hard to explain. It appears to be akin to a Running Total but with restrictions and of various operations, i.e. addition, subtraction and products.
Restrictions
The first two numbers are seeds
The following numbers must accumulate by some operation
The accumulations must progress contiguously
Code
import operator as op
import itertools as it
def accumulate(vals):
"""Return a set of results from prior, observed operations."""
adds = set(it.accumulate(vals)) # i[0] == i[1] + i[2]
muls = set(it.accumulate(vals, op.mul)) # i[0] == i[1] * i[2]
subs = {-x for x in it.accumulate(vals, func=op.sub)} # i[0] == i[1] - i[2]
#print(adds, muls, subs)
return adds | muls | subs
def rolling_acc(vals):
"""Return accumulations by sweeping all contiguous, windowed values."""
seen = set()
for i, _ in enumerate(vals):
window = vals[i:]
if len(window) >= 3:
seen |= accumulate(window)
return seen
def is_operable(vals):
"""Return `True` if rolling operations on contiguous elements will be seen."""
s = str(vals)
nums = [int(x) for x in s]
ahead = nums[2:]
accums = rolling_acc(nums)
#print(ahead, accums)
return len(set(ahead) & accums) == len(ahead)
Tests
assert is_operable(23156) == True
assert is_operable(21365) == False # {2,3} non-contiguous
assert is_operable(2136) == True
assert is_operable(11125) == True

'list index out of range' in while loop designed to return two values from list that adds to a specific sum

Line 11 produces the error. Stepping through the code doesn't reveal a problem?
The code just points at from left and right ends of list, moving pointers toward per iteration until a target sum is found or not! Doesn't look like the loops can step on itself but seems to anyway.
def twoSum(num_array, sum):
'''1.twoSum
Given an array of integers, return indices of the two numbers that
add up to a specific target.
'''
array = sorted(num_array)
l = array[0]
r = array[len(array)-1]
indx_Dict = dict(enumerate(array))
while (l < r) :
if (array[l] + array[r]) == sum:
return [indx_Dict[l], indx_Dict[r]]
elif array[l] + array[r] < sum:
l += 1
else:
r -= 1
num_array1 = [2, 7, 11, 15,1,0]
target1 = 9
twoSum(num_array1, target1)
that is what i changed:
array[len(array)-1] -> len(array)-1 (that's what caused your IndexError)
indx_Dict: i changed it such that indx_Dict[sorted_index] = original_index
sum -> sum_: sum is a built-in. it is never a good idea to use one of those as variable name! (yes, the new name could be better)
this is the final code:
def two_sum(num_array, sum_):
'''1.twoSum
Given an array of integers, return indices of the two numbers that
add up to a specific target.
'''
array = sorted(num_array)
l = 0
r = len(array)-1
indx_Dict = {array.index(val): index for index, val in enumerate(num_array)} ##
while (l < r) :
if (array[l] + array[r]) == sum_:
return [indx_Dict[l], indx_Dict[r]]
elif array[l] + array[r] < sum_:
l += 1
else:
r -= 1
here is a discussion about this problem:
Find 2 numbers in an unsorted array equal to a given sum (which you seem to be aware of - looks like what you are trying to do). this is a python version of just that:
def two_sum(lst, total):
sorted_lst = sorted(lst)
n = len(lst)
for i, val0 in enumerate(sorted_lst):
for j in range(n-1, i, -1):
val1 = sorted_lst[j]
s = val0 + val1
if s < total:
break
if s == total:
return sorted((lst.index(val0), lst.index(val1)))
return None
this version is based on looping over the indices i and j.
now here is a version that i feel is more pythonic (but maybe a little bit harder to understand; but it does the exact same as the one above). it ignores the index j completely as it is not really needed:
from itertools import islice
def two_sum(lst, total):
n = len(lst)
sorted_lst = sorted(lst)
for i, val0 in enumerate(sorted_lst):
for val1 in islice(reversed(sorted_lst), n-i):
s = val0 + val1
if s < total:
break
if s == total:
return sorted((lst.index(val0), lst.index(val1)))
return None
aaaaand just for the fun of it: whenever there is a sorted list in play i feel the need to use the bisect module. (a very rudimentary benchmark showed that this may perform better for n > 10'000'000; n being the length of the list. so maybe not worth it for all practical purposes...)
def two_sum_binary(lst, total):
n = len(lst)
sorted_lst = sorted(lst)
for i, val0 in enumerate(sorted_lst):
# binary search in sorted_lst[i:]
j = bisect_left(sorted_lst, total-val0, lo=i)
if j >= n:
continue
val1 = sorted_lst[j]
if val0 + val1 == total:
return sorted((lst.index(val0), lst.index(val1)))
else:
continue
return None
for (a bit more) completeness: there is a dictionary based approach:
def two_sum_dict(lst, total):
dct = {val: index for index, val in enumerate(lst)}
for i, val in enumerate(lst):
try:
return sorted((i, dct[total-val]))
except KeyError:
pass
return None
i hope the code serves as its own explanation...
l and r are not your indices, but values from your array.
Say you have an array: [21,22,23,23]. l is 21, r is 23; therefore, calling array[21] is out of bounds.
Additionally, you would have a problem with your indx_Dict. You call enumerate on it, which returns [(0,21),...(3,23)]. Calling dict gives you {0:21,1:22,2:23,3:23}. There is no key equivalent to 21 or 23, which will also give you an error.
What you could try is:
def twoSum(num_array, asum):
'''1.twoSum
Given an array of integers, return indices of the two numbers that
add up to a specific target.
'''
array = sorted(num_array)
l = 0
r = len(array)-1
while (l < len(array)-1) :
while (r > l):
if (array[l] + array[r]) == asum:
return [num_array.index(array[l]),\
num_array.index(array[r])]
r -= 1
r = len(array)-1
l += 1
num_array1 = [2, 7, 11, 15,1,0]
target1 = 9
twoSum(num_array1, target1)
This way, your l and r are both indices of the sorted array. It goes through every possible combination of values from the array, and returns when it either has found the sum or gone through everything. It then returns the index of the original num_array that contains the correct values.
Also, as #hiro-protagonist said, sum is a built-in function in Python already, so it should be changed to something else (asum in my example).

Printing on the same line different Permuations of a value

Hey guys so here is my question. I have written code that sums two prime numbers and prints the values less than or equal to 100 and even. How do I write it so that every combination of the number prints on the same line
like so
100 = 3 + 97 = 11 + 89
def isPrime(n):
limit = int(n ** 0.5) +1
for divisor in range (2, limit):
if (n % divisor == 0):
return False
return True
def main():
a = 0
b = 0
for n in range (4, 101):
if (n % 2 == 0):
for a in range (1, n + 1):
if isPrime(a):
for b in range (1, n + 1):
if isPrime(b):
if n == (a + b):
print ( n, "=", a, "+", b)
main()
any ideas?
I don't know too much about strings yet, but I was thinking we could set the string as n == a + b and some how repeat on the same line where n == n print the a + b statement or idk haha
One way to do this is to accumulate a and b pairs in some collection, then print a line containing all the pairs. Here's an example with some comments explaining whats going on and general Python tips:
def main():
for n in range (4, 101, 2): # range() can have third argument -> step
accumulator = []
for a in filter(isPrime, range(1, n + 1)): # filter() is useful if you want to skip some values
for b in filter(isPrime, range (1, n + 1)):
if n == (a + b):
accumulator.append((a,b)) # We accumulate instead of printing
str_accumulator = ["{} + {}".format(i[0], i[1]) for i in accumulator]
joined_accumulator = " = ".join(str_accumulator)
print("{} = {}".format(n, joined_accumulator))
Now, some explanation:
range(4, 101, 2) - as said in comment, it has an optional third argument. Some examples and explanations on how to use range in documentation.
filter() - Very useful generic iterator constructor. You pass a function that returns True/False, a collection, and you receive an iterator that spits out only those elements from the collection that are accepted by the function. See documentation.
str.format - For me, format is the best way to paste values into strings. It has PLENTY options and is very versatile. You should read the whole documentation here.
str.join - When you have a collection of string, and you want to make one string of them, join is what you want. It's much faster than str + str operation, and also you don't have to care if there is one or many elements in the collection. See documentation.

Resources