Python Forum
I've always wanted to write this but having problems
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I've always wanted to write this but having problems
#3
Another approach could be using divmod:

def to_binary(num):
  reminders = []
  while num:
      num, reminder = divmod(num, 2)
      reminders.append(reminder)
  return ''.join(str(x) for x in reversed(reminders),)
To test:

>>> to_binary(42)
'101010'
>>> int(to_binary(42), 2)
42
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: I've always wanted to write this but having problems - by perfringo - Sep-08-2019, 10:22 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Upgrading from 2 to 3 and having file write problems KenHorse 2 1,563 May-08-2022, 09:47 PM
Last Post: KenHorse

Forum Jump:

User Panel Messages

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