Python Forum
Incrementing binary number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Incrementing binary number
#1


Hello, I got this assignment of incrementing a binary number (which displays as a string) without using base converting.

i wrote the code which i think is pretty good, but i got stuck with an error message when used this line of code:
return ''.join(lst_binary.insert(0,'1'))
that happens when the prog gets a string like '111', and needs to add another digit at the end of number.

the error i got was
Error:
"TypeError: can only join an iterable"
while was debugging with python-tutor

this is the whole code:
def inc(binary):
    lst_binary = list(binary)
    for bit in range(len(binary)-1, -1, -1):
        if lst_binary[bit] == '0':
            lst_binary[bit] = '1'
            return ''.join(lst_binary)
        else:
            lst_binary[bit] = '0'
    return ''.join(lst_binary.insert(0,'1'))
im not looking though for other ways to do this, just to understand why this line doesnt work
Reply
#2
The method insert of lst_binary returns None. Just memorize, that methods which mutates the object, returns regularly None. Immutable objects return something, when you use a method. For example str.upper('Foo') returns a new object, because the object itself is not mutable. It's immutable.

Methods of lists like sort, insert and remove won't return the list itself. The list object is mutating.
Just do your modification to your list with insert and use return ''.join(lst_binary) to join the modified list.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
(Nov-10-2017, 11:40 AM)DeaD_EyE Wrote: The method insert of lst_binary returns None. Just memorize, that methods which mutates the object, returns regularly None. Immutable objects return something, when you use a method. For example str.upper('Foo') returns a new object, because the object itself is not mutable. It's immutable.

Methods of lists like sort, insert and remove won't return the list itself. The list object is mutating.
Just do your modification to your list with insert and use return ''.join(lst_binary) to join the modified list.

Thanks for the reply. At last i thought about this way return '1' + ''.join(lst_binary), and it works as well.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020