18
19
20# merge function merges the sorted runs
21def merge(arr, l, m, r):22 # original array is broken in two parts
23 # left and right array
24 len1, len2 = m - l + 1, r - m
57# array[0...n-1] (similar to merge sort)
58
59
60def tim_sort(arr):61 n = len(arr)
62 # Sort individual subarrays of size RUN
63 for i in range(0, n, RUN):
5# to right index which is of size atmost RUN
6
7
8def insertion_sort(arr, left, right): 9 for i in range(left + 1, right + 1):
10 temp = arr[i]
11 j = i - 1
1# Python program to implement stooge sort
2def stooge_sort(arr, first=0, last=None): 3 if last is None:
4 last = len(arr) - 1
5 if first >= last:
1# Python3 program for implementation of Shell Sort
2
3
4def shell_sort(arr): 5 # Start with a big gap, then reduce the gap
6 n = len(arr)
7 gap = n // 2
The local variable name hides the variable defined in the outer scope, making it inaccessible and might confuse.
filename = 'myfile.txt'
def read_file(filename): # This shadows the global `filename`
with open(filename) as file:
return file.readlines()
FILENAME = 'myfile.txt' # renamed global to UPPER_CASE as convention
def read_file(filename):
with open(filename) as file:
return file.readlines()
Another usual suspect of this is when you use the same parameter name inside a function as the global variable you are using. For example:
def run_app(app):
# This `app` shadows the global app...
app.run()
if __name__ == '__main__':
app = MyApp() # This is a global variable!
run_app(app)
To avoid this re-defining of a global, consider not defining app
as a global, but inside a main()
function instead:
def run_app(app):
# There is no longer a global `app` variable.
app.run()
def main():
app = MyApp()
run_app(app)
if __name__ == '__main__':
main()