Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1Find the smallest regular number that is not less than N (Python)Streamlining a method to run fasterGenerating formatted multiplication tables in C++Printing longest sequence of zeroesCustomizable Multi-Agent Predator/Prey Simulation2D array inquiriesEnsuring performance of sketching/streaming algorithm (countSketch)Finding the position in a triangle for the given challengeFinding a key from values (which are list) in dictProgram for CodeHS 8.3.8: Word Ladder in Python 3
On a piano, are the effects of holding notes and the sustain pedal the same for a single chord?
Is there a way to generate a mapping graph like this?
Was murdering a slave illegal in American slavery, and if so, what punishments were given for it?
Good examples of "two is easy, three is hard" in computational sciences
How could Dwarves prevent sand from filling up their settlements
Salesforce bug enabled "Modify All"
What does "bella ciao" mean literally?
How can I prevent Bash expansion from passing files starting with "-" as argument?
Working hours and productivity expectations for game artists and programmers
Mark’s father’s name
Is being an extrovert a necessary condition to be a manager?
Eigenvalues of the Laplace-Beltrami operator on a compact Riemannnian manifold
Germany rejected my entry to Schengen countries
Find this seven digit phone number under certain conditions
Does the Aboleth have expertise in History and Perception?
Do most Taxis give Receipts in London?
How to say "invitation for war"?
HoD says group project may be rejected. How to mitigate?
Is there a word for pant sleeves?
Are there any nuances between "dismiss" and "ignore"?
Gambler's Fallacy Dice
No Active Recurring Contributions on civi record but stripe has the data. Is there a way to resend IPN?
How can sister protect herself from impulse purchases with a credit card?
Warped chessboard
Program for finding longest run of zeros from a list of 100 random integers which are either 0 or 1
Find the smallest regular number that is not less than N (Python)Streamlining a method to run fasterGenerating formatted multiplication tables in C++Printing longest sequence of zeroesCustomizable Multi-Agent Predator/Prey Simulation2D array inquiriesEnsuring performance of sketching/streaming algorithm (countSketch)Finding the position in a triangle for the given challengeFinding a key from values (which are list) in dictProgram for CodeHS 8.3.8: Word Ladder in Python 3
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.
Write a program that generates 100 random integers that are either
0
or1.
Then find the:
- longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0]is
4.
My answer to this is:
import random
l = []
def my_list():
for j in range(0,100):
x = random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
max_count = 0
for j in l:
if j == 0:
c += 1
else:
if c > max_count:
max_count = c
c = 0
return max_count
l = my_list()
print(largest_row_of_zeros(l))
NOTE: I have changed zero_count to max_count as it sounds more sensible. It keeps track of the max_count (or the largest number of zeros in a row) seen so far, and if a number is not 0, it resets the value of c (count) to 0 after updating the value of max_count with a new value.
So, I would like to know whether I could make this code shorter and more efficient.
Any help would be highly appreciated.
python performance python-3.x
$endgroup$
|
show 4 more comments
$begingroup$
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.
Write a program that generates 100 random integers that are either
0
or1.
Then find the:
- longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0]is
4.
My answer to this is:
import random
l = []
def my_list():
for j in range(0,100):
x = random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
max_count = 0
for j in l:
if j == 0:
c += 1
else:
if c > max_count:
max_count = c
c = 0
return max_count
l = my_list()
print(largest_row_of_zeros(l))
NOTE: I have changed zero_count to max_count as it sounds more sensible. It keeps track of the max_count (or the largest number of zeros in a row) seen so far, and if a number is not 0, it resets the value of c (count) to 0 after updating the value of max_count with a new value.
So, I would like to know whether I could make this code shorter and more efficient.
Any help would be highly appreciated.
python performance python-3.x
$endgroup$
8
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
1
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
1
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
1
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
1
$begingroup$
what's wrong with the variousrlecodes? It's 2 or 3 lines, at least inR; then add a line to findmax(runlength(val==0))Here's the base package code:y <- x[-1L] != x[-n];i <- c(which(y | is.na(y)), n);structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
$endgroup$
– Carl Witthoft
May 9 at 12:58
|
show 4 more comments
$begingroup$
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.
Write a program that generates 100 random integers that are either
0
or1.
Then find the:
- longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0]is
4.
My answer to this is:
import random
l = []
def my_list():
for j in range(0,100):
x = random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
max_count = 0
for j in l:
if j == 0:
c += 1
else:
if c > max_count:
max_count = c
c = 0
return max_count
l = my_list()
print(largest_row_of_zeros(l))
NOTE: I have changed zero_count to max_count as it sounds more sensible. It keeps track of the max_count (or the largest number of zeros in a row) seen so far, and if a number is not 0, it resets the value of c (count) to 0 after updating the value of max_count with a new value.
So, I would like to know whether I could make this code shorter and more efficient.
Any help would be highly appreciated.
python performance python-3.x
$endgroup$
I have written an answer to this question on Stack Overflow. To make it easier for you, I have copy-pasted the main question below.
Write a program that generates 100 random integers that are either
0
or1.
Then find the:
- longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0]is
4.
My answer to this is:
import random
l = []
def my_list():
for j in range(0,100):
x = random.randint(0,1)
l.append(x)
print (l)
return l
def largest_row_of_zeros(l):
c = 0
max_count = 0
for j in l:
if j == 0:
c += 1
else:
if c > max_count:
max_count = c
c = 0
return max_count
l = my_list()
print(largest_row_of_zeros(l))
NOTE: I have changed zero_count to max_count as it sounds more sensible. It keeps track of the max_count (or the largest number of zeros in a row) seen so far, and if a number is not 0, it resets the value of c (count) to 0 after updating the value of max_count with a new value.
So, I would like to know whether I could make this code shorter and more efficient.
Any help would be highly appreciated.
python performance python-3.x
python performance python-3.x
edited 12 hours ago
Justin
asked May 7 at 14:30
JustinJustin
249111
249111
8
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
1
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
1
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
1
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
1
$begingroup$
what's wrong with the variousrlecodes? It's 2 or 3 lines, at least inR; then add a line to findmax(runlength(val==0))Here's the base package code:y <- x[-1L] != x[-n];i <- c(which(y | is.na(y)), n);structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
$endgroup$
– Carl Witthoft
May 9 at 12:58
|
show 4 more comments
8
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
1
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
1
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
1
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
1
$begingroup$
what's wrong with the variousrlecodes? It's 2 or 3 lines, at least inR; then add a line to findmax(runlength(val==0))Here's the base package code:y <- x[-1L] != x[-n];i <- c(which(y | is.na(y)), n);structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
$endgroup$
– Carl Witthoft
May 9 at 12:58
8
8
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
1
1
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
1
1
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
1
1
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
1
1
$begingroup$
what's wrong with the various
rle codes? It's 2 or 3 lines, at least in R; then add a line to find max(runlength(val==0)) Here's the base package code: y <- x[-1L] != x[-n] ; i <- c(which(y | is.na(y)), n) ; structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")$endgroup$
– Carl Witthoft
May 9 at 12:58
$begingroup$
what's wrong with the various
rle codes? It's 2 or 3 lines, at least in R; then add a line to find max(runlength(val==0)) Here's the base package code: y <- x[-1L] != x[-n] ; i <- c(which(y | is.na(y)), n) ; structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")$endgroup$
– Carl Witthoft
May 9 at 12:58
|
show 4 more comments
8 Answers
8
active
oldest
votes
$begingroup$
Generating a random list
Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.
Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.
You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:
def random_list(length=100):
return [random.randint(0, 1) for _ in range(length)]
Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:
def random_list(length=100):
return random.choices((0, 1), k=length)
Finding the longest sequence
Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.
itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.
Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:
def largest_row_of_zero(iterable):
return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)
Testing code
Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:
if __name__ == '__main__':
l = random_list()
print(l, largest_row_of_zero(l))
$endgroup$
2
$begingroup$
Looping overrandom.randintis 5 times slower (on my machine) thanrandom.choices(POPULATION, k=100), with a global listPOPULATION = [0, 1].
$endgroup$
– jpmc26
May 8 at 1:28
2
$begingroup$
Pretty surenumpy.random.randint(0, 1, size=100)would make a good job here
$endgroup$
– Right leg
May 8 at 12:38
2
$begingroup$
@jpmc26 right, butchoicesis only available in latest versions and not yet an automatism
$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
$begingroup$
@Rightleg And then usingnp.maxon a variation of this answer. But I fear that, for such a small problem, you spend more time importingnumpythan you'd be able to get as speedup from it.
$endgroup$
– Mathias Ettinger
May 9 at 7:34
add a comment |
$begingroup$
Bug in the posted code. If you try it with the input [1,0,1,0,0] you will get the answer 1. The first two lines in the else won't get executed if the sequence ends with the longest run of zeros. Correct code is
for j in l:
if j==0:
c+=1
else:
c = 0
if c > max_count:
max_count = c
return max_count
This can be considerably shortened and, I think, clarified:
for j in l:
c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op
max_count = max( max_count, c)
return max_count
Two stylistic issues:
never use l as a variable name, it reads like 1. Lowercase l is best avoided altogether unless it's part of a word in a natural language. Similar arguments against O and Z which read like 0 and 2, but class-names starting with capital O or Z aren't so confusing.
The Pythonic form of initialization is c, max_count = 0, 0 (one line) provided the right-hand side, in particular, needs no real thought.
$endgroup$
add a comment |
$begingroup$
First the good: your code provides a testable function. So let's add some test code
def largest_row_of_zeros(l):
'''
>>> largest_row_of_zeros([])
0
>>> largest_row_of_zeros([0])
1
>>> largest_row_of_zeros([1])
0
>>> largest_row_of_zeros([0, 0])
2
>>> largest_row_of_zeros([0, 1])
1
>>> largest_row_of_zeros([1, 0])
1
>>> largest_row_of_zeros([1, 1])
0
'''
c = 0
max_count = 0
for j in l:
if j==0:
c+=1
else:
if c > max_count:
max_count = c
c = 0
return max_count
if __name__ == "__main__":
import doctest
doctest.testmod()
which gives
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
**********************************************************************
File "main.py", line 5, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0])
Expected:
1
Got:
0
**********************************************************************
File "main.py", line 9, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0, 0])
Expected:
2
Got:
0
**********************************************************************
File "main.py", line 13, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([1, 0])
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
3 of 7 in __main__.largest_row_of_zeros
***Test Failed*** 3 failures.
Here I use doctest. Another very common module is unittest. But you could also use simple assertions
if __name__ == "__main__":
assert largest_row_of_zeros([0]) == 1
Have fun with testing.
$endgroup$
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
add a comment |
$begingroup$
To simplify the code you can:
- You can use
itertools.groupbyto group the runs of 1s and 0s. - Filter if these groups to ones just containing zero.
- Find the length of each group.
- Return the maximum.
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
In your code I would move the max aspect of the code out of the function and make the original a generator function. This allows you to use max to simplify the handling of the data.
def zero_groups(l):
c = 0
for j in l:
if j == 0:
c += 1
else:
yield c
c = 0
def largest_row_of_zeros(l):
return max(zero_groups(l))
$endgroup$
add a comment |
$begingroup$
Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration
def longest_run(arr, element):
longest = 0
start = 0
non_match = -1
while start < len(arr):
if arr[start] == element:
current_run = 1
while current_run <= longest and arr[start - current_run] == element:
current_run += 1
if current_run > longest:
while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:
current_run += 1
longest = current_run
non_match = non_match + current_run
else:
non_match = start - current_run
else:
non_match = start
start = non_match + longest + 1
return longest
$endgroup$
add a comment |
$begingroup$
Another alternative: use RLE (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name.
Here's the code, albeit in the R language. (For non-users, 1L just forces integer-class, x[-k] means all of vector x except index 'k' )
Here's the base package code for the function rle(x) :
First line: generate logical vector of "is x[j] == x[j-1] ? "
y <- x[-1L] != x[-n] ;
which returns index values when argument is TRUE, and c concatenates vectors (is.na just catches N/A values in case the input was skeevy)
i <- c(which(y | is.na(y)), n) ;
finally, create a structure. First element calculates run lengths by comparing sequential index values in i ; second element returns the value of the input vector every time that run terminates
structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
then add a line to find max(lengths[values==0]).
$endgroup$
$begingroup$
Is theRlanguage related to Python?
$endgroup$
– Justin
May 9 at 16:09
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
add a comment |
$begingroup$
Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:
# importing functools for reduce()
import functools
# initializing list
inputString = "1,0,1,1,0,0,0,0,1,0,0"
#remove commas and split result into an array using 1 as the delimiter
inputString = inputString.replace(",", "")
resultArr = inputString.split("1");
# using reduce to compute maximum element from resulting array list
longestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr))
#output the result
print ("The maximum element of the list is : ",end="")
print (len(longestString))
$endgroup$
$begingroup$
Hello! I get the error -Cannot set property 'innerHTML' of nullwhen I run it on an online javascript compiler.
$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -document is not definedwhen I ran it on another compiler.
$endgroup$
– Justin
May 8 at 17:22
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
add a comment |
$begingroup$
Wanted to provide an alternate solution to the largest_row_of_zeros method. Easier to understand, but might not be as efficient.
def largest_row_of_zeros():
asStr = reduce((lambda x, y: str(x) + str(y)), random_list())
splitted = asStr.split("1")
return len(max(splitted))
- Basically create a string
"1010010101010" - Split at 1s.
"","0","00","0"... - Get length of longest string
$endgroup$
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
$begingroup$
Instead of using reduce,''.join(map(str, random_list()))is more idiomatic and understandable at a glance.
$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
add a comment |
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: "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%2f219872%2fprogram-for-finding-longest-run-of-zeros-from-a-list-of-100-random-integers-whic%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Generating a random list
Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.
Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.
You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:
def random_list(length=100):
return [random.randint(0, 1) for _ in range(length)]
Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:
def random_list(length=100):
return random.choices((0, 1), k=length)
Finding the longest sequence
Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.
itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.
Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:
def largest_row_of_zero(iterable):
return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)
Testing code
Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:
if __name__ == '__main__':
l = random_list()
print(l, largest_row_of_zero(l))
$endgroup$
2
$begingroup$
Looping overrandom.randintis 5 times slower (on my machine) thanrandom.choices(POPULATION, k=100), with a global listPOPULATION = [0, 1].
$endgroup$
– jpmc26
May 8 at 1:28
2
$begingroup$
Pretty surenumpy.random.randint(0, 1, size=100)would make a good job here
$endgroup$
– Right leg
May 8 at 12:38
2
$begingroup$
@jpmc26 right, butchoicesis only available in latest versions and not yet an automatism
$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
$begingroup$
@Rightleg And then usingnp.maxon a variation of this answer. But I fear that, for such a small problem, you spend more time importingnumpythan you'd be able to get as speedup from it.
$endgroup$
– Mathias Ettinger
May 9 at 7:34
add a comment |
$begingroup$
Generating a random list
Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.
Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.
You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:
def random_list(length=100):
return [random.randint(0, 1) for _ in range(length)]
Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:
def random_list(length=100):
return random.choices((0, 1), k=length)
Finding the longest sequence
Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.
itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.
Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:
def largest_row_of_zero(iterable):
return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)
Testing code
Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:
if __name__ == '__main__':
l = random_list()
print(l, largest_row_of_zero(l))
$endgroup$
2
$begingroup$
Looping overrandom.randintis 5 times slower (on my machine) thanrandom.choices(POPULATION, k=100), with a global listPOPULATION = [0, 1].
$endgroup$
– jpmc26
May 8 at 1:28
2
$begingroup$
Pretty surenumpy.random.randint(0, 1, size=100)would make a good job here
$endgroup$
– Right leg
May 8 at 12:38
2
$begingroup$
@jpmc26 right, butchoicesis only available in latest versions and not yet an automatism
$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
$begingroup$
@Rightleg And then usingnp.maxon a variation of this answer. But I fear that, for such a small problem, you spend more time importingnumpythan you'd be able to get as speedup from it.
$endgroup$
– Mathias Ettinger
May 9 at 7:34
add a comment |
$begingroup$
Generating a random list
Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.
Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.
You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:
def random_list(length=100):
return [random.randint(0, 1) for _ in range(length)]
Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:
def random_list(length=100):
return random.choices((0, 1), k=length)
Finding the longest sequence
Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.
itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.
Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:
def largest_row_of_zero(iterable):
return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)
Testing code
Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:
if __name__ == '__main__':
l = random_list()
print(l, largest_row_of_zero(l))
$endgroup$
Generating a random list
Instead of defining a global variable that will be modified by your generation function, you should instead define that variable inside the function and return it. This way, you will be able to call my_list a second time without having l being 200 items long. It will make the code easier to test.
Also note that l as a variable name is a poor choice as certain fonts make it hard to distinguish from 1.
You also use the "empty list + for loop + append" pattern which can be converted to a more efficient list-comprehension:
def random_list(length=100):
return [random.randint(0, 1) for _ in range(length)]
Note that, as suggested by @jpmc26 in the comments, and starting with Python 3.6, you can simplify further using random.choices:
def random_list(length=100):
return random.choices((0, 1), k=length)
Finding the longest sequence
Your manual counting is not that bad, but usually counting a number of element can be done using either sum or len depending on the iterable at play. And finding the longest count can be delegated to max. So you just need to group zeroes together, count how much there is in each group and find the max of these counts.
itertools.groupby will happily do the grouping for you. But you won't be able to use len on the resulting groups, so you can add 1 for each element in said group.
Lastly, if there is no sequence of zeroes, you'll get no groups, and thus no lengths to take the maximum from, so you need to instruct max that the longest count is 0 in such cases:
def largest_row_of_zero(iterable):
return max((sum(1 for _ in group) for value, group in itertools.groupby(iterable) if value == 0), default=0)
Testing code
Instead of putting the testing code at the top-level of the file, you should take the habit of using an if __name__ == '__main__': guard:
if __name__ == '__main__':
l = random_list()
print(l, largest_row_of_zero(l))
edited May 9 at 15:18
M.Herzkamp
1031
1031
answered May 7 at 15:04
Mathias EttingerMathias Ettinger
25.5k33387
25.5k33387
2
$begingroup$
Looping overrandom.randintis 5 times slower (on my machine) thanrandom.choices(POPULATION, k=100), with a global listPOPULATION = [0, 1].
$endgroup$
– jpmc26
May 8 at 1:28
2
$begingroup$
Pretty surenumpy.random.randint(0, 1, size=100)would make a good job here
$endgroup$
– Right leg
May 8 at 12:38
2
$begingroup$
@jpmc26 right, butchoicesis only available in latest versions and not yet an automatism
$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
$begingroup$
@Rightleg And then usingnp.maxon a variation of this answer. But I fear that, for such a small problem, you spend more time importingnumpythan you'd be able to get as speedup from it.
$endgroup$
– Mathias Ettinger
May 9 at 7:34
add a comment |
2
$begingroup$
Looping overrandom.randintis 5 times slower (on my machine) thanrandom.choices(POPULATION, k=100), with a global listPOPULATION = [0, 1].
$endgroup$
– jpmc26
May 8 at 1:28
2
$begingroup$
Pretty surenumpy.random.randint(0, 1, size=100)would make a good job here
$endgroup$
– Right leg
May 8 at 12:38
2
$begingroup$
@jpmc26 right, butchoicesis only available in latest versions and not yet an automatism
$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
$begingroup$
@Rightleg And then usingnp.maxon a variation of this answer. But I fear that, for such a small problem, you spend more time importingnumpythan you'd be able to get as speedup from it.
$endgroup$
– Mathias Ettinger
May 9 at 7:34
2
2
$begingroup$
Looping over
random.randint is 5 times slower (on my machine) than random.choices(POPULATION, k=100), with a global list POPULATION = [0, 1].$endgroup$
– jpmc26
May 8 at 1:28
$begingroup$
Looping over
random.randint is 5 times slower (on my machine) than random.choices(POPULATION, k=100), with a global list POPULATION = [0, 1].$endgroup$
– jpmc26
May 8 at 1:28
2
2
$begingroup$
Pretty sure
numpy.random.randint(0, 1, size=100) would make a good job here$endgroup$
– Right leg
May 8 at 12:38
$begingroup$
Pretty sure
numpy.random.randint(0, 1, size=100) would make a good job here$endgroup$
– Right leg
May 8 at 12:38
2
2
$begingroup$
@jpmc26 right, but
choices is only available in latest versions and not yet an automatism$endgroup$
– Mathias Ettinger
May 8 at 14:25
$begingroup$
@jpmc26 right, but
choices is only available in latest versions and not yet an automatism$endgroup$
– Mathias Ettinger
May 8 at 14:25
1
1
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
$begingroup$
OP is using 3.7.
$endgroup$
– jpmc26
May 8 at 17:17
1
1
$begingroup$
@Rightleg And then using
np.max on a variation of this answer. But I fear that, for such a small problem, you spend more time importing numpy than you'd be able to get as speedup from it.$endgroup$
– Mathias Ettinger
May 9 at 7:34
$begingroup$
@Rightleg And then using
np.max on a variation of this answer. But I fear that, for such a small problem, you spend more time importing numpy than you'd be able to get as speedup from it.$endgroup$
– Mathias Ettinger
May 9 at 7:34
add a comment |
$begingroup$
Bug in the posted code. If you try it with the input [1,0,1,0,0] you will get the answer 1. The first two lines in the else won't get executed if the sequence ends with the longest run of zeros. Correct code is
for j in l:
if j==0:
c+=1
else:
c = 0
if c > max_count:
max_count = c
return max_count
This can be considerably shortened and, I think, clarified:
for j in l:
c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op
max_count = max( max_count, c)
return max_count
Two stylistic issues:
never use l as a variable name, it reads like 1. Lowercase l is best avoided altogether unless it's part of a word in a natural language. Similar arguments against O and Z which read like 0 and 2, but class-names starting with capital O or Z aren't so confusing.
The Pythonic form of initialization is c, max_count = 0, 0 (one line) provided the right-hand side, in particular, needs no real thought.
$endgroup$
add a comment |
$begingroup$
Bug in the posted code. If you try it with the input [1,0,1,0,0] you will get the answer 1. The first two lines in the else won't get executed if the sequence ends with the longest run of zeros. Correct code is
for j in l:
if j==0:
c+=1
else:
c = 0
if c > max_count:
max_count = c
return max_count
This can be considerably shortened and, I think, clarified:
for j in l:
c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op
max_count = max( max_count, c)
return max_count
Two stylistic issues:
never use l as a variable name, it reads like 1. Lowercase l is best avoided altogether unless it's part of a word in a natural language. Similar arguments against O and Z which read like 0 and 2, but class-names starting with capital O or Z aren't so confusing.
The Pythonic form of initialization is c, max_count = 0, 0 (one line) provided the right-hand side, in particular, needs no real thought.
$endgroup$
add a comment |
$begingroup$
Bug in the posted code. If you try it with the input [1,0,1,0,0] you will get the answer 1. The first two lines in the else won't get executed if the sequence ends with the longest run of zeros. Correct code is
for j in l:
if j==0:
c+=1
else:
c = 0
if c > max_count:
max_count = c
return max_count
This can be considerably shortened and, I think, clarified:
for j in l:
c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op
max_count = max( max_count, c)
return max_count
Two stylistic issues:
never use l as a variable name, it reads like 1. Lowercase l is best avoided altogether unless it's part of a word in a natural language. Similar arguments against O and Z which read like 0 and 2, but class-names starting with capital O or Z aren't so confusing.
The Pythonic form of initialization is c, max_count = 0, 0 (one line) provided the right-hand side, in particular, needs no real thought.
$endgroup$
Bug in the posted code. If you try it with the input [1,0,1,0,0] you will get the answer 1. The first two lines in the else won't get executed if the sequence ends with the longest run of zeros. Correct code is
for j in l:
if j==0:
c+=1
else:
c = 0
if c > max_count:
max_count = c
return max_count
This can be considerably shortened and, I think, clarified:
for j in l:
c = c + 1 if j==0 else 0 # in other languages there is a ternary ?: op
max_count = max( max_count, c)
return max_count
Two stylistic issues:
never use l as a variable name, it reads like 1. Lowercase l is best avoided altogether unless it's part of a word in a natural language. Similar arguments against O and Z which read like 0 and 2, but class-names starting with capital O or Z aren't so confusing.
The Pythonic form of initialization is c, max_count = 0, 0 (one line) provided the right-hand side, in particular, needs no real thought.
edited May 7 at 18:19
answered May 7 at 17:43
nigel222nigel222
26316
26316
add a comment |
add a comment |
$begingroup$
First the good: your code provides a testable function. So let's add some test code
def largest_row_of_zeros(l):
'''
>>> largest_row_of_zeros([])
0
>>> largest_row_of_zeros([0])
1
>>> largest_row_of_zeros([1])
0
>>> largest_row_of_zeros([0, 0])
2
>>> largest_row_of_zeros([0, 1])
1
>>> largest_row_of_zeros([1, 0])
1
>>> largest_row_of_zeros([1, 1])
0
'''
c = 0
max_count = 0
for j in l:
if j==0:
c+=1
else:
if c > max_count:
max_count = c
c = 0
return max_count
if __name__ == "__main__":
import doctest
doctest.testmod()
which gives
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
**********************************************************************
File "main.py", line 5, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0])
Expected:
1
Got:
0
**********************************************************************
File "main.py", line 9, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0, 0])
Expected:
2
Got:
0
**********************************************************************
File "main.py", line 13, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([1, 0])
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
3 of 7 in __main__.largest_row_of_zeros
***Test Failed*** 3 failures.
Here I use doctest. Another very common module is unittest. But you could also use simple assertions
if __name__ == "__main__":
assert largest_row_of_zeros([0]) == 1
Have fun with testing.
$endgroup$
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
add a comment |
$begingroup$
First the good: your code provides a testable function. So let's add some test code
def largest_row_of_zeros(l):
'''
>>> largest_row_of_zeros([])
0
>>> largest_row_of_zeros([0])
1
>>> largest_row_of_zeros([1])
0
>>> largest_row_of_zeros([0, 0])
2
>>> largest_row_of_zeros([0, 1])
1
>>> largest_row_of_zeros([1, 0])
1
>>> largest_row_of_zeros([1, 1])
0
'''
c = 0
max_count = 0
for j in l:
if j==0:
c+=1
else:
if c > max_count:
max_count = c
c = 0
return max_count
if __name__ == "__main__":
import doctest
doctest.testmod()
which gives
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
**********************************************************************
File "main.py", line 5, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0])
Expected:
1
Got:
0
**********************************************************************
File "main.py", line 9, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0, 0])
Expected:
2
Got:
0
**********************************************************************
File "main.py", line 13, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([1, 0])
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
3 of 7 in __main__.largest_row_of_zeros
***Test Failed*** 3 failures.
Here I use doctest. Another very common module is unittest. But you could also use simple assertions
if __name__ == "__main__":
assert largest_row_of_zeros([0]) == 1
Have fun with testing.
$endgroup$
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
add a comment |
$begingroup$
First the good: your code provides a testable function. So let's add some test code
def largest_row_of_zeros(l):
'''
>>> largest_row_of_zeros([])
0
>>> largest_row_of_zeros([0])
1
>>> largest_row_of_zeros([1])
0
>>> largest_row_of_zeros([0, 0])
2
>>> largest_row_of_zeros([0, 1])
1
>>> largest_row_of_zeros([1, 0])
1
>>> largest_row_of_zeros([1, 1])
0
'''
c = 0
max_count = 0
for j in l:
if j==0:
c+=1
else:
if c > max_count:
max_count = c
c = 0
return max_count
if __name__ == "__main__":
import doctest
doctest.testmod()
which gives
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
**********************************************************************
File "main.py", line 5, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0])
Expected:
1
Got:
0
**********************************************************************
File "main.py", line 9, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0, 0])
Expected:
2
Got:
0
**********************************************************************
File "main.py", line 13, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([1, 0])
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
3 of 7 in __main__.largest_row_of_zeros
***Test Failed*** 3 failures.
Here I use doctest. Another very common module is unittest. But you could also use simple assertions
if __name__ == "__main__":
assert largest_row_of_zeros([0]) == 1
Have fun with testing.
$endgroup$
First the good: your code provides a testable function. So let's add some test code
def largest_row_of_zeros(l):
'''
>>> largest_row_of_zeros([])
0
>>> largest_row_of_zeros([0])
1
>>> largest_row_of_zeros([1])
0
>>> largest_row_of_zeros([0, 0])
2
>>> largest_row_of_zeros([0, 1])
1
>>> largest_row_of_zeros([1, 0])
1
>>> largest_row_of_zeros([1, 1])
0
'''
c = 0
max_count = 0
for j in l:
if j==0:
c+=1
else:
if c > max_count:
max_count = c
c = 0
return max_count
if __name__ == "__main__":
import doctest
doctest.testmod()
which gives
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
**********************************************************************
File "main.py", line 5, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0])
Expected:
1
Got:
0
**********************************************************************
File "main.py", line 9, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([0, 0])
Expected:
2
Got:
0
**********************************************************************
File "main.py", line 13, in __main__.largest_row_of_zeros
Failed example:
largest_row_of_zeros([1, 0])
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
3 of 7 in __main__.largest_row_of_zeros
***Test Failed*** 3 failures.
Here I use doctest. Another very common module is unittest. But you could also use simple assertions
if __name__ == "__main__":
assert largest_row_of_zeros([0]) == 1
Have fun with testing.
edited May 11 at 9:02
mdfst13
18k62357
18k62357
answered May 7 at 16:40
stefanstefan
1,733212
1,733212
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
add a comment |
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
1
1
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
For discussions about whether or not this answer is a good answer for Code Review Stack Exchange, see this question on meta
$endgroup$
– Simon Forsberg♦
May 10 at 9:56
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
$begingroup$
@stefan - Upvoted! I tried unit-testing and I am starting to get a hang of it. Thank you!
$endgroup$
– Justin
May 10 at 12:24
add a comment |
$begingroup$
To simplify the code you can:
- You can use
itertools.groupbyto group the runs of 1s and 0s. - Filter if these groups to ones just containing zero.
- Find the length of each group.
- Return the maximum.
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
In your code I would move the max aspect of the code out of the function and make the original a generator function. This allows you to use max to simplify the handling of the data.
def zero_groups(l):
c = 0
for j in l:
if j == 0:
c += 1
else:
yield c
c = 0
def largest_row_of_zeros(l):
return max(zero_groups(l))
$endgroup$
add a comment |
$begingroup$
To simplify the code you can:
- You can use
itertools.groupbyto group the runs of 1s and 0s. - Filter if these groups to ones just containing zero.
- Find the length of each group.
- Return the maximum.
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
In your code I would move the max aspect of the code out of the function and make the original a generator function. This allows you to use max to simplify the handling of the data.
def zero_groups(l):
c = 0
for j in l:
if j == 0:
c += 1
else:
yield c
c = 0
def largest_row_of_zeros(l):
return max(zero_groups(l))
$endgroup$
add a comment |
$begingroup$
To simplify the code you can:
- You can use
itertools.groupbyto group the runs of 1s and 0s. - Filter if these groups to ones just containing zero.
- Find the length of each group.
- Return the maximum.
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
In your code I would move the max aspect of the code out of the function and make the original a generator function. This allows you to use max to simplify the handling of the data.
def zero_groups(l):
c = 0
for j in l:
if j == 0:
c += 1
else:
yield c
c = 0
def largest_row_of_zeros(l):
return max(zero_groups(l))
$endgroup$
To simplify the code you can:
- You can use
itertools.groupbyto group the runs of 1s and 0s. - Filter if these groups to ones just containing zero.
- Find the length of each group.
- Return the maximum.
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
In your code I would move the max aspect of the code out of the function and make the original a generator function. This allows you to use max to simplify the handling of the data.
def zero_groups(l):
c = 0
for j in l:
if j == 0:
c += 1
else:
yield c
c = 0
def largest_row_of_zeros(l):
return max(zero_groups(l))
answered May 7 at 14:50
PeilonrayzPeilonrayz
27.5k343114
27.5k343114
add a comment |
add a comment |
$begingroup$
Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration
def longest_run(arr, element):
longest = 0
start = 0
non_match = -1
while start < len(arr):
if arr[start] == element:
current_run = 1
while current_run <= longest and arr[start - current_run] == element:
current_run += 1
if current_run > longest:
while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:
current_run += 1
longest = current_run
non_match = non_match + current_run
else:
non_match = start - current_run
else:
non_match = start
start = non_match + longest + 1
return longest
$endgroup$
add a comment |
$begingroup$
Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration
def longest_run(arr, element):
longest = 0
start = 0
non_match = -1
while start < len(arr):
if arr[start] == element:
current_run = 1
while current_run <= longest and arr[start - current_run] == element:
current_run += 1
if current_run > longest:
while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:
current_run += 1
longest = current_run
non_match = non_match + current_run
else:
non_match = start - current_run
else:
non_match = start
start = non_match + longest + 1
return longest
$endgroup$
add a comment |
$begingroup$
Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration
def longest_run(arr, element):
longest = 0
start = 0
non_match = -1
while start < len(arr):
if arr[start] == element:
current_run = 1
while current_run <= longest and arr[start - current_run] == element:
current_run += 1
if current_run > longest:
while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:
current_run += 1
longest = current_run
non_match = non_match + current_run
else:
non_match = start - current_run
else:
non_match = start
start = non_match + longest + 1
return longest
$endgroup$
Why check all the elements? You can jump ahead k+1 elements at a time once you find k in a row. After a while you're jumping huge amounts each iteration
def longest_run(arr, element):
longest = 0
start = 0
non_match = -1
while start < len(arr):
if arr[start] == element:
current_run = 1
while current_run <= longest and arr[start - current_run] == element:
current_run += 1
if current_run > longest:
while non_match + current_run + 1 < len(arr) and arr[non_match + current_run + 1] == element:
current_run += 1
longest = current_run
non_match = non_match + current_run
else:
non_match = start - current_run
else:
non_match = start
start = non_match + longest + 1
return longest
edited May 8 at 6:34
Justin
249111
249111
answered May 8 at 1:13
DaveSawyerDaveSawyer
412
412
add a comment |
add a comment |
$begingroup$
Another alternative: use RLE (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name.
Here's the code, albeit in the R language. (For non-users, 1L just forces integer-class, x[-k] means all of vector x except index 'k' )
Here's the base package code for the function rle(x) :
First line: generate logical vector of "is x[j] == x[j-1] ? "
y <- x[-1L] != x[-n] ;
which returns index values when argument is TRUE, and c concatenates vectors (is.na just catches N/A values in case the input was skeevy)
i <- c(which(y | is.na(y)), n) ;
finally, create a structure. First element calculates run lengths by comparing sequential index values in i ; second element returns the value of the input vector every time that run terminates
structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
then add a line to find max(lengths[values==0]).
$endgroup$
$begingroup$
Is theRlanguage related to Python?
$endgroup$
– Justin
May 9 at 16:09
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
add a comment |
$begingroup$
Another alternative: use RLE (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name.
Here's the code, albeit in the R language. (For non-users, 1L just forces integer-class, x[-k] means all of vector x except index 'k' )
Here's the base package code for the function rle(x) :
First line: generate logical vector of "is x[j] == x[j-1] ? "
y <- x[-1L] != x[-n] ;
which returns index values when argument is TRUE, and c concatenates vectors (is.na just catches N/A values in case the input was skeevy)
i <- c(which(y | is.na(y)), n) ;
finally, create a structure. First element calculates run lengths by comparing sequential index values in i ; second element returns the value of the input vector every time that run terminates
structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
then add a line to find max(lengths[values==0]).
$endgroup$
$begingroup$
Is theRlanguage related to Python?
$endgroup$
– Justin
May 9 at 16:09
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
add a comment |
$begingroup$
Another alternative: use RLE (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name.
Here's the code, albeit in the R language. (For non-users, 1L just forces integer-class, x[-k] means all of vector x except index 'k' )
Here's the base package code for the function rle(x) :
First line: generate logical vector of "is x[j] == x[j-1] ? "
y <- x[-1L] != x[-n] ;
which returns index values when argument is TRUE, and c concatenates vectors (is.na just catches N/A values in case the input was skeevy)
i <- c(which(y | is.na(y)), n) ;
finally, create a structure. First element calculates run lengths by comparing sequential index values in i ; second element returns the value of the input vector every time that run terminates
structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
then add a line to find max(lengths[values==0]).
$endgroup$
Another alternative: use RLE (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name.
Here's the code, albeit in the R language. (For non-users, 1L just forces integer-class, x[-k] means all of vector x except index 'k' )
Here's the base package code for the function rle(x) :
First line: generate logical vector of "is x[j] == x[j-1] ? "
y <- x[-1L] != x[-n] ;
which returns index values when argument is TRUE, and c concatenates vectors (is.na just catches N/A values in case the input was skeevy)
i <- c(which(y | is.na(y)), n) ;
finally, create a structure. First element calculates run lengths by comparing sequential index values in i ; second element returns the value of the input vector every time that run terminates
structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")
then add a line to find max(lengths[values==0]).
edited May 13 at 13:46
answered May 9 at 16:07
Carl WitthoftCarl Witthoft
1215
1215
$begingroup$
Is theRlanguage related to Python?
$endgroup$
– Justin
May 9 at 16:09
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
add a comment |
$begingroup$
Is theRlanguage related to Python?
$endgroup$
– Justin
May 9 at 16:09
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
$begingroup$
Is the
R language related to Python?$endgroup$
– Justin
May 9 at 16:09
$begingroup$
Is the
R language related to Python?$endgroup$
– Justin
May 9 at 16:09
3
3
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
Welcome to Code Review! If you are not able to provide example code in the OP's requested language, it might be worth to write an informal/pseudo-code description of the algorithm if the algorithm itself is the core of your answer.
$endgroup$
– AlexV
May 9 at 16:35
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
$begingroup$
@AlexV Done -- I hope :-)
$endgroup$
– Carl Witthoft
May 9 at 16:53
2
2
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
RLE stands for Run Length Encoding, AFAIK. There is no estimation involved.
$endgroup$
– Graipher
May 11 at 10:33
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
$begingroup$
@graipher - thanks - corrected that.
$endgroup$
– Carl Witthoft
May 13 at 13:46
add a comment |
$begingroup$
Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:
# importing functools for reduce()
import functools
# initializing list
inputString = "1,0,1,1,0,0,0,0,1,0,0"
#remove commas and split result into an array using 1 as the delimiter
inputString = inputString.replace(",", "")
resultArr = inputString.split("1");
# using reduce to compute maximum element from resulting array list
longestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr))
#output the result
print ("The maximum element of the list is : ",end="")
print (len(longestString))
$endgroup$
$begingroup$
Hello! I get the error -Cannot set property 'innerHTML' of nullwhen I run it on an online javascript compiler.
$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -document is not definedwhen I ran it on another compiler.
$endgroup$
– Justin
May 8 at 17:22
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
add a comment |
$begingroup$
Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:
# importing functools for reduce()
import functools
# initializing list
inputString = "1,0,1,1,0,0,0,0,1,0,0"
#remove commas and split result into an array using 1 as the delimiter
inputString = inputString.replace(",", "")
resultArr = inputString.split("1");
# using reduce to compute maximum element from resulting array list
longestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr))
#output the result
print ("The maximum element of the list is : ",end="")
print (len(longestString))
$endgroup$
$begingroup$
Hello! I get the error -Cannot set property 'innerHTML' of nullwhen I run it on an online javascript compiler.
$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -document is not definedwhen I ran it on another compiler.
$endgroup$
– Justin
May 8 at 17:22
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
add a comment |
$begingroup$
Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:
# importing functools for reduce()
import functools
# initializing list
inputString = "1,0,1,1,0,0,0,0,1,0,0"
#remove commas and split result into an array using 1 as the delimiter
inputString = inputString.replace(",", "")
resultArr = inputString.split("1");
# using reduce to compute maximum element from resulting array list
longestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr))
#output the result
print ("The maximum element of the list is : ",end="")
print (len(longestString))
$endgroup$
Just curious, but if the values list appears as a delimited collection, could you not just strip out the commas and split on the 1's to make an array and then reduce that? I haven't worked in python in 15 years (edit: updated to python) but this code seems to work:
# importing functools for reduce()
import functools
# initializing list
inputString = "1,0,1,1,0,0,0,0,1,0,0"
#remove commas and split result into an array using 1 as the delimiter
inputString = inputString.replace(",", "")
resultArr = inputString.split("1");
# using reduce to compute maximum element from resulting array list
longestString = (functools.reduce(lambda a,b : a if a >= b else b,resultArr))
#output the result
print ("The maximum element of the list is : ",end="")
print (len(longestString))
edited May 8 at 20:50
answered May 8 at 16:55
user200345user200345
112
112
$begingroup$
Hello! I get the error -Cannot set property 'innerHTML' of nullwhen I run it on an online javascript compiler.
$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -document is not definedwhen I ran it on another compiler.
$endgroup$
– Justin
May 8 at 17:22
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
add a comment |
$begingroup$
Hello! I get the error -Cannot set property 'innerHTML' of nullwhen I run it on an online javascript compiler.
$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -document is not definedwhen I ran it on another compiler.
$endgroup$
– Justin
May 8 at 17:22
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
$begingroup$
Hello! I get the error -
Cannot set property 'innerHTML' of null when I run it on an online javascript compiler.$endgroup$
– Justin
May 8 at 17:19
$begingroup$
Hello! I get the error -
Cannot set property 'innerHTML' of null when I run it on an online javascript compiler.$endgroup$
– Justin
May 8 at 17:19
$begingroup$
I got the error -
document is not defined when I ran it on another compiler.$endgroup$
– Justin
May 8 at 17:22
$begingroup$
I got the error -
document is not defined when I ran it on another compiler.$endgroup$
– Justin
May 8 at 17:22
1
1
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
Is there someway you can change the wording of your answer so that it doesn't appear to be a question. Also can you add something about why the alternate solution you provided in another language would be an improvement. Please see this help page codereview.stackexchange.com/help/how-to-answer.
$endgroup$
– pacmaninbw
May 8 at 17:58
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
@user200345 - You could try getting some help on converting this javascript code to python. This answer seems interesting to me.
$endgroup$
– Justin
May 8 at 17:59
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
$begingroup$
Updated my example. I was just looking to minimize the looping and lines of code that the other ideas had. This seems to work... Thanks for the comments guys.
$endgroup$
– user200345
May 8 at 20:53
add a comment |
$begingroup$
Wanted to provide an alternate solution to the largest_row_of_zeros method. Easier to understand, but might not be as efficient.
def largest_row_of_zeros():
asStr = reduce((lambda x, y: str(x) + str(y)), random_list())
splitted = asStr.split("1")
return len(max(splitted))
- Basically create a string
"1010010101010" - Split at 1s.
"","0","00","0"... - Get length of longest string
$endgroup$
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
$begingroup$
Instead of using reduce,''.join(map(str, random_list()))is more idiomatic and understandable at a glance.
$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
add a comment |
$begingroup$
Wanted to provide an alternate solution to the largest_row_of_zeros method. Easier to understand, but might not be as efficient.
def largest_row_of_zeros():
asStr = reduce((lambda x, y: str(x) + str(y)), random_list())
splitted = asStr.split("1")
return len(max(splitted))
- Basically create a string
"1010010101010" - Split at 1s.
"","0","00","0"... - Get length of longest string
$endgroup$
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
$begingroup$
Instead of using reduce,''.join(map(str, random_list()))is more idiomatic and understandable at a glance.
$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
add a comment |
$begingroup$
Wanted to provide an alternate solution to the largest_row_of_zeros method. Easier to understand, but might not be as efficient.
def largest_row_of_zeros():
asStr = reduce((lambda x, y: str(x) + str(y)), random_list())
splitted = asStr.split("1")
return len(max(splitted))
- Basically create a string
"1010010101010" - Split at 1s.
"","0","00","0"... - Get length of longest string
$endgroup$
Wanted to provide an alternate solution to the largest_row_of_zeros method. Easier to understand, but might not be as efficient.
def largest_row_of_zeros():
asStr = reduce((lambda x, y: str(x) + str(y)), random_list())
splitted = asStr.split("1")
return len(max(splitted))
- Basically create a string
"1010010101010" - Split at 1s.
"","0","00","0"... - Get length of longest string
answered May 9 at 9:45
Viktor MellgrenViktor Mellgren
231210
231210
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
$begingroup$
Instead of using reduce,''.join(map(str, random_list()))is more idiomatic and understandable at a glance.
$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
add a comment |
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
$begingroup$
Instead of using reduce,''.join(map(str, random_list()))is more idiomatic and understandable at a glance.
$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
$begingroup$
Yes, this also a very good solution to my question. Thanks for the answer!
$endgroup$
– Justin
May 9 at 9:53
3
3
$begingroup$
Instead of using reduce,
''.join(map(str, random_list())) is more idiomatic and understandable at a glance.$endgroup$
– Mathias Ettinger
May 9 at 13:12
$begingroup$
Instead of using reduce,
''.join(map(str, random_list())) is more idiomatic and understandable at a glance.$endgroup$
– Mathias Ettinger
May 9 at 13:12
1
1
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
$begingroup$
@MathiasEttinger much nicer
$endgroup$
– Viktor Mellgren
May 9 at 13:46
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%2f219872%2fprogram-for-finding-longest-run-of-zeros-from-a-list-of-100-random-integers-whic%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
8
$begingroup$
Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to this post for more information
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
May 7 at 17:17
1
$begingroup$
What's your metric for efficiency? Shortest program, fastest execution, least memory? I mean, you're using Python and you have a tiny string; you're not going to see any user-visible efficiency wins in that scenario.
$endgroup$
– Eric Lippert
May 8 at 0:15
1
$begingroup$
What version of Python are you using?
$endgroup$
– jpmc26
May 8 at 16:56
1
$begingroup$
@jpmc26 - Python 3.7
$endgroup$
– Justin
May 8 at 17:04
1
$begingroup$
what's wrong with the various
rlecodes? It's 2 or 3 lines, at least inR; then add a line to findmax(runlength(val==0))Here's the base package code:y <- x[-1L] != x[-n];i <- c(which(y | is.na(y)), n);structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle")$endgroup$
– Carl Witthoft
May 9 at 12:58