Memory Limit Exceed - Python











up vote
1
down vote

favorite












I am running below code for getting indexes of two numbers from the input list whose sum is equal to target.



import itertools

class Solution:
def twoSum(self, nums, target):
combs = set(itertools.combinations(enumerate(nums), 2))
while combs:
elem = combs.pop()
if int(elem[0][1]) + int(elem[1][1]) == target:
return [elem[0][0], elem[1][0]]

cls = Solution()
nums = [3,3]
lst = cls.twoSum(nums,6)
print(lst)


It runs fine till input array is small, but when it grows to thousands of number, am getting Memory Limit Exceed. I believe there should be some other optimised way to do it.










share|improve this question


























    up vote
    1
    down vote

    favorite












    I am running below code for getting indexes of two numbers from the input list whose sum is equal to target.



    import itertools

    class Solution:
    def twoSum(self, nums, target):
    combs = set(itertools.combinations(enumerate(nums), 2))
    while combs:
    elem = combs.pop()
    if int(elem[0][1]) + int(elem[1][1]) == target:
    return [elem[0][0], elem[1][0]]

    cls = Solution()
    nums = [3,3]
    lst = cls.twoSum(nums,6)
    print(lst)


    It runs fine till input array is small, but when it grows to thousands of number, am getting Memory Limit Exceed. I believe there should be some other optimised way to do it.










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I am running below code for getting indexes of two numbers from the input list whose sum is equal to target.



      import itertools

      class Solution:
      def twoSum(self, nums, target):
      combs = set(itertools.combinations(enumerate(nums), 2))
      while combs:
      elem = combs.pop()
      if int(elem[0][1]) + int(elem[1][1]) == target:
      return [elem[0][0], elem[1][0]]

      cls = Solution()
      nums = [3,3]
      lst = cls.twoSum(nums,6)
      print(lst)


      It runs fine till input array is small, but when it grows to thousands of number, am getting Memory Limit Exceed. I believe there should be some other optimised way to do it.










      share|improve this question













      I am running below code for getting indexes of two numbers from the input list whose sum is equal to target.



      import itertools

      class Solution:
      def twoSum(self, nums, target):
      combs = set(itertools.combinations(enumerate(nums), 2))
      while combs:
      elem = combs.pop()
      if int(elem[0][1]) + int(elem[1][1]) == target:
      return [elem[0][0], elem[1][0]]

      cls = Solution()
      nums = [3,3]
      lst = cls.twoSum(nums,6)
      print(lst)


      It runs fine till input array is small, but when it grows to thousands of number, am getting Memory Limit Exceed. I believe there should be some other optimised way to do it.







      loops python-3.6






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 at 11:47









      Neeraj Sharma

      478




      478
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Well because we cannot have array/ consecutive memory blocks more than 10^6 or 10^7



          If we have Multidimensional array size will reduce to Matrix[1000][1000] to get total ~10^7 blocks



          Itertools generate all possible pairs which could be exponential, and storing it in the set will definately overflow both in time and space.



          So Solution to this would be improve the algorithm in both time and memory complexity.



          one of the way to solve this problem is by hashing,



          Basic idea is
          A + B = target, where A,B are elements of an array



          so we maintain hashtable with, key = element and value = index



          and iterate to find if B = target - A, is present in the array, if found we print index of (A,B)



          class Solution:
          def twoSum(self, nums, target):
          hashtable = dict() # key = number , value = index
          n = len(nums)
          lst =
          for i in range(n):

          if(hashtable.get(target-nums[i],None) is None):
          # not found so update the hashtable
          hashtable[nums[i]] = i
          else:
          # pair found
          lst.append((hashtable[target-nums[i]],i))

          return lst

          cls = Solution()

          nums = [3,3]
          lst = cls.twoSum(nums,6)

          print(lst)





          share|improve this answer























          • It worked very well. Thanks very good logic.
            – Neeraj Sharma
            2 days ago











          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%2f53373986%2fmemory-limit-exceed-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          Well because we cannot have array/ consecutive memory blocks more than 10^6 or 10^7



          If we have Multidimensional array size will reduce to Matrix[1000][1000] to get total ~10^7 blocks



          Itertools generate all possible pairs which could be exponential, and storing it in the set will definately overflow both in time and space.



          So Solution to this would be improve the algorithm in both time and memory complexity.



          one of the way to solve this problem is by hashing,



          Basic idea is
          A + B = target, where A,B are elements of an array



          so we maintain hashtable with, key = element and value = index



          and iterate to find if B = target - A, is present in the array, if found we print index of (A,B)



          class Solution:
          def twoSum(self, nums, target):
          hashtable = dict() # key = number , value = index
          n = len(nums)
          lst =
          for i in range(n):

          if(hashtable.get(target-nums[i],None) is None):
          # not found so update the hashtable
          hashtable[nums[i]] = i
          else:
          # pair found
          lst.append((hashtable[target-nums[i]],i))

          return lst

          cls = Solution()

          nums = [3,3]
          lst = cls.twoSum(nums,6)

          print(lst)





          share|improve this answer























          • It worked very well. Thanks very good logic.
            – Neeraj Sharma
            2 days ago















          up vote
          0
          down vote



          accepted










          Well because we cannot have array/ consecutive memory blocks more than 10^6 or 10^7



          If we have Multidimensional array size will reduce to Matrix[1000][1000] to get total ~10^7 blocks



          Itertools generate all possible pairs which could be exponential, and storing it in the set will definately overflow both in time and space.



          So Solution to this would be improve the algorithm in both time and memory complexity.



          one of the way to solve this problem is by hashing,



          Basic idea is
          A + B = target, where A,B are elements of an array



          so we maintain hashtable with, key = element and value = index



          and iterate to find if B = target - A, is present in the array, if found we print index of (A,B)



          class Solution:
          def twoSum(self, nums, target):
          hashtable = dict() # key = number , value = index
          n = len(nums)
          lst =
          for i in range(n):

          if(hashtable.get(target-nums[i],None) is None):
          # not found so update the hashtable
          hashtable[nums[i]] = i
          else:
          # pair found
          lst.append((hashtable[target-nums[i]],i))

          return lst

          cls = Solution()

          nums = [3,3]
          lst = cls.twoSum(nums,6)

          print(lst)





          share|improve this answer























          • It worked very well. Thanks very good logic.
            – Neeraj Sharma
            2 days ago













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          Well because we cannot have array/ consecutive memory blocks more than 10^6 or 10^7



          If we have Multidimensional array size will reduce to Matrix[1000][1000] to get total ~10^7 blocks



          Itertools generate all possible pairs which could be exponential, and storing it in the set will definately overflow both in time and space.



          So Solution to this would be improve the algorithm in both time and memory complexity.



          one of the way to solve this problem is by hashing,



          Basic idea is
          A + B = target, where A,B are elements of an array



          so we maintain hashtable with, key = element and value = index



          and iterate to find if B = target - A, is present in the array, if found we print index of (A,B)



          class Solution:
          def twoSum(self, nums, target):
          hashtable = dict() # key = number , value = index
          n = len(nums)
          lst =
          for i in range(n):

          if(hashtable.get(target-nums[i],None) is None):
          # not found so update the hashtable
          hashtable[nums[i]] = i
          else:
          # pair found
          lst.append((hashtable[target-nums[i]],i))

          return lst

          cls = Solution()

          nums = [3,3]
          lst = cls.twoSum(nums,6)

          print(lst)





          share|improve this answer














          Well because we cannot have array/ consecutive memory blocks more than 10^6 or 10^7



          If we have Multidimensional array size will reduce to Matrix[1000][1000] to get total ~10^7 blocks



          Itertools generate all possible pairs which could be exponential, and storing it in the set will definately overflow both in time and space.



          So Solution to this would be improve the algorithm in both time and memory complexity.



          one of the way to solve this problem is by hashing,



          Basic idea is
          A + B = target, where A,B are elements of an array



          so we maintain hashtable with, key = element and value = index



          and iterate to find if B = target - A, is present in the array, if found we print index of (A,B)



          class Solution:
          def twoSum(self, nums, target):
          hashtable = dict() # key = number , value = index
          n = len(nums)
          lst =
          for i in range(n):

          if(hashtable.get(target-nums[i],None) is None):
          # not found so update the hashtable
          hashtable[nums[i]] = i
          else:
          # pair found
          lst.append((hashtable[target-nums[i]],i))

          return lst

          cls = Solution()

          nums = [3,3]
          lst = cls.twoSum(nums,6)

          print(lst)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 at 12:27

























          answered Nov 19 at 12:19









          jwala

          616




          616












          • It worked very well. Thanks very good logic.
            – Neeraj Sharma
            2 days ago


















          • It worked very well. Thanks very good logic.
            – Neeraj Sharma
            2 days ago
















          It worked very well. Thanks very good logic.
          – Neeraj Sharma
          2 days ago




          It worked very well. Thanks very good logic.
          – Neeraj Sharma
          2 days ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53373986%2fmemory-limit-exceed-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

          Wiesbaden

          Marschland

          Dieringhausen