Distribute value over listHow do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Iterating over dictionaries using 'for' loopsWhy not inherit from List<T>?

More than three domains hosted on the same IP address

Stack class in Java 8

Contractor cut joist hangers to make them fit

What is the difference between a translation and a Galilean transformation?

What makes an ending "happy"?

Is mountain bike good for long distances?

How would two worlds first establish an exchange rate between their currencies

Why does low tire pressure decrease fuel economy?

Determining System Regular Expression Library

Aftermarket seats

How to capture c-lightining logs?

How is lower/no gravity simulated on a planet with gravity, without leaving the surface?

Does the 2019 UA artificer need to prepare the Lesser Restoration spell to cast it with their Alchemical Mastery feature?

Can you mark a new target with the Hunter's Mark spell if the original target shifts to a different plane?

Distinguishing between octahedral and tetrahedral holes

Leaving the USA for 10 yrs when you have asylum

How can I protect myself in case of attack in case like this?

The pirate treasure of Leatherback Atoll

If you draw two cards in consecutively in a standard deck of 52 cards, what is the probability of getting black on the second draw?

Problem with listing a directory to grep

What makes things real?

How can faith be maintained in a world of living gods?

How invisible hand adjusts stock prices if company is listed on multiple exchanges, under multiple currencies, and one of the currencies plunges?

When did computers stop checking memory on boot?



Distribute value over list


How do I check if a list is empty?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How to make a flat list out of list of listsHow do I get the number of elements in a list?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?Iterating over dictionaries using 'for' loopsWhy not inherit from List<T>?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-1















Given the amount S=25 and list L = [10,20,30] I want to distribute S over L in the following way:
output -> [10, 15, 0]



I wrote the following code, which does the job:



S = 25
l = [10,20,30]
res= []
b = True

for value in l:
if b == True:
if S - value >0:
res.append(value)
else:
res.append(S)
b= False
S -= value
else:
res.append(0)


Is it possible to rewrite it, maybe as a one-liner? (numpy is allowed)










share|improve this question
































    -1















    Given the amount S=25 and list L = [10,20,30] I want to distribute S over L in the following way:
    output -> [10, 15, 0]



    I wrote the following code, which does the job:



    S = 25
    l = [10,20,30]
    res= []
    b = True

    for value in l:
    if b == True:
    if S - value >0:
    res.append(value)
    else:
    res.append(S)
    b= False
    S -= value
    else:
    res.append(0)


    Is it possible to rewrite it, maybe as a one-liner? (numpy is allowed)










    share|improve this question




























      -1












      -1








      -1








      Given the amount S=25 and list L = [10,20,30] I want to distribute S over L in the following way:
      output -> [10, 15, 0]



      I wrote the following code, which does the job:



      S = 25
      l = [10,20,30]
      res= []
      b = True

      for value in l:
      if b == True:
      if S - value >0:
      res.append(value)
      else:
      res.append(S)
      b= False
      S -= value
      else:
      res.append(0)


      Is it possible to rewrite it, maybe as a one-liner? (numpy is allowed)










      share|improve this question
















      Given the amount S=25 and list L = [10,20,30] I want to distribute S over L in the following way:
      output -> [10, 15, 0]



      I wrote the following code, which does the job:



      S = 25
      l = [10,20,30]
      res= []
      b = True

      for value in l:
      if b == True:
      if S - value >0:
      res.append(value)
      else:
      res.append(S)
      b= False
      S -= value
      else:
      res.append(0)


      Is it possible to rewrite it, maybe as a one-liner? (numpy is allowed)







      python list numpy






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '18 at 0:55







      Kirill

















      asked Feb 19 '18 at 0:38









      KirillKirill

      114 bronze badges




      114 bronze badges

























          3 Answers
          3






          active

          oldest

          votes


















          2
















          Slightly shorter and more readable:



          def distribute(S, L):
          res = []
          for e in L:
          res.append(min(e, S))
          S = max(0, S-e)
          return res


          While you can make this (or anything really) a one-liner, I wouldn't force it. It's better to keep things readable.



          You can also use an equivalent generator function:



          def distribute(S, L):
          for e in L:
          yield min(e, S)
          S = max(0, S-e)

          list(distribute(S, l))





          share|improve this answer



























          • I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

            – jpp
            Feb 19 '18 at 1:08











          • I love the latter one. Cool!

            – Kirill
            Feb 19 '18 at 1:10


















          1
















          This is one way, but please do not get attached to one-liners for the sake of them being one-liners. Often they are not the best method, either in terms of readability or performance.



          from itertools import accumulate

          S = 25
          l = [10, 20, 30]

          res = [i if j <= S else max(0, S-k)
          for i, j, k in zip(l, accumulate(l), accumulate([0]+l))]

          # [10, 15, 0]





          share|improve this answer


































            0
















            numpy



            Since OP specifically asked for numpy, let's assume this is about large arrays. I think distribute in the OP subject was a key word, because this is very similar to conversion between PDF and CDF (https://en.wikipedia.org/wiki/Cumulative_distribution_function) and the inverse:



            a = numpy.array([10, 20, 30])
            c = a.cumsum() # [10, 30, 60]
            b = c.clip(0, 25) # [20, 25, 25]
            numpy.ediff1d(b, to_begin=b[0]) # [10, 15, 0]





            share|improve this answer



























              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',
              autoActivateHeartbeat: false,
              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/4.0/"u003ecc by-sa 4.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%2f48858193%2fdistribute-value-over-list%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









              2
















              Slightly shorter and more readable:



              def distribute(S, L):
              res = []
              for e in L:
              res.append(min(e, S))
              S = max(0, S-e)
              return res


              While you can make this (or anything really) a one-liner, I wouldn't force it. It's better to keep things readable.



              You can also use an equivalent generator function:



              def distribute(S, L):
              for e in L:
              yield min(e, S)
              S = max(0, S-e)

              list(distribute(S, l))





              share|improve this answer



























              • I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

                – jpp
                Feb 19 '18 at 1:08











              • I love the latter one. Cool!

                – Kirill
                Feb 19 '18 at 1:10















              2
















              Slightly shorter and more readable:



              def distribute(S, L):
              res = []
              for e in L:
              res.append(min(e, S))
              S = max(0, S-e)
              return res


              While you can make this (or anything really) a one-liner, I wouldn't force it. It's better to keep things readable.



              You can also use an equivalent generator function:



              def distribute(S, L):
              for e in L:
              yield min(e, S)
              S = max(0, S-e)

              list(distribute(S, l))





              share|improve this answer



























              • I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

                – jpp
                Feb 19 '18 at 1:08











              • I love the latter one. Cool!

                – Kirill
                Feb 19 '18 at 1:10













              2














              2










              2









              Slightly shorter and more readable:



              def distribute(S, L):
              res = []
              for e in L:
              res.append(min(e, S))
              S = max(0, S-e)
              return res


              While you can make this (or anything really) a one-liner, I wouldn't force it. It's better to keep things readable.



              You can also use an equivalent generator function:



              def distribute(S, L):
              for e in L:
              yield min(e, S)
              S = max(0, S-e)

              list(distribute(S, l))





              share|improve this answer















              Slightly shorter and more readable:



              def distribute(S, L):
              res = []
              for e in L:
              res.append(min(e, S))
              S = max(0, S-e)
              return res


              While you can make this (or anything really) a one-liner, I wouldn't force it. It's better to keep things readable.



              You can also use an equivalent generator function:



              def distribute(S, L):
              for e in L:
              yield min(e, S)
              S = max(0, S-e)

              list(distribute(S, l))






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 19 '18 at 1:07









              jpp

              107k21 gold badges89 silver badges134 bronze badges




              107k21 gold badges89 silver badges134 bronze badges










              answered Feb 19 '18 at 0:57









              viraptorviraptor

              25.3k7 gold badges82 silver badges155 bronze badges




              25.3k7 gold badges82 silver badges155 bronze badges















              • I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

                – jpp
                Feb 19 '18 at 1:08











              • I love the latter one. Cool!

                – Kirill
                Feb 19 '18 at 1:10

















              • I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

                – jpp
                Feb 19 '18 at 1:08











              • I love the latter one. Cool!

                – Kirill
                Feb 19 '18 at 1:10
















              I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

              – jpp
              Feb 19 '18 at 1:08





              I added a (in my opinion) more pythonic generator. Your solution is still very good. +1

              – jpp
              Feb 19 '18 at 1:08













              I love the latter one. Cool!

              – Kirill
              Feb 19 '18 at 1:10





              I love the latter one. Cool!

              – Kirill
              Feb 19 '18 at 1:10













              1
















              This is one way, but please do not get attached to one-liners for the sake of them being one-liners. Often they are not the best method, either in terms of readability or performance.



              from itertools import accumulate

              S = 25
              l = [10, 20, 30]

              res = [i if j <= S else max(0, S-k)
              for i, j, k in zip(l, accumulate(l), accumulate([0]+l))]

              # [10, 15, 0]





              share|improve this answer































                1
















                This is one way, but please do not get attached to one-liners for the sake of them being one-liners. Often they are not the best method, either in terms of readability or performance.



                from itertools import accumulate

                S = 25
                l = [10, 20, 30]

                res = [i if j <= S else max(0, S-k)
                for i, j, k in zip(l, accumulate(l), accumulate([0]+l))]

                # [10, 15, 0]





                share|improve this answer





























                  1














                  1










                  1









                  This is one way, but please do not get attached to one-liners for the sake of them being one-liners. Often they are not the best method, either in terms of readability or performance.



                  from itertools import accumulate

                  S = 25
                  l = [10, 20, 30]

                  res = [i if j <= S else max(0, S-k)
                  for i, j, k in zip(l, accumulate(l), accumulate([0]+l))]

                  # [10, 15, 0]





                  share|improve this answer















                  This is one way, but please do not get attached to one-liners for the sake of them being one-liners. Often they are not the best method, either in terms of readability or performance.



                  from itertools import accumulate

                  S = 25
                  l = [10, 20, 30]

                  res = [i if j <= S else max(0, S-k)
                  for i, j, k in zip(l, accumulate(l), accumulate([0]+l))]

                  # [10, 15, 0]






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 19 '18 at 1:04

























                  answered Feb 19 '18 at 0:50









                  jppjpp

                  107k21 gold badges89 silver badges134 bronze badges




                  107k21 gold badges89 silver badges134 bronze badges
























                      0
















                      numpy



                      Since OP specifically asked for numpy, let's assume this is about large arrays. I think distribute in the OP subject was a key word, because this is very similar to conversion between PDF and CDF (https://en.wikipedia.org/wiki/Cumulative_distribution_function) and the inverse:



                      a = numpy.array([10, 20, 30])
                      c = a.cumsum() # [10, 30, 60]
                      b = c.clip(0, 25) # [20, 25, 25]
                      numpy.ediff1d(b, to_begin=b[0]) # [10, 15, 0]





                      share|improve this answer





























                        0
















                        numpy



                        Since OP specifically asked for numpy, let's assume this is about large arrays. I think distribute in the OP subject was a key word, because this is very similar to conversion between PDF and CDF (https://en.wikipedia.org/wiki/Cumulative_distribution_function) and the inverse:



                        a = numpy.array([10, 20, 30])
                        c = a.cumsum() # [10, 30, 60]
                        b = c.clip(0, 25) # [20, 25, 25]
                        numpy.ediff1d(b, to_begin=b[0]) # [10, 15, 0]





                        share|improve this answer



























                          0














                          0










                          0









                          numpy



                          Since OP specifically asked for numpy, let's assume this is about large arrays. I think distribute in the OP subject was a key word, because this is very similar to conversion between PDF and CDF (https://en.wikipedia.org/wiki/Cumulative_distribution_function) and the inverse:



                          a = numpy.array([10, 20, 30])
                          c = a.cumsum() # [10, 30, 60]
                          b = c.clip(0, 25) # [20, 25, 25]
                          numpy.ediff1d(b, to_begin=b[0]) # [10, 15, 0]





                          share|improve this answer













                          numpy



                          Since OP specifically asked for numpy, let's assume this is about large arrays. I think distribute in the OP subject was a key word, because this is very similar to conversion between PDF and CDF (https://en.wikipedia.org/wiki/Cumulative_distribution_function) and the inverse:



                          a = numpy.array([10, 20, 30])
                          c = a.cumsum() # [10, 30, 60]
                          b = c.clip(0, 25) # [20, 25, 25]
                          numpy.ediff1d(b, to_begin=b[0]) # [10, 15, 0]






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 28 at 7:32









                          Dima TisnekDima Tisnek

                          7,4332 gold badges38 silver badges87 bronze badges




                          7,4332 gold badges38 silver badges87 bronze badges































                              draft saved

                              draft discarded















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f48858193%2fdistribute-value-over-list%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript