Python scripts converted from Pascal Demonstrations

The first example of a Python script based on a Pascal demonstration calculates factorials using recursion.

# Calculates factorials using recursion
def factorial(i):
    if i == 0:
        return 1
    else:
        return i * factorial(i - 1)

str_num = input('Please enter an integer from 0 to 20. ')
num = int(str_num)
print(num,'! = ', factorial(num), sep='')

Insertion Sort

The next example, based on our Pascal demonstration, shows you how an insertion sort works. A copy of the output follows the code.

# Insertion sort demonstration with zero based indices
# based on the Pascal demonstration at http://www.pp4s.co.uk/main/tu-ss-sort-insertion.html
nums  =  [503, 87, 512, 61, 908, 170, 897, 275, 653, 426, 154, 509, 612, 677, 765, 703];

def display(arr):
    for num in arr:
        print(num, end = ' ')
    print('\n')

def insertion_sort(arr):
    current = 0
    if len(arr) < 2:
        print('No sorting possible')
    else:
        for insert in range(1, len(arr)):
            inserted = False
            current = insert # starts at 1
            temp = arr[insert]
            while not inserted:
                if temp > nums[current - 1]:
                    inserted = True; #Position found
                    nums[current] = temp
                    print('Sorted up to index', insert, '    ', temp, 'inserted at position', current)
                    display(arr)
                else:
                    # Shift up integer one place
                    nums[current] = nums[current - 1]
                    current -= 1
                    if current == 0:
                        nums[0] = temp
                        print('Sorted up to index', insert, '    ', temp, 'inserted at position 0')
                        inserted = True
                        display(arr)
display(nums)
insertion_sort(nums)

Output:

503 87 512 61 908 170 897 275 653 426 154 509 612 677 765 703

Sorted up to index 1      87 inserted at position 0
87 503 512 61 908 170 897 275 653 426 154 509 612 677 765 703

Sorted up to index 2      512 inserted at position 2
87 503 512 61 908 170 897 275 653 426 154 509 612 677 765 703

Sorted up to index 3      61 inserted at position 0
61 87 503 512 908 170 897 275 653 426 154 509 612 677 765 703

Sorted up to index 4      908 inserted at position 4
61 87 503 512 908 170 897 275 653 426 154 509 612 677 765 703

Sorted up to index 5      170 inserted at position 2
61 87 170 503 512 908 897 275 653 426 154 509 612 677 765 703

Sorted up to index 6      897 inserted at position 5
61 87 170 503 512 897 908 275 653 426 154 509 612 677 765 703

Sorted up to index 7      275 inserted at position 3
61 87 170 275 503 512 897 908 653 426 154 509 612 677 765 703

Sorted up to index 8      653 inserted at position 6
61 87 170 275 503 512 653 897 908 426 154 509 612 677 765 703

Sorted up to index 9      426 inserted at position 4
61 87 170 275 426 503 512 653 897 908 154 509 612 677 765 703

Sorted up to index 10      154 inserted at position 2
61 87 154 170 275 426 503 512 653 897 908 509 612 677 765 703

Sorted up to index 11      509 inserted at position 7
61 87 154 170 275 426 503 509 512 653 897 908 612 677 765 703

Sorted up to index 12      612 inserted at position 9
61 87 154 170 275 426 503 509 512 612 653 897 908 677 765 703

Sorted up to index 13      677 inserted at position 11
61 87 154 170 275 426 503 509 512 612 653 677 897 908 765 703

Sorted up to index 14      765 inserted at position 12
61 87 154 170 275 426 503 509 512 612 653 677 765 897 908 703

Sorted up to index 15      703 inserted at position 12
61 87 154 170 275 426 503 509 512 612 653 677 703 765 897 908

Quicksort

This example is based on our first Pascal quicksort demonstration. Coloured output to the console is essential for this teaching aid. We use Colorama and provide straightforward installation instructions for it.

# Quicksort of digits from 0 to 9

from colorama import init, Fore, Back
 
UPPER_BOUND = 10

ints  = [9, 6, 2, 4, 7, 1, 5, 8, 0, 3]
 
def quicksort(left, right):
    pivot, temp, ptr_left, ptr_right = 0, 0, 0, 0

    def display_list():
        for count in range(0, UPPER_BOUND):
            if (count >= left) and (count <= right):
                print(Back.YELLOW, end='')
            else:
                print(Back.BLACK, end='')
            if count == ptr_left:
                print(Fore.GREEN, end='')
            elif count ==  ptr_right:
                print(Fore.RED, end='')
            else:
                print(Fore.WHITE, end='')
            if ints[count] ==  pivot:
                print(Back.LIGHTBLACK_EX, end='')
            print(ints[count], end='') 

        print(Fore.WHITE + Back.BLACK, end='')
        if ptr_left == ptr_right:
            print('  Pointers coincide. Press return to continue.')
        else:
            print('                     Press return to continue.')
        dummy = input() # End of inner routine display_list()
        
    ptr_left = left
    ptr_right = right
    pivot = ints[(left + right) // 2]
    print(Fore.WHITE,'quicksort for index ', left,  ' to ', right, ' with pivot ', pivot,':')
    display_list()
    while ptr_left <= ptr_right: 
        # Increment left pointer while  it has not reached upper
        # index of array segment and value remains less than pivot.
        while (ptr_left < right) and (ints[ptr_left] < pivot):
            print('Left pointer moves right:')
            ptr_left += 1
            display_list()

        # Decrement left pointer while it has not reached lower
        # index of array segment and value remains greater than pivot.
        while (ptr_right > left) and (ints[ptr_right] > pivot):
            print('Right pointer moves left:')
            ptr_right -= 1
            display_list()

        if ptr_left <= ptr_right:  # if left pointer and right pointer have not crossed
            #Swap values at left and right pointers if pointers are not equal
            if ptr_left < ptr_right:
                print('Swapping ', ints[ptr_left], ' with ', ints[ptr_right])
                temp = ints[ptr_left]
                ints[ptr_left] = ints[ptr_right]
                ints[ptr_right] = temp
                display_list()

            print('Both pointers move one place:')
            # Left pointer moves right and right pointer moves left.
            ptr_left += 1
            ptr_right -= 1
            display_list()

    print('Pointers have crossed. ')
    # Sort the left partition if necessary.
    if ptr_right > left:
        quicksort(left, ptr_right)
    # Sort the right partition if necessary.
    if ptr_left < right:
        quicksort(ptr_left, right) 
 # Main section       
init()
quicksort(0, UPPER_BOUND - 1)
print(Fore.RESET + Back.RESET)
print('Sorted!')

Programming - a skill for life!

Converting from Python to Pascal