Writing a function that alternates plus and minus signs between list indices









up vote
4
down vote

favorite
2












In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:




"Write a function alternate : int list -> int that takes a list of
numbers and adds them with alternating sign. For example alternate
[1,2,3,4] = 1 - 2 + 3 - 4 = -2."




Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:



splitting the list,



if [i] % 2 == 0:


and then concatenating the alternate plus and minus signs.










share|improve this question





















  • write down how you would approach, a code that you wrote and failed may be then we can help you out.
    – Ja8zyjits
    Dec 27 '16 at 5:59














up vote
4
down vote

favorite
2












In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:




"Write a function alternate : int list -> int that takes a list of
numbers and adds them with alternating sign. For example alternate
[1,2,3,4] = 1 - 2 + 3 - 4 = -2."




Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:



splitting the list,



if [i] % 2 == 0:


and then concatenating the alternate plus and minus signs.










share|improve this question





















  • write down how you would approach, a code that you wrote and failed may be then we can help you out.
    – Ja8zyjits
    Dec 27 '16 at 5:59












up vote
4
down vote

favorite
2









up vote
4
down vote

favorite
2






2





In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:




"Write a function alternate : int list -> int that takes a list of
numbers and adds them with alternating sign. For example alternate
[1,2,3,4] = 1 - 2 + 3 - 4 = -2."




Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:



splitting the list,



if [i] % 2 == 0:


and then concatenating the alternate plus and minus signs.










share|improve this question













In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:




"Write a function alternate : int list -> int that takes a list of
numbers and adds them with alternating sign. For example alternate
[1,2,3,4] = 1 - 2 + 3 - 4 = -2."




Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:



splitting the list,



if [i] % 2 == 0:


and then concatenating the alternate plus and minus signs.







python list python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 27 '16 at 5:56









A. Chiasson

286




286











  • write down how you would approach, a code that you wrote and failed may be then we can help you out.
    – Ja8zyjits
    Dec 27 '16 at 5:59
















  • write down how you would approach, a code that you wrote and failed may be then we can help you out.
    – Ja8zyjits
    Dec 27 '16 at 5:59















write down how you would approach, a code that you wrote and failed may be then we can help you out.
– Ja8zyjits
Dec 27 '16 at 5:59




write down how you would approach, a code that you wrote and failed may be then we can help you out.
– Ja8zyjits
Dec 27 '16 at 5:59












6 Answers
6






active

oldest

votes

















up vote
7
down vote



accepted










def alternate(l):
return sum(l[::2]) - sum(l[1::2])


Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.



References:



  • list slice examples

  • sum()





share|improve this answer





























    up vote
    3
    down vote













    Not using fancy modules or operators since you are learning Python.



    >>> mylist = range(2,20,3)
    >>> mylist
    [2, 5, 8, 11, 14, 17]
    >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
    -9
    >>>


    How it works?



    >>> mylist = range(2,20,3)
    >>> mylist
    [2, 5, 8, 11, 14, 17]


    enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1



    If the index is odd, then add the item. If the index is even add the negative of the item.



    if i%2:
    return item
    else:
    return -1*item


    Add everything using sum bulitin.



    >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
    -9
    >>>





    share|improve this answer





























      up vote
      1
      down vote













      Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.



      def alt_sum(lst):
      total = 0
      for i, value in enumerate(lst):
      # checks if current index is odd or even
      # if even then add, if odd then subtract
      if i % 2 == 0:
      total += value
      else:
      total -= value
      return total

      >>> alt_sum([1, 2, 3, 4])
      -2





      share|improve this answer



























        up vote
        1
        down vote













        my_list = range(3, 20, 2)
        sum(item * ((-1)**index) for index, item in enumerate(my_list))


        sum = 11 (result of 3-5+7-9+11-13+15-17+19)






        share|improve this answer



























          up vote
          1
          down vote













          You could try this list comprehension:



          sum([-e if c%2 else e for c,e in enumerate(yourlistylist)])





          share|improve this answer



























            up vote
            1
            down vote













            Here is one way using operator module:



            In [21]: from operator import pos, neg

            In [23]: ops = (pos, neg)

            In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
            Out[24]: -2





            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',
              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%2f41339744%2fwriting-a-function-that-alternates-plus-and-minus-signs-between-list-indices%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              7
              down vote



              accepted










              def alternate(l):
              return sum(l[::2]) - sum(l[1::2])


              Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.



              References:



              • list slice examples

              • sum()





              share|improve this answer


























                up vote
                7
                down vote



                accepted










                def alternate(l):
                return sum(l[::2]) - sum(l[1::2])


                Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.



                References:



                • list slice examples

                • sum()





                share|improve this answer
























                  up vote
                  7
                  down vote



                  accepted







                  up vote
                  7
                  down vote



                  accepted






                  def alternate(l):
                  return sum(l[::2]) - sum(l[1::2])


                  Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.



                  References:



                  • list slice examples

                  • sum()





                  share|improve this answer














                  def alternate(l):
                  return sum(l[::2]) - sum(l[1::2])


                  Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0 so it coincidently handles lists of length 0 or 1 without code specifically for those cases.



                  References:



                  • list slice examples

                  • sum()






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 10 at 14:01

























                  answered Dec 27 '16 at 6:15









                  Ouroborus

                  6,1411533




                  6,1411533






















                      up vote
                      3
                      down vote













                      Not using fancy modules or operators since you are learning Python.



                      >>> mylist = range(2,20,3)
                      >>> mylist
                      [2, 5, 8, 11, 14, 17]
                      >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                      -9
                      >>>


                      How it works?



                      >>> mylist = range(2,20,3)
                      >>> mylist
                      [2, 5, 8, 11, 14, 17]


                      enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1



                      If the index is odd, then add the item. If the index is even add the negative of the item.



                      if i%2:
                      return item
                      else:
                      return -1*item


                      Add everything using sum bulitin.



                      >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                      -9
                      >>>





                      share|improve this answer


























                        up vote
                        3
                        down vote













                        Not using fancy modules or operators since you are learning Python.



                        >>> mylist = range(2,20,3)
                        >>> mylist
                        [2, 5, 8, 11, 14, 17]
                        >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                        -9
                        >>>


                        How it works?



                        >>> mylist = range(2,20,3)
                        >>> mylist
                        [2, 5, 8, 11, 14, 17]


                        enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1



                        If the index is odd, then add the item. If the index is even add the negative of the item.



                        if i%2:
                        return item
                        else:
                        return -1*item


                        Add everything using sum bulitin.



                        >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                        -9
                        >>>





                        share|improve this answer
























                          up vote
                          3
                          down vote










                          up vote
                          3
                          down vote









                          Not using fancy modules or operators since you are learning Python.



                          >>> mylist = range(2,20,3)
                          >>> mylist
                          [2, 5, 8, 11, 14, 17]
                          >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                          -9
                          >>>


                          How it works?



                          >>> mylist = range(2,20,3)
                          >>> mylist
                          [2, 5, 8, 11, 14, 17]


                          enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1



                          If the index is odd, then add the item. If the index is even add the negative of the item.



                          if i%2:
                          return item
                          else:
                          return -1*item


                          Add everything using sum bulitin.



                          >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                          -9
                          >>>





                          share|improve this answer














                          Not using fancy modules or operators since you are learning Python.



                          >>> mylist = range(2,20,3)
                          >>> mylist
                          [2, 5, 8, 11, 14, 17]
                          >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                          -9
                          >>>


                          How it works?



                          >>> mylist = range(2,20,3)
                          >>> mylist
                          [2, 5, 8, 11, 14, 17]


                          enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1



                          If the index is odd, then add the item. If the index is even add the negative of the item.



                          if i%2:
                          return item
                          else:
                          return -1*item


                          Add everything using sum bulitin.



                          >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
                          -9
                          >>>






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Dec 27 '16 at 6:25

























                          answered Dec 27 '16 at 6:18









                          helloV

                          28.7k34074




                          28.7k34074




















                              up vote
                              1
                              down vote













                              Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.



                              def alt_sum(lst):
                              total = 0
                              for i, value in enumerate(lst):
                              # checks if current index is odd or even
                              # if even then add, if odd then subtract
                              if i % 2 == 0:
                              total += value
                              else:
                              total -= value
                              return total

                              >>> alt_sum([1, 2, 3, 4])
                              -2





                              share|improve this answer
























                                up vote
                                1
                                down vote













                                Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.



                                def alt_sum(lst):
                                total = 0
                                for i, value in enumerate(lst):
                                # checks if current index is odd or even
                                # if even then add, if odd then subtract
                                if i % 2 == 0:
                                total += value
                                else:
                                total -= value
                                return total

                                >>> alt_sum([1, 2, 3, 4])
                                -2





                                share|improve this answer






















                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.



                                  def alt_sum(lst):
                                  total = 0
                                  for i, value in enumerate(lst):
                                  # checks if current index is odd or even
                                  # if even then add, if odd then subtract
                                  if i % 2 == 0:
                                  total += value
                                  else:
                                  total -= value
                                  return total

                                  >>> alt_sum([1, 2, 3, 4])
                                  -2





                                  share|improve this answer












                                  Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.



                                  def alt_sum(lst):
                                  total = 0
                                  for i, value in enumerate(lst):
                                  # checks if current index is odd or even
                                  # if even then add, if odd then subtract
                                  if i % 2 == 0:
                                  total += value
                                  else:
                                  total -= value
                                  return total

                                  >>> alt_sum([1, 2, 3, 4])
                                  -2






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 27 '16 at 7:14









                                  Steven Summers

                                  3,60121022




                                  3,60121022




















                                      up vote
                                      1
                                      down vote













                                      my_list = range(3, 20, 2)
                                      sum(item * ((-1)**index) for index, item in enumerate(my_list))


                                      sum = 11 (result of 3-5+7-9+11-13+15-17+19)






                                      share|improve this answer
























                                        up vote
                                        1
                                        down vote













                                        my_list = range(3, 20, 2)
                                        sum(item * ((-1)**index) for index, item in enumerate(my_list))


                                        sum = 11 (result of 3-5+7-9+11-13+15-17+19)






                                        share|improve this answer






















                                          up vote
                                          1
                                          down vote










                                          up vote
                                          1
                                          down vote









                                          my_list = range(3, 20, 2)
                                          sum(item * ((-1)**index) for index, item in enumerate(my_list))


                                          sum = 11 (result of 3-5+7-9+11-13+15-17+19)






                                          share|improve this answer












                                          my_list = range(3, 20, 2)
                                          sum(item * ((-1)**index) for index, item in enumerate(my_list))


                                          sum = 11 (result of 3-5+7-9+11-13+15-17+19)







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Sep 17 '17 at 16:44









                                          Seshadri R

                                          407313




                                          407313




















                                              up vote
                                              1
                                              down vote













                                              You could try this list comprehension:



                                              sum([-e if c%2 else e for c,e in enumerate(yourlistylist)])





                                              share|improve this answer
























                                                up vote
                                                1
                                                down vote













                                                You could try this list comprehension:



                                                sum([-e if c%2 else e for c,e in enumerate(yourlistylist)])





                                                share|improve this answer






















                                                  up vote
                                                  1
                                                  down vote










                                                  up vote
                                                  1
                                                  down vote









                                                  You could try this list comprehension:



                                                  sum([-e if c%2 else e for c,e in enumerate(yourlistylist)])





                                                  share|improve this answer












                                                  You could try this list comprehension:



                                                  sum([-e if c%2 else e for c,e in enumerate(yourlistylist)])






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jun 26 at 3:13









                                                  ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000

                                                  4,64541230




                                                  4,64541230




















                                                      up vote
                                                      1
                                                      down vote













                                                      Here is one way using operator module:



                                                      In [21]: from operator import pos, neg

                                                      In [23]: ops = (pos, neg)

                                                      In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
                                                      Out[24]: -2





                                                      share|improve this answer


























                                                        up vote
                                                        1
                                                        down vote













                                                        Here is one way using operator module:



                                                        In [21]: from operator import pos, neg

                                                        In [23]: ops = (pos, neg)

                                                        In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
                                                        Out[24]: -2





                                                        share|improve this answer
























                                                          up vote
                                                          1
                                                          down vote










                                                          up vote
                                                          1
                                                          down vote









                                                          Here is one way using operator module:



                                                          In [21]: from operator import pos, neg

                                                          In [23]: ops = (pos, neg)

                                                          In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
                                                          Out[24]: -2





                                                          share|improve this answer














                                                          Here is one way using operator module:



                                                          In [21]: from operator import pos, neg

                                                          In [23]: ops = (pos, neg)

                                                          In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
                                                          Out[24]: -2






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jun 26 at 5:42

























                                                          answered Dec 27 '16 at 6:08









                                                          Kasrâmvd

                                                          76.6k1088121




                                                          76.6k1088121



























                                                               

                                                              draft saved


                                                              draft discarded















































                                                               


                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function ()
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41339744%2fwriting-a-function-that-alternates-plus-and-minus-signs-between-list-indices%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







                                                              這個網誌中的熱門文章

                                                              How to read a connectionString WITH PROVIDER in .NET Core?

                                                              Node.js Script on GitHub Pages or Amazon S3

                                                              Museum of Modern and Contemporary Art of Trento and Rovereto