Split a number into equal parts given the number of partsSplit Django into appsUtility function to split a number into n parts in the given ratioSplit large file into smaller filesCategorizing gene sequences read from a CSV fileSplit up an iterable into batchesSplitting the coordinates of the world into equal blocksSplit mp3 of album into individual tracksGenerating a bytearray by choosing an exclusive set of parametersSplit a given number so that their sum adds to another given numberGiven 4 vertices representing a quadrilateral, divide it into N parts
Can anyone tell me why this program fails?
Does the statement `int val = (++i > ++j) ? ++i : ++j;` invoke undefined behavior?
How to make healing in an exploration game interesting
Why are the outputs of printf and std::cout different
How to simplify this time periods definition interface?
Replacing Windows 7 security updates with anti-virus?
Rules about breaking the rules. How do I do it well?
Why are there 40 737 Max planes in flight when they have been grounded as not airworthy?
Theorems like the Lovász Local Lemma?
Identifying the interval from A♭ to D♯
My adviser wants to be the first author
Is it possible / allowed to upcast ritual spells?
Informing my boss about remarks from a nasty colleague
Why must traveling waves have the same amplitude to form a standing wave?
Professor being mistaken for a grad student
How do anti-virus programs start at Windows boot?
Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?
Making a sword in the stone, in a medieval world without magic
How to write cleanly even if my character uses expletive language?
Is it possible that AIC = BIC?
How to deal with a cynical class?
What is IP squat space
Does splitting a potentially monolithic application into several smaller ones help prevent bugs?
Should we release the security issues we found in our product as CVE or we can just update those on weekly release notes?
Split a number into equal parts given the number of parts
Split Django into appsUtility function to split a number into n parts in the given ratioSplit large file into smaller filesCategorizing gene sequences read from a CSV fileSplit up an iterable into batchesSplitting the coordinates of the world into equal blocksSplit mp3 of album into individual tracksGenerating a bytearray by choosing an exclusive set of parametersSplit a given number so that their sum adds to another given numberGiven 4 vertices representing a quadrilateral, divide it into N parts
$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]]
python python-3.x
$endgroup$
add a comment |
$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]]
python python-3.x
$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
add a comment |
$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]]
python python-3.x
$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
python python-3.x
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
add a comment |
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
add a comment |
4 Answers
4
active
oldest
votes
$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)]
$endgroup$
add a comment |
$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)
$endgroup$
add a comment |
$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)))
$endgroup$
add a comment |
$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
.
$endgroup$
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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)]
$endgroup$
add a comment |
$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)]
$endgroup$
add a comment |
$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)]
$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)]
answered Mar 6 at 18:43
200_success200_success
130k17153419
130k17153419
add a comment |
add a comment |
$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)
$endgroup$
add a comment |
$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)
$endgroup$
add a comment |
$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)
$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)
answered Mar 6 at 18:02
JosayJosay
26k14087
26k14087
add a comment |
add a comment |
$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)))
$endgroup$
add a comment |
$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)))
$endgroup$
add a comment |
$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)))
$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)))
answered Mar 6 at 17:58
PeilonrayzPeilonrayz
25.7k338109
25.7k338109
add a comment |
add a comment |
$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
.
$endgroup$
add a comment |
$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
.
$endgroup$
add a comment |
$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
.
$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
.
edited Mar 6 at 20:01
answered Mar 6 at 17:58
CarcigenicateCarcigenicate
3,76311632
3,76311632
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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