From c2ecdcf89b035bb9ff8b6b00c80fd6de7595eb77 Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Sat, 12 Aug 2017 20:58:19 -0400 Subject: [PATCH] Remove many uses of range(), a Python 2/3 difference Signed-off-by: David A. Wheeler --- flawfinder | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/flawfinder b/flawfinder index 5824938..e670845 100755 --- a/flawfinder +++ b/flawfinder @@ -1392,7 +1392,11 @@ def process_directive(): return hitfound = 0 # Iterate backwards over hits, to be careful about the destructive iterator - for i in xrange(len(hitlist) - 1, -1, -1): + # Note: On Python 2 this is inefficient, because the "range" operator + # creates a list. We used to use "xrange", but that doesn't exist + # in Python3. So we use "range" which at least works everywhere. + # If speed is vital on Python 2 we could replace this with xrange. + for i in range(len(hitlist) - 1, -1, -1): if hitlist[i].filename == filename and hitlist[i].line == linenumber: del hitlist[i] # DESTROY - this is a DESTRUCTIVE iterator. hitfound = 1 # Don't break, because there may be more than one. @@ -2003,9 +2007,10 @@ def show_final_results(): count = 0 count_per_level = {} count_per_level_and_up = {} - for i in range(0, 6): # Initialize count_per_level + possible_levels = [0, 1, 2, 3, 4, 5] # Eliminate dependency on range + for i in possible_levels: # Initialize count_per_level count_per_level[i] = 0 - for i in range(0, 6): # Initialize count_per_level + for i in possible_levels: # Initialize count_per_level count_per_level_and_up[i] = 0 if show_immediately or not quiet: # Separate the final results. print() @@ -2078,7 +2083,7 @@ def show_final_results(): print("
") # Output hits@each level. print("Hits@level =", end='') - for i in range(0, 6): + for i in possible_levels: print(" [%d] %3d" % (i, count_per_level[i]), end='') if output_format: print("
") @@ -2086,12 +2091,12 @@ def show_final_results(): print() # Compute hits at "level x or higher" print("Hits@level+ =", end='') - for i in range(0, 6): + for i in possible_levels: for j in range(i, 6): count_per_level_and_up[ i] = count_per_level_and_up[i] + count_per_level[j] # Display hits at "level x or higher" - for i in range(0, 6): + for i in possible_levels: print(" [%d+] %3d" % (i, count_per_level_and_up[i]), end='') if output_format: print("
") @@ -2099,7 +2104,7 @@ def show_final_results(): print() if sloc > 0: print("Hits/KSLOC@level+ =", end='') - for i in range(0, 6): + for i in possible_levels: print(" [%d+] %3g" % ( i, count_per_level_and_up[i] * 1000.0 / sloc), end='') if output_format: