0

LIST OF LIST BIN DIVIDED INTO 8 : [[0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1]]

the output I want is:

[101, 119]

3
  • @Shmack It was probably deleted because it was syntactically flawed Commented Nov 30, 2022 at 8:57
  • @Cobra well I didn't get a long enough glance at it, but it looked good. Commented Nov 30, 2022 at 16:43
  • @Schmack I can still see the original post. Trust me, it's broken Commented Nov 30, 2022 at 16:45

1 Answer 1

2

This is more complex but significantly faster than any kind of string manipulation as it's essentially just integer arithmetic.

from timeit import timeit

lob = [[0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1, 1, 1]]

def v1():
    result = []
    for e in lob:
        r = 0
        for _e in e:
            r = r * 2 + _e
        result.append(r)
    return result

def v2():
    return [int(''.join([str(y) for y in x]), 2) for x in lob]

assert v1() == v2()

for func in v1, v2:
    print(func.__name__, timeit(func))

Output:

v1 0.6906622060014342
v2 2.173182999999881
Sign up to request clarification or add additional context in comments.

7 Comments

Are you sure this will be significantly faster?
@user56700 See edit. Performance will vary depending on your system's capability
Thank you, now I can see that it's faster, but can you elaborate why that might be? I cannot seem to figure out why. Why is int() so slow as a build in function?
@user56700 You need to break down the "string" version into its component parts. You convert each int to a str. You build a list. You join that list. You then convert the resultant str to int. My version is essentially just integer arithmetic
Thank you so much! Maybe you should add some explanation to the answer too for others. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.