@diazona@techhub.social avatar

diazona

@diazona@techhub.social

Software engineer, former particle physicist, occasional blogger. I support the principle of cake.

This profile is from a federated server and may be incomplete. Browse more on the original instance.

desertplains, to python
@desertplains@mastodon.social avatar

I wonder if there's a more efficient way of implementing decimal to #binary conversion in #python

Without recursion, it's ok, but there will be variable assignments operations, which seems to me as something not so efficient, comparing with recursion...

image/png

diazona,
@diazona@techhub.social avatar

@desertplains You could make a helper function which is a generator and just yield digits instead of appending to a string. Then call ''.join(helper_function(n)) to get the final result. That avoids a bunch of string concatenations. Or another (slightly less elegant IMO, but totally valid) way to do it is to build up a list of characters in the loop instead of appending to a string. You may find working with a list is more efficient.

If you really want to get into high efficiency (within the constraints of what Python allows, of course; it'll never be as fast as C), you might try something like using a lookup table and accumulator to produce blocks of 3 bits at a time. I don't know if that'd actually turn out faster, but it may be worth checking. I can elaborate if you're interested.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • JUstTest
  • kavyap
  • DreamBathrooms
  • mdbf
  • InstantRegret
  • ngwrru68w68
  • magazineikmin
  • thenastyranch
  • Durango
  • rosin
  • Youngstown
  • slotface
  • khanakhh
  • tacticalgear
  • megavids
  • ethstaker
  • cubers
  • cisconetworking
  • Leos
  • modclub
  • everett
  • osvaldo12
  • GTA5RPClips
  • tester
  • anitta
  • provamag3
  • normalnudes
  • lostlight
  • All magazines