Split a number into equal parts given the number of parts












11












$begingroup$


I want to split a song into multiple parts, given the song duration and number of parts.



My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions.



song_duration = 20 # these two 
num_of_parts = 4 # are given

part_duration = song_duration / num_of_parts
parts =
marker = 0

for _ in range(num_of_parts):
part = [marker, marker + part_duration]
marker += part_duration
parts.append(part)

print(parts)

# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]









share|improve this question











$endgroup$








  • 1




    $begingroup$
    Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
    $endgroup$
    – Josay
    Mar 6 at 17:52






  • 1




    $begingroup$
    Thanks for the warm welcome:). Yes, I am using Python 3.
    $endgroup$
    – barciewicz
    Mar 6 at 17:57


















11












$begingroup$


I want to split a song into multiple parts, given the song duration and number of parts.



My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions.



song_duration = 20 # these two 
num_of_parts = 4 # are given

part_duration = song_duration / num_of_parts
parts =
marker = 0

for _ in range(num_of_parts):
part = [marker, marker + part_duration]
marker += part_duration
parts.append(part)

print(parts)

# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]









share|improve this question











$endgroup$








  • 1




    $begingroup$
    Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
    $endgroup$
    – Josay
    Mar 6 at 17:52






  • 1




    $begingroup$
    Thanks for the warm welcome:). Yes, I am using Python 3.
    $endgroup$
    – barciewicz
    Mar 6 at 17:57
















11












11








11


1



$begingroup$


I want to split a song into multiple parts, given the song duration and number of parts.



My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions.



song_duration = 20 # these two 
num_of_parts = 4 # are given

part_duration = song_duration / num_of_parts
parts =
marker = 0

for _ in range(num_of_parts):
part = [marker, marker + part_duration]
marker += part_duration
parts.append(part)

print(parts)

# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]









share|improve this question











$endgroup$




I want to split a song into multiple parts, given the song duration and number of parts.



My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions.



song_duration = 20 # these two 
num_of_parts = 4 # are given

part_duration = song_duration / num_of_parts
parts =
marker = 0

for _ in range(num_of_parts):
part = [marker, marker + part_duration]
marker += part_duration
parts.append(part)

print(parts)

# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]






python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 at 20:23









chicks

1,5832919




1,5832919










asked Mar 6 at 17:45









barciewiczbarciewicz

1906




1906








  • 1




    $begingroup$
    Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
    $endgroup$
    – Josay
    Mar 6 at 17:52






  • 1




    $begingroup$
    Thanks for the warm welcome:). Yes, I am using Python 3.
    $endgroup$
    – barciewicz
    Mar 6 at 17:57
















  • 1




    $begingroup$
    Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
    $endgroup$
    – Josay
    Mar 6 at 17:52






  • 1




    $begingroup$
    Thanks for the warm welcome:). Yes, I am using Python 3.
    $endgroup$
    – barciewicz
    Mar 6 at 17:57










1




1




$begingroup$
Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
$endgroup$
– Josay
Mar 6 at 17:52




$begingroup$
Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)
$endgroup$
– Josay
Mar 6 at 17:52




1




1




$begingroup$
Thanks for the warm welcome:). Yes, I am using Python 3.
$endgroup$
– barciewicz
Mar 6 at 17:57






$begingroup$
Thanks for the warm welcome:). Yes, I am using Python 3.
$endgroup$
– barciewicz
Mar 6 at 17:57












4 Answers
4






active

oldest

votes


















11












$begingroup$

In general, building a list using a loop of the form




some_list = 
for …:
some_list.append(…)



… would be better written using a list comprehension.



Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as tuples instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)



Finally, I'd package the code into a function.



def intervals(parts, duration):
part_duration = duration / parts
return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]





share|improve this answer









$endgroup$





















    7












    $begingroup$

    Here are a few suggestions.



    Write a function



    Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.



    def split_song(song_duration, num_of_parts):
    """Returns parts when a song of duration song_duration is split into num_of_parts parts."""
    part_duration = song_duration / num_of_parts
    parts =
    marker = 0

    for _ in range(num_of_parts):
    part = [marker, marker + part_duration]
    marker += part_duration
    parts.append(part)
    return parts

    assert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
    assert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]


    Proper data structure



    You are returning a list of list. In Python, there is a cultural difference in how tuple and list are used.



    In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.



    part = (marker, marker + part_duration)





    share|improve this answer









    $endgroup$





















      6












      $begingroup$

      Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the pairwise recipe:



      def pairwise(iterable):
      "s -> (s0,s1), (s1,s2), (s2, s3), ..."
      a, b = tee(iterable)
      next(b, None)
      return zip(a, b)


      From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:



      part_duration = song_duration / num_of_parts
      parts = [i * part_duration for i in range(num_of_parts + 1)]




      import itertools

      def pairwise(iterable):
      "s -> (s0,s1), (s1,s2), (s2, s3), ..."
      a, b = itertools.tee(iterable)
      next(b, None)
      return zip(a, b)

      def song_segments(duration, segments):
      delta = duration / segments
      return pairwise([i * delta for i in range(segments + 1)])


      print(list(song_segments(20, 4)))





      share|improve this answer









      $endgroup$





















        6












        $begingroup$

        A few things:



        First, you can make use of the third parameter of range, which is the step, IF you can guarantee that part_duration is an integer (which is the case for the example you posted here):



        # Integer division
        part_duration = song_duration // num_of_parts
        parts =

        # I rearranged this a bit too
        for i in range(0, song_duration, part_duration):
        part = [i, i + part_duration]
        parts.append(part)

        print(parts)
        # [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers


        Note how this is just a transformation from a range to a list though. If you're transforming one collection to a list, list comprehensions should come to mind:



        # List comprehension split over two lines
        parts = [[i, i + part_duration]
        for i in range(0, song_duration, part_duration)]

        print(parts)
        # [[0, 5], [5, 10], [10, 15], [15, 20]]




        If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its range.






        share|improve this answer











        $endgroup$













          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          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: "196"
          };
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fcodereview.stackexchange.com%2fquestions%2f214857%2fsplit-a-number-into-equal-parts-given-the-number-of-parts%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          11












          $begingroup$

          In general, building a list using a loop of the form




          some_list = 
          for …:
          some_list.append(…)



          … would be better written using a list comprehension.



          Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as tuples instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)



          Finally, I'd package the code into a function.



          def intervals(parts, duration):
          part_duration = duration / parts
          return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]





          share|improve this answer









          $endgroup$


















            11












            $begingroup$

            In general, building a list using a loop of the form




            some_list = 
            for …:
            some_list.append(…)



            … would be better written using a list comprehension.



            Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as tuples instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)



            Finally, I'd package the code into a function.



            def intervals(parts, duration):
            part_duration = duration / parts
            return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]





            share|improve this answer









            $endgroup$
















              11












              11








              11





              $begingroup$

              In general, building a list using a loop of the form




              some_list = 
              for …:
              some_list.append(…)



              … would be better written using a list comprehension.



              Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as tuples instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)



              Finally, I'd package the code into a function.



              def intervals(parts, duration):
              part_duration = duration / parts
              return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]





              share|improve this answer









              $endgroup$



              In general, building a list using a loop of the form




              some_list = 
              for …:
              some_list.append(…)



              … would be better written using a list comprehension.



              Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as tuples instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)



              Finally, I'd package the code into a function.



              def intervals(parts, duration):
              part_duration = duration / parts
              return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 6 at 18:43









              200_success200_success

              130k17153419




              130k17153419

























                  7












                  $begingroup$

                  Here are a few suggestions.



                  Write a function



                  Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.



                  def split_song(song_duration, num_of_parts):
                  """Returns parts when a song of duration song_duration is split into num_of_parts parts."""
                  part_duration = song_duration / num_of_parts
                  parts =
                  marker = 0

                  for _ in range(num_of_parts):
                  part = [marker, marker + part_duration]
                  marker += part_duration
                  parts.append(part)
                  return parts

                  assert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
                  assert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]


                  Proper data structure



                  You are returning a list of list. In Python, there is a cultural difference in how tuple and list are used.



                  In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.



                  part = (marker, marker + part_duration)





                  share|improve this answer









                  $endgroup$


















                    7












                    $begingroup$

                    Here are a few suggestions.



                    Write a function



                    Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.



                    def split_song(song_duration, num_of_parts):
                    """Returns parts when a song of duration song_duration is split into num_of_parts parts."""
                    part_duration = song_duration / num_of_parts
                    parts =
                    marker = 0

                    for _ in range(num_of_parts):
                    part = [marker, marker + part_duration]
                    marker += part_duration
                    parts.append(part)
                    return parts

                    assert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
                    assert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]


                    Proper data structure



                    You are returning a list of list. In Python, there is a cultural difference in how tuple and list are used.



                    In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.



                    part = (marker, marker + part_duration)





                    share|improve this answer









                    $endgroup$
















                      7












                      7








                      7





                      $begingroup$

                      Here are a few suggestions.



                      Write a function



                      Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.



                      def split_song(song_duration, num_of_parts):
                      """Returns parts when a song of duration song_duration is split into num_of_parts parts."""
                      part_duration = song_duration / num_of_parts
                      parts =
                      marker = 0

                      for _ in range(num_of_parts):
                      part = [marker, marker + part_duration]
                      marker += part_duration
                      parts.append(part)
                      return parts

                      assert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
                      assert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]


                      Proper data structure



                      You are returning a list of list. In Python, there is a cultural difference in how tuple and list are used.



                      In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.



                      part = (marker, marker + part_duration)





                      share|improve this answer









                      $endgroup$



                      Here are a few suggestions.



                      Write a function



                      Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.



                      def split_song(song_duration, num_of_parts):
                      """Returns parts when a song of duration song_duration is split into num_of_parts parts."""
                      part_duration = song_duration / num_of_parts
                      parts =
                      marker = 0

                      for _ in range(num_of_parts):
                      part = [marker, marker + part_duration]
                      marker += part_duration
                      parts.append(part)
                      return parts

                      assert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
                      assert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]


                      Proper data structure



                      You are returning a list of list. In Python, there is a cultural difference in how tuple and list are used.



                      In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.



                      part = (marker, marker + part_duration)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 6 at 18:02









                      JosayJosay

                      26k14087




                      26k14087























                          6












                          $begingroup$

                          Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the pairwise recipe:



                          def pairwise(iterable):
                          "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                          a, b = tee(iterable)
                          next(b, None)
                          return zip(a, b)


                          From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:



                          part_duration = song_duration / num_of_parts
                          parts = [i * part_duration for i in range(num_of_parts + 1)]




                          import itertools

                          def pairwise(iterable):
                          "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                          a, b = itertools.tee(iterable)
                          next(b, None)
                          return zip(a, b)

                          def song_segments(duration, segments):
                          delta = duration / segments
                          return pairwise([i * delta for i in range(segments + 1)])


                          print(list(song_segments(20, 4)))





                          share|improve this answer









                          $endgroup$


















                            6












                            $begingroup$

                            Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the pairwise recipe:



                            def pairwise(iterable):
                            "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                            a, b = tee(iterable)
                            next(b, None)
                            return zip(a, b)


                            From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:



                            part_duration = song_duration / num_of_parts
                            parts = [i * part_duration for i in range(num_of_parts + 1)]




                            import itertools

                            def pairwise(iterable):
                            "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                            a, b = itertools.tee(iterable)
                            next(b, None)
                            return zip(a, b)

                            def song_segments(duration, segments):
                            delta = duration / segments
                            return pairwise([i * delta for i in range(segments + 1)])


                            print(list(song_segments(20, 4)))





                            share|improve this answer









                            $endgroup$
















                              6












                              6








                              6





                              $begingroup$

                              Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the pairwise recipe:



                              def pairwise(iterable):
                              "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                              a, b = tee(iterable)
                              next(b, None)
                              return zip(a, b)


                              From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:



                              part_duration = song_duration / num_of_parts
                              parts = [i * part_duration for i in range(num_of_parts + 1)]




                              import itertools

                              def pairwise(iterable):
                              "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                              a, b = itertools.tee(iterable)
                              next(b, None)
                              return zip(a, b)

                              def song_segments(duration, segments):
                              delta = duration / segments
                              return pairwise([i * delta for i in range(segments + 1)])


                              print(list(song_segments(20, 4)))





                              share|improve this answer









                              $endgroup$



                              Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the pairwise recipe:



                              def pairwise(iterable):
                              "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                              a, b = tee(iterable)
                              next(b, None)
                              return zip(a, b)


                              From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:



                              part_duration = song_duration / num_of_parts
                              parts = [i * part_duration for i in range(num_of_parts + 1)]




                              import itertools

                              def pairwise(iterable):
                              "s -> (s0,s1), (s1,s2), (s2, s3), ..."
                              a, b = itertools.tee(iterable)
                              next(b, None)
                              return zip(a, b)

                              def song_segments(duration, segments):
                              delta = duration / segments
                              return pairwise([i * delta for i in range(segments + 1)])


                              print(list(song_segments(20, 4)))






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 6 at 17:58









                              PeilonrayzPeilonrayz

                              25.7k338109




                              25.7k338109























                                  6












                                  $begingroup$

                                  A few things:



                                  First, you can make use of the third parameter of range, which is the step, IF you can guarantee that part_duration is an integer (which is the case for the example you posted here):



                                  # Integer division
                                  part_duration = song_duration // num_of_parts
                                  parts =

                                  # I rearranged this a bit too
                                  for i in range(0, song_duration, part_duration):
                                  part = [i, i + part_duration]
                                  parts.append(part)

                                  print(parts)
                                  # [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers


                                  Note how this is just a transformation from a range to a list though. If you're transforming one collection to a list, list comprehensions should come to mind:



                                  # List comprehension split over two lines
                                  parts = [[i, i + part_duration]
                                  for i in range(0, song_duration, part_duration)]

                                  print(parts)
                                  # [[0, 5], [5, 10], [10, 15], [15, 20]]




                                  If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its range.






                                  share|improve this answer











                                  $endgroup$


















                                    6












                                    $begingroup$

                                    A few things:



                                    First, you can make use of the third parameter of range, which is the step, IF you can guarantee that part_duration is an integer (which is the case for the example you posted here):



                                    # Integer division
                                    part_duration = song_duration // num_of_parts
                                    parts =

                                    # I rearranged this a bit too
                                    for i in range(0, song_duration, part_duration):
                                    part = [i, i + part_duration]
                                    parts.append(part)

                                    print(parts)
                                    # [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers


                                    Note how this is just a transformation from a range to a list though. If you're transforming one collection to a list, list comprehensions should come to mind:



                                    # List comprehension split over two lines
                                    parts = [[i, i + part_duration]
                                    for i in range(0, song_duration, part_duration)]

                                    print(parts)
                                    # [[0, 5], [5, 10], [10, 15], [15, 20]]




                                    If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its range.






                                    share|improve this answer











                                    $endgroup$
















                                      6












                                      6








                                      6





                                      $begingroup$

                                      A few things:



                                      First, you can make use of the third parameter of range, which is the step, IF you can guarantee that part_duration is an integer (which is the case for the example you posted here):



                                      # Integer division
                                      part_duration = song_duration // num_of_parts
                                      parts =

                                      # I rearranged this a bit too
                                      for i in range(0, song_duration, part_duration):
                                      part = [i, i + part_duration]
                                      parts.append(part)

                                      print(parts)
                                      # [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers


                                      Note how this is just a transformation from a range to a list though. If you're transforming one collection to a list, list comprehensions should come to mind:



                                      # List comprehension split over two lines
                                      parts = [[i, i + part_duration]
                                      for i in range(0, song_duration, part_duration)]

                                      print(parts)
                                      # [[0, 5], [5, 10], [10, 15], [15, 20]]




                                      If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its range.






                                      share|improve this answer











                                      $endgroup$



                                      A few things:



                                      First, you can make use of the third parameter of range, which is the step, IF you can guarantee that part_duration is an integer (which is the case for the example you posted here):



                                      # Integer division
                                      part_duration = song_duration // num_of_parts
                                      parts =

                                      # I rearranged this a bit too
                                      for i in range(0, song_duration, part_duration):
                                      part = [i, i + part_duration]
                                      parts.append(part)

                                      print(parts)
                                      # [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers


                                      Note how this is just a transformation from a range to a list though. If you're transforming one collection to a list, list comprehensions should come to mind:



                                      # List comprehension split over two lines
                                      parts = [[i, i + part_duration]
                                      for i in range(0, song_duration, part_duration)]

                                      print(parts)
                                      # [[0, 5], [5, 10], [10, 15], [15, 20]]




                                      If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its range.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Mar 6 at 20:01

























                                      answered Mar 6 at 17:58









                                      CarcigenicateCarcigenicate

                                      3,76311632




                                      3,76311632






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Code Review Stack Exchange!


                                          • 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.


                                          Use MathJax to format equations. MathJax reference.


                                          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%2fcodereview.stackexchange.com%2fquestions%2f214857%2fsplit-a-number-into-equal-parts-given-the-number-of-parts%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 change which sound is reproduced for terminal bell?

                                          Can I use Tabulator js library in my java Spring + Thymeleaf project?

                                          Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents