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
Then find the:
- longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
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
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.