Noob questions about Python

C

cokofreedom

On Oct 18, 7:05 am, Michele Simionato <[email protected]>
def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)
It basically does the same thing int(string, 2) does.
Thank you for the responses!
BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)

It returns '' when number == 0, so you need to test for that case:
def baseN(number, N=2):
"""
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0

if number == 0:
return "0"

Hey,

Isn't
if not number:
return "0"

faster?
 
A

A.T.Hofkamp

Hey,

Isn't
if not number:
return "0"

faster?

Depends on who is parsing it.

If a computer, possibly a few micro-seconds (if the Python byte-code generator
doesn't optimize it away).

If a human, then it is slower by at least a second.


Since I prefer to optimize on my time rather than CPU time, I'd prefer the
first version

Albert
 
G

Grant Edwards

I read somewhere:

Only 1 person in 1000 understands binary.
The other 111 don't have a clue.

There are only 10 kinds of people: those who understand binary
and those who don't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,117
Latest member
Matilda564
Top