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]
is4
.
Here is my answer to this:
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.
rle
codes? 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\$