Fastest algorithm to perform N*M iterations in Python









up vote
4
down vote

favorite
1












I am not an algorithm person, so pardon the naivety of the question.



I have a list A containing elements 100K elements. I have another list B containing 100K elements. Let's say a is an element from list A, b is the element from list B. I want to find out those (a, b) combinations whose sum is less than 100.



One obvious way to do this is following:



results = 
for a in A:
for b in B:
if (a+b) < 100:
results.append((a,b))


but the time complexity of this approach is O(n*m) = 100K * 100K which is quite large. Is there any fast algorithm which can compute the desired output more efficiently - in terms of memory and time. If yes, can it be implemented in python?










share|improve this question

















  • 1




    If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
    – merlyn
    Nov 9 at 16:15






  • 1




    @merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
    – Nelfeal
    Nov 9 at 16:17







  • 1




    @Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
    – merlyn
    Nov 9 at 16:19






  • 1




    @userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
    – Joseph Wood
    Nov 9 at 17:07






  • 1




    @userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
    – Nelfeal
    Nov 9 at 17:07














up vote
4
down vote

favorite
1












I am not an algorithm person, so pardon the naivety of the question.



I have a list A containing elements 100K elements. I have another list B containing 100K elements. Let's say a is an element from list A, b is the element from list B. I want to find out those (a, b) combinations whose sum is less than 100.



One obvious way to do this is following:



results = 
for a in A:
for b in B:
if (a+b) < 100:
results.append((a,b))


but the time complexity of this approach is O(n*m) = 100K * 100K which is quite large. Is there any fast algorithm which can compute the desired output more efficiently - in terms of memory and time. If yes, can it be implemented in python?










share|improve this question

















  • 1




    If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
    – merlyn
    Nov 9 at 16:15






  • 1




    @merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
    – Nelfeal
    Nov 9 at 16:17







  • 1




    @Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
    – merlyn
    Nov 9 at 16:19






  • 1




    @userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
    – Joseph Wood
    Nov 9 at 17:07






  • 1




    @userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
    – Nelfeal
    Nov 9 at 17:07












up vote
4
down vote

favorite
1









up vote
4
down vote

favorite
1






1





I am not an algorithm person, so pardon the naivety of the question.



I have a list A containing elements 100K elements. I have another list B containing 100K elements. Let's say a is an element from list A, b is the element from list B. I want to find out those (a, b) combinations whose sum is less than 100.



One obvious way to do this is following:



results = 
for a in A:
for b in B:
if (a+b) < 100:
results.append((a,b))


but the time complexity of this approach is O(n*m) = 100K * 100K which is quite large. Is there any fast algorithm which can compute the desired output more efficiently - in terms of memory and time. If yes, can it be implemented in python?










share|improve this question













I am not an algorithm person, so pardon the naivety of the question.



I have a list A containing elements 100K elements. I have another list B containing 100K elements. Let's say a is an element from list A, b is the element from list B. I want to find out those (a, b) combinations whose sum is less than 100.



One obvious way to do this is following:



results = 
for a in A:
for b in B:
if (a+b) < 100:
results.append((a,b))


but the time complexity of this approach is O(n*m) = 100K * 100K which is quite large. Is there any fast algorithm which can compute the desired output more efficiently - in terms of memory and time. If yes, can it be implemented in python?







python algorithm data-structures






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 16:07









userxxx

401515




401515







  • 1




    If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
    – merlyn
    Nov 9 at 16:15






  • 1




    @merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
    – Nelfeal
    Nov 9 at 16:17







  • 1




    @Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
    – merlyn
    Nov 9 at 16:19






  • 1




    @userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
    – Joseph Wood
    Nov 9 at 17:07






  • 1




    @userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
    – Nelfeal
    Nov 9 at 17:07












  • 1




    If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
    – merlyn
    Nov 9 at 16:15






  • 1




    @merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
    – Nelfeal
    Nov 9 at 16:17







  • 1




    @Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
    – merlyn
    Nov 9 at 16:19






  • 1




    @userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
    – Joseph Wood
    Nov 9 at 17:07






  • 1




    @userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
    – Nelfeal
    Nov 9 at 17:07







1




1




If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
– merlyn
Nov 9 at 16:15




If you want to find all the actual pairs, then there is no faster method as the final output can be as big as 100k * 100k.
– merlyn
Nov 9 at 16:15




1




1




@merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
– Nelfeal
Nov 9 at 16:17





@merlyn There are 5 positive integers smaller than 6, but I didn't have to think about all 5 to come up with that. Well, unless you want the complete list of them, indeed.
– Nelfeal
Nov 9 at 16:17





1




1




@Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
– merlyn
Nov 9 at 16:19




@Nelfeal That's kind of my point. You can find the number of solutions, not the solutions themselves. That could very well be what the OP actually wanted, but in the question, he is calculating the actual list.
– merlyn
Nov 9 at 16:19




1




1




@userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
– Joseph Wood
Nov 9 at 17:07




@userxxx , you should not ask a follow up question in the comments. Instead, ask a new question and reference this question if necessary.
– Joseph Wood
Nov 9 at 17:07




1




1




@userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
– Nelfeal
Nov 9 at 17:07




@userxxx Finding all pairs of strings a, b such that concatenation(a, b) = target is even easier: only some as can serve as prefix, and only some bs can serve as suffix. But the problem is quite different, so the solution is also quite different.
– Nelfeal
Nov 9 at 17:07












3 Answers
3






active

oldest

votes

















up vote
9
down vote













Sort both lists (O(n log n) and O(m log m), maybe less if the values are constrained).



Then, you can simply find, for each a in A, the largest b in B such that (a+b) < 100. Every smaller b will also satisfy that condition.



Finding the largest b for some a can be done using binary search to find a lower bound in B. And by starting with the largest a going down, you can preserve the list of bs corresponding to the previous a, since the sum is going to be smaller.






share|improve this answer






















  • yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
    – Jean-François Fabre
    Nov 9 at 16:14










  • "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
    – Alex
    Nov 9 at 16:22











  • appending would, but a slice should be O(1), correct?
    – C.Nivs
    Nov 9 at 16:22










  • @C.Nivs when you combine slices for each element in A, you still hit O(m).
    – Alex
    Nov 9 at 16:24










  • @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
    – Nelfeal
    Nov 9 at 16:28

















up vote
1
down vote













No you can't get better than that in the worst case. Consider a pathological case where every combination of A and B must be appended to the list:



A = list(range(0, -n, -1))
B = list(range(0, -m, -1))


Because each pair must be appended, you are doing O(m * n) operations.



If you only needed to count the number of combinations this could be a different story.






share|improve this answer



























    up vote
    0
    down vote













    As your criteria is that a + b < 100 that can be defined as range. In this case I defined it as wanted_result_range = range(0, 100) as your lists A and B are containing only positive numbers so results will be only positive values.



    Run the following script and you will see how much faster is my approach than "frontal" one that you have mentioned. My solution will be bad if wider wanted_result_range is defined.



    import timeit
    # http://docs.python.org/3.3/library/timeit.html

    print "nTiming execution timesn"

    version1="""
    results1 =
    list_A = range(1000)
    list_B = range(1000)
    wanted_result_range = range(0, 100)
    d1 =
    l3 =
    for key in list_A:
    d1[key] = True # Value associated to key is not important and can be any value
    for wanted_result in wanted_result_range:
    for key2 in list_B:
    if ((wanted_result-key2) in d1):
    results1.append((key2,wanted_result-key2))
    """
    print("Version 1 - Hash table (dictionary) approach")
    print(timeit.repeat(version1, number=10, repeat=4))
    print('END Version 1n')

    version2="""
    results2 =
    list_A = range(1000)
    list_B = range(1000)
    for a in list_A:
    for b in list_B:
    if (a+b) < 100:
    results2.append((a,b))
    """
    print("Version 2 - Frontal approach")
    print(timeit.repeat(version2, number=10, repeat=4))
    print('END Version 2n')





    share|improve this answer




















    • Nowhere in the question is stated that A and B contain only positive numbers.
      – Nelfeal
      Nov 10 at 7:07










    • @Nelfeal This can be used with negative numbers too.
      – jaskowitchious
      Nov 10 at 21:28










    • Really? Good luck making it work with the "wanted result range" being [-inf, 100].
      – Nelfeal
      Nov 11 at 7:09










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229317%2ffastest-algorithm-to-perform-nm-iterations-in-python%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    9
    down vote













    Sort both lists (O(n log n) and O(m log m), maybe less if the values are constrained).



    Then, you can simply find, for each a in A, the largest b in B such that (a+b) < 100. Every smaller b will also satisfy that condition.



    Finding the largest b for some a can be done using binary search to find a lower bound in B. And by starting with the largest a going down, you can preserve the list of bs corresponding to the previous a, since the sum is going to be smaller.






    share|improve this answer






















    • yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
      – Jean-François Fabre
      Nov 9 at 16:14










    • "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
      – Alex
      Nov 9 at 16:22











    • appending would, but a slice should be O(1), correct?
      – C.Nivs
      Nov 9 at 16:22










    • @C.Nivs when you combine slices for each element in A, you still hit O(m).
      – Alex
      Nov 9 at 16:24










    • @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
      – Nelfeal
      Nov 9 at 16:28














    up vote
    9
    down vote













    Sort both lists (O(n log n) and O(m log m), maybe less if the values are constrained).



    Then, you can simply find, for each a in A, the largest b in B such that (a+b) < 100. Every smaller b will also satisfy that condition.



    Finding the largest b for some a can be done using binary search to find a lower bound in B. And by starting with the largest a going down, you can preserve the list of bs corresponding to the previous a, since the sum is going to be smaller.






    share|improve this answer






















    • yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
      – Jean-François Fabre
      Nov 9 at 16:14










    • "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
      – Alex
      Nov 9 at 16:22











    • appending would, but a slice should be O(1), correct?
      – C.Nivs
      Nov 9 at 16:22










    • @C.Nivs when you combine slices for each element in A, you still hit O(m).
      – Alex
      Nov 9 at 16:24










    • @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
      – Nelfeal
      Nov 9 at 16:28












    up vote
    9
    down vote










    up vote
    9
    down vote









    Sort both lists (O(n log n) and O(m log m), maybe less if the values are constrained).



    Then, you can simply find, for each a in A, the largest b in B such that (a+b) < 100. Every smaller b will also satisfy that condition.



    Finding the largest b for some a can be done using binary search to find a lower bound in B. And by starting with the largest a going down, you can preserve the list of bs corresponding to the previous a, since the sum is going to be smaller.






    share|improve this answer














    Sort both lists (O(n log n) and O(m log m), maybe less if the values are constrained).



    Then, you can simply find, for each a in A, the largest b in B such that (a+b) < 100. Every smaller b will also satisfy that condition.



    Finding the largest b for some a can be done using binary search to find a lower bound in B. And by starting with the largest a going down, you can preserve the list of bs corresponding to the previous a, since the sum is going to be smaller.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 9 at 18:02

























    answered Nov 9 at 16:13









    Nelfeal

    3,773621




    3,773621











    • yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
      – Jean-François Fabre
      Nov 9 at 16:14










    • "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
      – Alex
      Nov 9 at 16:22











    • appending would, but a slice should be O(1), correct?
      – C.Nivs
      Nov 9 at 16:22










    • @C.Nivs when you combine slices for each element in A, you still hit O(m).
      – Alex
      Nov 9 at 16:24










    • @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
      – Nelfeal
      Nov 9 at 16:28
















    • yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
      – Jean-François Fabre
      Nov 9 at 16:14










    • "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
      – Alex
      Nov 9 at 16:22











    • appending would, but a slice should be O(1), correct?
      – C.Nivs
      Nov 9 at 16:22










    • @C.Nivs when you combine slices for each element in A, you still hit O(m).
      – Alex
      Nov 9 at 16:24










    • @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
      – Nelfeal
      Nov 9 at 16:28















    yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
    – Jean-François Fabre
    Nov 9 at 16:14




    yeah, knapsack problem all right. Needs special bisect implementation. That's the way.
    – Jean-François Fabre
    Nov 9 at 16:14












    "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
    – Alex
    Nov 9 at 16:22





    "Every smaller b will also satisfy that condition." this can be O(m) to append them all to a list. That statement just obfuscates that part of the time complexity.
    – Alex
    Nov 9 at 16:22













    appending would, but a slice should be O(1), correct?
    – C.Nivs
    Nov 9 at 16:22




    appending would, but a slice should be O(1), correct?
    – C.Nivs
    Nov 9 at 16:22












    @C.Nivs when you combine slices for each element in A, you still hit O(m).
    – Alex
    Nov 9 at 16:24




    @C.Nivs when you combine slices for each element in A, you still hit O(m).
    – Alex
    Nov 9 at 16:24












    @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
    – Nelfeal
    Nov 9 at 16:28




    @Alex Well of course you can't go below q operations if you have q solutions and want them all in a list. I figure you either group them, or you know constraints that imply q isn't too large.
    – Nelfeal
    Nov 9 at 16:28












    up vote
    1
    down vote













    No you can't get better than that in the worst case. Consider a pathological case where every combination of A and B must be appended to the list:



    A = list(range(0, -n, -1))
    B = list(range(0, -m, -1))


    Because each pair must be appended, you are doing O(m * n) operations.



    If you only needed to count the number of combinations this could be a different story.






    share|improve this answer
























      up vote
      1
      down vote













      No you can't get better than that in the worst case. Consider a pathological case where every combination of A and B must be appended to the list:



      A = list(range(0, -n, -1))
      B = list(range(0, -m, -1))


      Because each pair must be appended, you are doing O(m * n) operations.



      If you only needed to count the number of combinations this could be a different story.






      share|improve this answer






















        up vote
        1
        down vote










        up vote
        1
        down vote









        No you can't get better than that in the worst case. Consider a pathological case where every combination of A and B must be appended to the list:



        A = list(range(0, -n, -1))
        B = list(range(0, -m, -1))


        Because each pair must be appended, you are doing O(m * n) operations.



        If you only needed to count the number of combinations this could be a different story.






        share|improve this answer












        No you can't get better than that in the worst case. Consider a pathological case where every combination of A and B must be appended to the list:



        A = list(range(0, -n, -1))
        B = list(range(0, -m, -1))


        Because each pair must be appended, you are doing O(m * n) operations.



        If you only needed to count the number of combinations this could be a different story.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 16:36









        Alex

        10.2k32354




        10.2k32354




















            up vote
            0
            down vote













            As your criteria is that a + b < 100 that can be defined as range. In this case I defined it as wanted_result_range = range(0, 100) as your lists A and B are containing only positive numbers so results will be only positive values.



            Run the following script and you will see how much faster is my approach than "frontal" one that you have mentioned. My solution will be bad if wider wanted_result_range is defined.



            import timeit
            # http://docs.python.org/3.3/library/timeit.html

            print "nTiming execution timesn"

            version1="""
            results1 =
            list_A = range(1000)
            list_B = range(1000)
            wanted_result_range = range(0, 100)
            d1 =
            l3 =
            for key in list_A:
            d1[key] = True # Value associated to key is not important and can be any value
            for wanted_result in wanted_result_range:
            for key2 in list_B:
            if ((wanted_result-key2) in d1):
            results1.append((key2,wanted_result-key2))
            """
            print("Version 1 - Hash table (dictionary) approach")
            print(timeit.repeat(version1, number=10, repeat=4))
            print('END Version 1n')

            version2="""
            results2 =
            list_A = range(1000)
            list_B = range(1000)
            for a in list_A:
            for b in list_B:
            if (a+b) < 100:
            results2.append((a,b))
            """
            print("Version 2 - Frontal approach")
            print(timeit.repeat(version2, number=10, repeat=4))
            print('END Version 2n')





            share|improve this answer




















            • Nowhere in the question is stated that A and B contain only positive numbers.
              – Nelfeal
              Nov 10 at 7:07










            • @Nelfeal This can be used with negative numbers too.
              – jaskowitchious
              Nov 10 at 21:28










            • Really? Good luck making it work with the "wanted result range" being [-inf, 100].
              – Nelfeal
              Nov 11 at 7:09














            up vote
            0
            down vote













            As your criteria is that a + b < 100 that can be defined as range. In this case I defined it as wanted_result_range = range(0, 100) as your lists A and B are containing only positive numbers so results will be only positive values.



            Run the following script and you will see how much faster is my approach than "frontal" one that you have mentioned. My solution will be bad if wider wanted_result_range is defined.



            import timeit
            # http://docs.python.org/3.3/library/timeit.html

            print "nTiming execution timesn"

            version1="""
            results1 =
            list_A = range(1000)
            list_B = range(1000)
            wanted_result_range = range(0, 100)
            d1 =
            l3 =
            for key in list_A:
            d1[key] = True # Value associated to key is not important and can be any value
            for wanted_result in wanted_result_range:
            for key2 in list_B:
            if ((wanted_result-key2) in d1):
            results1.append((key2,wanted_result-key2))
            """
            print("Version 1 - Hash table (dictionary) approach")
            print(timeit.repeat(version1, number=10, repeat=4))
            print('END Version 1n')

            version2="""
            results2 =
            list_A = range(1000)
            list_B = range(1000)
            for a in list_A:
            for b in list_B:
            if (a+b) < 100:
            results2.append((a,b))
            """
            print("Version 2 - Frontal approach")
            print(timeit.repeat(version2, number=10, repeat=4))
            print('END Version 2n')





            share|improve this answer




















            • Nowhere in the question is stated that A and B contain only positive numbers.
              – Nelfeal
              Nov 10 at 7:07










            • @Nelfeal This can be used with negative numbers too.
              – jaskowitchious
              Nov 10 at 21:28










            • Really? Good luck making it work with the "wanted result range" being [-inf, 100].
              – Nelfeal
              Nov 11 at 7:09












            up vote
            0
            down vote










            up vote
            0
            down vote









            As your criteria is that a + b < 100 that can be defined as range. In this case I defined it as wanted_result_range = range(0, 100) as your lists A and B are containing only positive numbers so results will be only positive values.



            Run the following script and you will see how much faster is my approach than "frontal" one that you have mentioned. My solution will be bad if wider wanted_result_range is defined.



            import timeit
            # http://docs.python.org/3.3/library/timeit.html

            print "nTiming execution timesn"

            version1="""
            results1 =
            list_A = range(1000)
            list_B = range(1000)
            wanted_result_range = range(0, 100)
            d1 =
            l3 =
            for key in list_A:
            d1[key] = True # Value associated to key is not important and can be any value
            for wanted_result in wanted_result_range:
            for key2 in list_B:
            if ((wanted_result-key2) in d1):
            results1.append((key2,wanted_result-key2))
            """
            print("Version 1 - Hash table (dictionary) approach")
            print(timeit.repeat(version1, number=10, repeat=4))
            print('END Version 1n')

            version2="""
            results2 =
            list_A = range(1000)
            list_B = range(1000)
            for a in list_A:
            for b in list_B:
            if (a+b) < 100:
            results2.append((a,b))
            """
            print("Version 2 - Frontal approach")
            print(timeit.repeat(version2, number=10, repeat=4))
            print('END Version 2n')





            share|improve this answer












            As your criteria is that a + b < 100 that can be defined as range. In this case I defined it as wanted_result_range = range(0, 100) as your lists A and B are containing only positive numbers so results will be only positive values.



            Run the following script and you will see how much faster is my approach than "frontal" one that you have mentioned. My solution will be bad if wider wanted_result_range is defined.



            import timeit
            # http://docs.python.org/3.3/library/timeit.html

            print "nTiming execution timesn"

            version1="""
            results1 =
            list_A = range(1000)
            list_B = range(1000)
            wanted_result_range = range(0, 100)
            d1 =
            l3 =
            for key in list_A:
            d1[key] = True # Value associated to key is not important and can be any value
            for wanted_result in wanted_result_range:
            for key2 in list_B:
            if ((wanted_result-key2) in d1):
            results1.append((key2,wanted_result-key2))
            """
            print("Version 1 - Hash table (dictionary) approach")
            print(timeit.repeat(version1, number=10, repeat=4))
            print('END Version 1n')

            version2="""
            results2 =
            list_A = range(1000)
            list_B = range(1000)
            for a in list_A:
            for b in list_B:
            if (a+b) < 100:
            results2.append((a,b))
            """
            print("Version 2 - Frontal approach")
            print(timeit.repeat(version2, number=10, repeat=4))
            print('END Version 2n')






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 9 at 20:50









            jaskowitchious

            61




            61











            • Nowhere in the question is stated that A and B contain only positive numbers.
              – Nelfeal
              Nov 10 at 7:07










            • @Nelfeal This can be used with negative numbers too.
              – jaskowitchious
              Nov 10 at 21:28










            • Really? Good luck making it work with the "wanted result range" being [-inf, 100].
              – Nelfeal
              Nov 11 at 7:09
















            • Nowhere in the question is stated that A and B contain only positive numbers.
              – Nelfeal
              Nov 10 at 7:07










            • @Nelfeal This can be used with negative numbers too.
              – jaskowitchious
              Nov 10 at 21:28










            • Really? Good luck making it work with the "wanted result range" being [-inf, 100].
              – Nelfeal
              Nov 11 at 7:09















            Nowhere in the question is stated that A and B contain only positive numbers.
            – Nelfeal
            Nov 10 at 7:07




            Nowhere in the question is stated that A and B contain only positive numbers.
            – Nelfeal
            Nov 10 at 7:07












            @Nelfeal This can be used with negative numbers too.
            – jaskowitchious
            Nov 10 at 21:28




            @Nelfeal This can be used with negative numbers too.
            – jaskowitchious
            Nov 10 at 21:28












            Really? Good luck making it work with the "wanted result range" being [-inf, 100].
            – Nelfeal
            Nov 11 at 7:09




            Really? Good luck making it work with the "wanted result range" being [-inf, 100].
            – Nelfeal
            Nov 11 at 7:09

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229317%2ffastest-algorithm-to-perform-nm-iterations-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Syphilis

            Darth Vader #20