1

I have the following code in Python 3:

events_count = len(events)
for i, e in enumerate(events):
    finished = 100*(i/events_count)
    if finished % 10 == 0:
        logger.info('Finished processing {} % of all events'.format(int(finished)))

In the current case events_count = 133805 and it's printing only 20%, 40%, etc. but not 10%, 20%, 30%. How can I achieve that? I tried rounding: finished = 100*round((i/events_count), (len(str(events_count)))) but it doesn't work. I tried also subtracting one from the length of precision but it starts printing some percentages twice.

I am not interested in progress bars, just in the correct computation here.

Nikita Vlasenko
  • 4,004
  • 7
  • 47
  • 87

2 Answers2

4

You could keep track of how many alerts you've done. divmod returns the division and the mod values in a tuple, so you could use that to identify that you have crossed a multiple of 10, then update the alerts counter (below I've called it updates) to be one more which will cause the conditional to fail until it surpasses the next 10 multiple. This won't really work for lists less than 10 though.

events_count = len(events)
updates = 0
for i, e in enumerate(events):
    finished = 100*(i/events_count)
    if divmod(finished, 10) == (updates, 0):
        updates += 1
        logger.info('Finished processing {} % of all events'.format(int(finished)))
Finished processing 0 % of all events
Finished processing 10 % of all events
Finished processing 20 % of all events
Finished processing 30 % of all events
Finished processing 40 % of all events
Finished processing 50 % of all events
Finished processing 60 % of all events
Finished processing 70 % of all events
Finished processing 80 % of all events
Finished processing 90 % of all events
BWStearns
  • 2,567
  • 2
  • 19
  • 33
1

Actually, it does work properly. The issue here is, your list of events might not all be divisible of 10.

For example, if events_count = 10, it will result in the logger printing 0% 10% 20% 30% etc. This is because, you have an if statement which tells your code to print when the percentage is divisible by 10.

If your events_count = 4, it will only print 0% 50%. The variable finished is equal to 25% when i = 1, but since 25 is not divisible by 10, it won't print it. When i = 2, finished is equal to 50%, which is divisible by 10. That's why it only print 0% and 50%. This also apply to your case.

You could show the correct progress by removing your if statement. That way, it will just print the progress.

events_count = len(events)
for i, e in enumerate(events):
    finished = 100*(i/events_count)
    logger.info('Finished processing {} % of all events'.format(int(finished)))
Kevin Yobeth
  • 939
  • 1
  • 8
  • 17