Conversion of denary number to binary number problem (Python) - python

Im stuck on a problem where I have to write a function that converts a denary number into a binary number using the repeated division by two algorithm. Steps Include:
The number to be converted is divided by two.
The remainder from the division is the next binary digit. Digits are added to the front of the sequence.
The result is truncated so that the input to the next division by two is always an integer.
The algorithm continues until the result is 0.
Please click the link below to see what the output should be like:
https://i.stack.imgur.com/pifUO.png
def dentobi(user):
denary = user
divide = user / 2
remainder = user % 2
binary = remainder
if user != 0:
print("Denary:", denary)
print("Divide by 2:", divide)
print("Remainder:", remainder)
print("Binary:", binary)
user = int(input("Please enter a number: "))
dentobi(user)
This is what I have done so far but Im not getting anywhere.
Can someone explain how I would do this?

The Answer provided by #user2390182 is functionally correct except that it returns an empty string when num is zero. However, I have noted on several occasions that divmod() is rather slow. Here are three slightly different techniques and their performance statistics.
import time
# This is the OP's original code edited to allow for num == 0
def binaryx(num):
b = ""
while num:
num, digit = divmod(num, 2)
b = f"{digit}{b}"
return b or '0'
# This is my preferred solution
def binaryo(n):
r = []
while n > 0:
r.append('1' if n & 1 else '0')
n >>= 1
return ''.join(reversed(r)) or '0'
# This uses techniques suggested by my namesake
def binaryy(n):
r = ''
while n > 0:
r = str(n & 1) + r
n >>= 1
return r or '0'
M = 250_000
for func in [binaryx, binaryo, binaryy]:
s = time.perf_counter()
for _ in range(M):
func(987654321)
e = time.perf_counter()
print(f'{func.__name__} -> {e-s:.4f}s')
Output:
binaryx -> 1.3817s
binaryo -> 0.9861s
binaryy -> 1.6052s

One way, using divmod to divide by 2 and get the remainder in one step:
def binary(num):
b = ""
while num:
num, digit = divmod(num, 2)
b = f"{digit}{b}"
return b
binary(26)
'11010'
This assumes a positive number but can easily be extended to work for 0 and negatives.

Related

Multiplication of binaries through repeated addition

Let's say we're trying to multiply 10011 and 1101 (or in arithmetic terms, 19 x 13). We all know that this is the same as adding 10011 to itself 13 times or vice versa. Apparently, I've found a code at https://www.w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-31.php which provided a way on how to add two binary numbers. My question is, in general, if we multiply two binary numbers A and B, how are we going to iterate A to add itself B times? Obviously, in order to do that we have to convert B to decimal/integer first.
def add_binary_nums(x, y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
print(add_binary_nums('11', '1'))
You can count up to a number by starting at 0 and adding 1 until you are done. Since you already have defined a binary add, you only need to add the loop:
def binary_range(stop: str):
"""Count `stop` times"""
current = '0'
while stop != current:
yield current
current = add_binary_nums(current, '1')
This is enough to do something "n times". You can now do "a * b" as "add a to itself b times":
def binary_mul(a: str, b: str):
"""Multiplay the binary ``a`` by the binary ``b``"""
result = '0'
for _ in binary_range(b):
result = add_binary_nums(result, a)
return result
If you don't care about building a binary calculator, use Python to convert binary to integers or vice versa. int(bin_string, 2) converts a string such as "01101" to the appropriate integer, and bin(integer) converts it back to "0b01101".
For example, a binary multiplication that takes and returns strings looks like this:
def binary_mul(a: str, b: str):
return bin(int(a, 2) * int(b, 2))[:2]

How to iterate through the digits of a number without having it under the form of a string in Python?

I've seen a couple posts explaning how to iterate through the digits of a number in Python, but they all turn the number into a string before iterating through it...
For example:
n=578
print d for d in str(n)
How can I do this without the conversion into a string?
10**int(log(n, 10)) is basically 10*, such that it is the same length as n. The floor division of n by that will give us the leading digit, while the modulo % gives us the rest of the number.
from math import log
def digits(n):
if n < 0:
yield '-'
n = -1 * n
elif n == 0:
yield 0
return
xp = int(log(n, 10).real)
factor = 10**xp
while n:
yield int(n/factor)
n = n % factor
try:
xp, old_xp = int(log(n, 10).real), xp
except ValueError:
for _ in range(xp):
yield 0
return
factor = 10**xp
for _ in range(1, old_xp-xp):
yield 0
for x in digits(12345):
print(x)
prints
1
2
3
4
5
Edit: I switched to this version, which is much less readable, but more robust. This version correctly handles negative and zero values, as well as trailing and internal 0 digits.

binary to decimal using recursion,python

Need help converting binary to decimal, using recursion.
So far I have :
(2* int(s[0])) + int(s[1])
with base cases for when s==0 and s==1.
I'm not sure how to pass this recursively so that the function will pass through all 1's and 0's in input,s.
The basic idea is to pick off the last character of the string and convert that to a number, then multiply it by the appropriate power of 2. I've commented the code for you.
# we need to keep track of the current string,
# the power of two, and the total (decimal)
def placeToInt (str, pow, total):
# if the length of the string is one,
# we won't call the function anymore
if (len(str) == 1):
# return the number, 0 or 1, in the string
# times 2 raised to the current power,
# plus the already accumulated total
return int(str) * (2 ** pow) + total
else:
# grab the last digit, a 0 or 1
num = int(str[-1:])
# the representation in binary is 2 raised to the given power,
# times the number (0 or 1)
# add this to the total
total += (num * (2 ** pow))
# return, since the string has more digits
return placeToInt(str[:-1], pow + 1, total)
# test case
# appropriately returns 21
print(placeToInt("10101", 0, 0))
Now, let's go through it manually, so you understand why this works.
# n = 101 (in binary
# this can also be represented as 1*(2^2) + 0*(2^1) + 1*(2^0)
# alternatively, since there are three digits in this binary number
# 1*(2^(n-1)) + 0*(2^(n-2)) + 1*(2^(n-3))
So what does this mean? Well, the rightmost digit is 1 or 0 times 2 raised to the power of zero. In other words, it either adds 1 or 0 to the total. What about the second rightmost digit? It either adds 0 or 2 to the total. The next one? 0 or 4. See the pattern?
Let's write the pseudocode:
let n = input, in binary
total = 0
power of 2 = 0
while n has a length:
lastDigit = last digit of n
add (2^pow)*lastDigit to the current total
Since we start with a power and a total of 0, you can see why this works.
def IntegerConvert(num, base):
if num == 0:
return 0
else:
IntegerConvert.sum += pow(10, IntegerConvert.counter)*(num % base)
IntegerConvert.counter += 1
IntegerConvert(num/base, base)
return IntegerConvert.sum
IntegerConvert.counter = 0
IntegerConvert.sum = 0
print IntegerConvert(10, 2)

How to added up a variable with multiple values together in Python Recursion Function?

So I was studying recursion function online. And the one question asks me to write a function to add up a number's digits together. For example (1023) -> 1 + 0 + 2 + 3 = 6. I used % and // get get rid of a digit each time. However, I don't know how to add them up together. The closest I can get is to print out each digit. Can anyone help me solve it or give me a hint please?
def digitalSum(n):
if n < 10:
sum_total = n
print(sum_total)
else:
sum_total = n % 10
digitalSum((n - (n % 10))//10)
print(sum_total)
digitalSum(1213)
Your function should return the current digit plus the sum of the rest of the digits:
def digitalSum(n):
if n < 10: return n
return n % 10 + digitalSum(n // 10)
print digitalSum(1213)
For completeness, you can also handle negative numbers:
def digitalSum(n):
if n < 0: sign = -1
else: sign = 1
n = abs(n)
if n < 10: return n
return sign * (n % 10 + digitalSum(n // 10))
print digitalSum(1213)
A correct version of your function is as follows:
from math import log10
def sum_digits(n, i=None):
if i is None:
i = int(log10(abs(n)))
e = float(10**i)
a, b = (n / e), (abs(n) % e)
if i == 0:
return int(a)
else:
return int(a) + sum_digits(b, (i - 1))
print sum_digits(1234)
print sum_digits(-1234)
Example:
$ python -i foo.py
10
8
>>>
Updated: Updated to properly (IHMO) cope with negative numbers. e.g: -1234 == -1 + 2 + 3 + 4 == 8
NB: Whilst this answer has been accepted (Thank you) I really think that perreal's answer should have been accepted for simplicity and clarity.
Also note: that whilst my solution handles negative numbers and summing their respective digits, perreal clearly points out in our comments that there are ate least three different ways to interpret the summing of digits of a negative number.

Optimizing python code

Any tips on optimizing this python code for finding next palindrome:
Input number can be of 1000000 digits
COMMENTS ADDED
#! /usr/bin/python
def inc(lst,lng):#this function first extract the left half of the string then
#convert it to int then increment it then reconvert it to string
#then reverse it and finally append it to the left half.
#lst is input number and lng is its length
if(lng%2==0):
olst=lst[:lng/2]
l=int(lng/2)
olst=int(olst)
olst+=1
olst=str(olst)
p=len(olst)
if l<p:
olst2=olst[p-2::-1]
else:
olst2=olst[::-1]
lst=olst+olst2
return lst
else:
olst=lst[:lng/2+1]
l=int(lng/2+1)
olst=int(olst)
olst+=1
olst=str(olst)
p=len(olst)
if l<p:
olst2=olst[p-3::-1]
else:
olst2=olst[p-2::-1]
lst=olst+olst2
return lst
t=raw_input()
t=int(t)
while True:
if t>0:
t-=1
else:
break
num=raw_input()#this is input number
lng=len(num)
lst=num[:]
if(lng%2==0):#this if find next palindrome to num variable
#without incrementing the middle digit and store it in lst.
olst=lst[:lng/2]
olst2=olst[::-1]
lst=olst+olst2
else:
olst=lst[:lng/2+1]
olst2=olst[len(olst)-2::-1]
lst=olst+olst2
if int(num)>=int(lst):#chk if lst satisfies criteria for next palindrome
num=inc(num,lng)#otherwise call inc function
print num
else:
print lst
I think most of the time in this code is spent converting strings to integers and back. The rest is slicing strings and bouncing around in the Python interpreter. What can be done about these three things? There are a few unnecessary conversions in the code, which we can remove. I see no way to avoid the string slicing. To minimize your time in the interpreter you just have to write as little code as possible :-) and it also helps to put all your code inside functions.
The code at the bottom of your program, which takes a quick guess to try and avoid calling inc(), has a bug or two. Here's how I might write that part:
def nextPal(num):
lng = len(num)
guess = num[:lng//2] + num[(lng-1)//2::-1] # works whether lng is even or odd
if guess > num: # don't bother converting to int
return guess
else:
return inc(numstr, n)
This simple change makes your code about 100x faster for numbers where inc doesn't need to be called, and about 3x faster for numbers where it does need to be called.
To do better than that, I think you need to avoid converting to int entirely. That means incrementing the left half of the number without using ordinary Python integer addition. You can use an array and carry out the addition algorithm "by hand":
import array
def nextPal(numstr):
# If we don't need to increment, just reflect the left half and return.
n = len(numstr)
h = n//2
guess = numstr[:n-h] + numstr[h-1::-1]
if guess > numstr:
return guess
# Increment the left half of the number without converting to int.
a = array.array('b', numstr)
zero = ord('0')
ten = ord('9') + 1
for i in range(n - h - 1, -1, -1):
d = a[i] + 1
if d == ten:
a[i] = zero
else:
a[i] = d
break
else:
# The left half was all nines. Carry the 1.
# Update n and h since the length changed.
a.insert(0, ord('1'))
n += 1
h = n//2
# Reflect the left half onto the right half.
a[n-h:] = a[h-1::-1]
return a.tostring()
This is another 9x faster or so for numbers that require incrementing.
You can make this a touch faster by using a while loop instead of for i in range(n - h - 1, -1, -1), and about twice as fast again by having the loop update both halves of the array rather than just updating the left-hand half and then reflecting it at the end.
You don't have to find the palindrome, you can just generate it.
Split the input number, and reflect it. If the generated number is too small, then increment the left hand side and reflect it again:
def nextPal(n):
ns = str(n)
oddoffset = 0
if len(ns) % 2 != 0:
oddoffset = 1
leftlen = len(ns) / 2 + oddoffset
lefts = ns[0:leftlen]
right = lefts[::-1][oddoffset:]
p = int(lefts + right)
if p < n:
## Need to increment middle digit
left = int(lefts)
left += 1
lefts = str(left)
right = lefts[::-1][oddoffset:]
p = int(lefts + right)
return p
def test(n):
print n
p = nextPal(n)
assert p >= n
print p
test(1234567890)
test(123456789)
test(999999)
test(999998)
test(888889)
test(8999999)
EDIT
NVM, just look at this page: http://thetaoishere.blogspot.com/2009/04/finding-next-palindrome-given-number.html
Using strings. n >= 0
from math import floor, ceil, log10
def next_pal(n):
# returns next palindrome, param is an int
n10 = str(n)
m = len(n10) / 2.0
s, e = int(floor(m - 0.5)), int(ceil(m + 0.5))
start, middle, end = n10[:s], n10[s:e], n10[e:]
assert (start, middle[0]) == (end[-1::-1], middle[-1]) #check that n is actually a palindrome
r = int(start + middle[0]) + 1 #where the actual increment occurs (i.e. add 1)
r10 = str(r)
i = 3 - len(middle)
if len(r10) > len(start) + 1:
i += 1
return int(r10 + r10[-i::-1])
Using log, more optized. n > 9
def next_pal2(n):
k = log10(n + 1)
l = ceil(k)
s, e = int(floor(l/2.0 - 0.5)), int(ceil(l/2.0 + 0.5))
mmod, emod = 10**(e - s), int(10**(l - e))
start, end = divmod(n, emod)
start, middle = divmod(start, mmod)
r1 = 10*start + middle%10 + 1
i = middle > 9 and 1 or 2
j = s - i + 2
if k == l:
i += 1
r2 = int(str(r1)[-i::-1])
return r1*10**j + r2

Categories