## Python: Grade_2 Math Questions V1

**Learning : Python, Math **

** Subject: Math Questions for Grade-2 V.1**

[

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

In the process of studing with/for my kids [specialy Math] i always need to give them some Questions in [+ -], I need to write the Questions on a paper then they solve it and i check the answers. So I thought if I create an app to solve this Problem.

**Application to Do What?**

- Select Two random numbers from a given range.
- Select a Math operator [+ -].
- Writing the Question on the Screen.
- Comparing the user input with the real answer.
- Writing a message on the screen acoording to the user answers.

**Application Menu**

x

y (+ -)

_______________

??

In this Version (V.1) of the application, there will be some limitations on the Questions Difficulties, Number ranges and type of Questions.

**Start Coding**

** The Menu **

As we can see above, we will have 7 keys for the Menu, **Menu 9** is for Exit. **Menu 3** will ask the user to Enter the Kid Name. **Menu 2** will ask for the Number Ranges (From/To as 0 to 9 so all the questions will be in this rage). **Menu 4, 5 and 6 ** each will be for type of questions. **Menu 1** will ask the user about All the questions type. In all menus 1,4,5 and 6 if the user did’t enter a Name or a number ranges, the application will as for it before srating.

Here is the code for the Main Menu.

# Code for Main Menu # ---------------- Main Menu ------------------------- def menu () : os.system('clear') print('\n\n\t This is a Math Revision Game.',version) print('\t --------------------------------------------') print(' '*34,'By:[AHRADWANI.COM]') print('\n\n\t') print('\t 1. Start Play the Game. [All Math Lessons]') print('\t 2. Re-set the Numbers Range.') print('\t 3. Register New Kid to Play.') print('\t \n ') print('\t 5. Questions Like: x (+ -) y = ?? \n') print('\t 6. Questions Like: x (+ -) ?? = y \n') print('\t 7. Questions Like: x','\n\t\t\t\t y (+ -)','\n\t\t\t ___________') print('\t ') print('\t 9. Exit.') user_select = input ('\n\n\t Select from the Menu. > ') return user_select

**Get the Numbers Range**

In this Function the user will be asked to Enter the Number range as from and to, we will check if the user Enter a valid input, No space, No Alphabetics.

# Get the Numbers Range def get_numbers_range () : """ Function to get the Number range from the user, we will check if the user Enter a valid input, No space, No Alphabetics. return: nfrom: is the lower number range. nto : is the upper number range. """ nfrom = check_user_input("\t Enter the Lower Range Number > ","\t ... You Need to Enter a Lower Range Number.") #(input('\n\t Enter the Lower Range > ')) nto = check_user_input("\t Enter the Upper Range Number > ","\t ... You Need to Enter an Upper Range Number.") if (int(nfrom)) > (int(nto)) : nfrom, nto = nto, nfrom return int(nfrom), int(nto)

**Check user input**

With each user input we will call this Function with two messages, statement message will be the one to gaid the user to What is need to Enter, error message will be display if the user input something wrong or not expected. Then the Function will return back the user input.

# check_user_input def check_user_input(statment_m,error_m): """ Function to check on the user input if it is a valid or not. Arguments: statmen_m: will be the one to gaid the user to What is need to Enter error_m: will be display if the user input something wrong or not expected. Return: uinput """ while True : print(statment_m,end="") uinput = input() if ((uinput) in [" ",""] or (not uinput.isnumeric()) or ((uinput) in schar) or ((str(uinput).isalpha()))): print(error_m) else: break return uinput

**Get the Kid Name**

A small and short Function to return the user/Kid Name.

# Get the Kid Name def get_kid_name () : return input('\n\t Enter Your Name > ')

**Setting and Variabls**

This is the first upper part of the application, we just import the random and os also we set some variables.

# Variables import random, os, operator score1 = 0 good = ['Correct','You are Right', 'Well Done..','Nice..','Excellent..','Amazing..','Good job',' YES .. Keep it up .. ','So Proud of You','Yes .. Another Point for You',] bad = ['Wrong ..','Sorry .. No!','Try Your Best','No!','No..Think Harder','ooops .. No','Not this Time'] oper_dict = { '+': operator.add, '-': operator.sub,} # '*': operator.mul, } schar = "@_!#$%^&*()?/\|}{~,.:'" nfrom = 0 nto = 0 name = 0 version = 'V.10.2022.R1'

**Math Question Type-1**

This Function will ask the user 10 Questions of Math according to the Numbers Range were the question will looks like: X [+ -] Y = ??, then if the answer is right good message will display on the screen.

# Math Question Type-1 (X [+ -] Y = ??) def Math_G2_type_1(): os.system('clear') score =0 for q in range(0,10): n1 = random.randint(nfrom,nto) n2 = random.randint(nfrom,nto) op = random.choice(list(oper_dict.keys())) if op == '-' : if n1 ') print(' ', n1, op ,n2,end='') ans = check_user_input(" = "," You Need to Enter an Answer .. ") if int(ans) == oper_dict[op](n1,n2): print(' ',random.choice(good),' .. ') score = score +1 else: print(' ',random.choice(bad),' .. ') return score

**Math Question Type-2**

This Function will ask the user 10 Questions of Math according to the Numbers Range were the question will looks like: X [+ -] ?? = Y, then if the answer is right good message will display on the screen.

# Math Question Type-1 (X [+ -] ?? = Y) def Math_G2_type_2(): os.system('clear') print('\n\n\t ', name ,' Now try to solve these once\n ') score =0 for q in range(0,10): n1 = random.randint(nfrom,nto) n2 = random.randint(nfrom,nto) op = random.choice(list(oper_dict.keys())) if op == '-' : if n1 < n2 : n1,n2 = n2,n1 print('\t\t ',n1) print('\t\t ',n2,' ',op) print('\t\t __________') ans = int(input('\t\t ')) if ans in [" ",""]: print(' ',random.choice(bad),' You Need to Enter an Answer .. ') else: if ans == oper_dict[op](n1,n2): print(' ',random.choice(good),' .. \n\n') score = score +1 else: print(' ',random.choice(bad),' .. \n\n') return score

**Math Question Type-3**

This Function will ask the user 10 Questions of Math according to the Numbers Range were the question will looks like:

X

Y [+ -]

__________

???

then if the answer is right good message will display on the screen.

# def Math_G2_type_3 (): os.system('clear') print('\n\n\t ', name ," let's try this.") print('\t Complete with correct number.\n') score = 0 for q in range(0,10): n1 = random.randint(nfrom,nto) n2 = random.randint(nfrom,nto) op = random.choice(list(oper_dict.keys())) if op == '-' : if n1 n2 : n1,n2 = n2, n1 print('\t ',n1,op, ' ______ = ', n2) ans = int(input(' Your Answer > ') ) if ans in [" ",""]: print(' ',random.choice(bad),' You Need to Enter an Answer .. ') else: if n2 == oper_dict[op](ans,n1): print(' ',random.choice(good),' .. \n\n') score = score +1 else: print(' ',random.choice(bad),' .. \n\n') return score

**Application Body**

In the Application Body itself I use a **while **loop to call and detect the User input from the menu and using that input to call the corresponding Function. All the codes and functions also the application Body code is on the Source file and can be Downloaded.

I test the code and RUN the app several times, but errors can be found, so next version of this Application will solve any errors also will add more Math Questions Type.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python Project: Properties Maintenance System P8

** Subject: Writing a Full Application for Properties Maintenance System [Property: Delete a Record] **

**Learning : Python, Math, SQL, Logeic **

[

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

In this part we will write a Function to Delete a record from the database, first we will call the def show_property(inside) to display all the records on the screen and ask the user to Select [enter] the ID of the Property to be Deleted. Next we will Display the Record again on the screen and ask the user to Confirm the Deleting by entering [Y] and any things else will be as [Don’t Delete]. Here is the code ..

.. End of Part 8 ..

NOTE: If you Download this Part you MUST Run the Option 82 (82. Delete the Data-Base and Start Again.) from the Main Menu to do the following Updates:

- Update the properties_t Table (Adding the number of BathRooms)
- Update on create_tables Function.
- Update on insert_zero_records Function.

**If you did this in last part (6) then you don’t need to do it again **

__In Part-9__ In the Next Part, we will write the Function to Edit a record of a selected Property.

**:: PMS Parts ::**

Part 1 | Part 2 | Part 3 | Part 4 |

Part 5 | Part 6 | Part 7 | Part 8 |

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python: Tower of Hanoi

**Learning : Python **

** Subject: Write a Function to Solve Tower of Hanoi Problem**

**Intoduction:** Tower Of Hanoi is Puzzle Game that has three Vertical Sticks/Pegs Named A, B, C (3 Towers) and we have n number of disks different in diameter soted on top of each other (Large to Small) in Tower A. The Gall is to move all the disks from (A) to (C).

# Tower of Hanoi Puzzel """ Project Name: Tower of Hanoi By: Ali Radwani Date: 13.6.2021 d : Number of Desk fs : From Stick ts : To Stick bs : Buffer Stick """ import os def hanoi_t(d, fs, bs, ts): if d ==1 : print("\n Move Desk 1 From {} To {}".format(fs,ts)) return else: hanoi_t(d-1,fs,ts,bs) print(" Move Desk {} From {} To {}".format(d,fs,ts)) hanoi_t(d-1,bs,fs,ts) print(" Move Desk {} From {} To {}".format(d,fs,ts)) os.system('clear') print('\n\n This is Tower Of Hanoi Project') print(' We are Solving a Three Desk Tower Named 1, 2 and 3, with Three Sticks Named A, B and C ') print('\n Start Solving ...') hanoi_t(3,'A','B','C')

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python: Random Pixel Color – P2

**Learning : Python, Math**

** Subject: Random Coloring Pixels**

[

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

Our last post about Random Pixel Color, we generate a Numpy Array of Row, Coloum and color then we Plot it on the screen [Read the Post Here], now in this post we will use some Math consepts to try if we can get some patterns out of ramdom Function.

Our Tools: In this post we will use the following:

1. Jupyter-NoteBook.

2. numpy.

3. random.

4. matplotlib.

5. PIL or Pillow.

In this version we will use **“Fibonacci Sequence”** Fibonacci Sequence is the sum of the two preceding ones, starting from 0 and 1 such as [1, 1, 2, 3, 5, 8, 13 … n], in our code we will have three variables:

cw: canvas width,

ch: canvas hight,

offset: the offset will be the value that will reset the Fibonacci Sequence to 1.

So, if we run the application, we will generate three numbers that will present the colors R,G,B (Will be Generated __ONE__ time) then for each pixcel in (cw*ch) we will calculate a v as Fibonacci Sequence from fs1 =1, fs2 = 1 here is the code:

v = fs1 + fs2

fs1,fs2 = fs2, v

this value v will be added to the colors r,g,b (on each pixcel) untill the v is grater the the offset numbre that we pass to the Function. If v > offset then we will re-set the fs1 = 1, fs2 = 1,.. Here is the Code ..

Run No.1 | Run No.2 |

Run No.3 |
Run No.4 |

The above is just 25×25 and i change the offset, feel free to download the code and change the numbers .. see what you will get …

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python: Random Pixel Color

**Learning : Python, Math**

** Subject: Random Coloring Pixels**

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

Last week I start reading and studying about “Image Processing”, in some point I was reading about converting an image to Array of numbers, and re-converting that Array back to an Image, at that moment popped into my mind what if we just generate an Array with random numbers and then show it as an Image.

In this article we will write a first simple Function to generate a random numbers presenting the three main color Red, Blue and Green; then storing the numbers in an Array then using matplotlib library to display the Image.

Our Tools: In this post we will use the following:

1. Jupyter-NoteBook.

2. numpy.

3. random.

4. matplotlib.

5. PIL or Pillow.

**Coding** I am user Jupyter NoteBook on samsung Tab S4. First we will do all imports we need as:

from PIL import Image

import numpy as np, matplotlib.pyplot as plt

import random

%matplotlib inline

Now, we will write a Function called rand_color, we will run a nested for loop to generate the Row and Column (width and height) and in/for each row we will generate thee numbers of colors range(0,255) as one pixel and storing them in an array, then we display the Array using:

Image.fromarray and plt.imshow(). Here is the Code ..

Run No.1 |
Run No.2 |

Run No.3 |
Run No.4 |

The above is just 25×25 image with random color pixels, this is the first function using default random, in coming posts we will use some Math variables [such: log,sin], constants [such: pi, golden ratio] to see if we can get a pattern from random.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python Sorting Algorithm – Heap Sorting -P4

**Learning : Python, Math, Algorithm **

** Subject: Sorting Algorithm, Heap Sort P2**

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

In Last Parts (2 & 3) we wort the Following Functions:

- Sections Header.
- Main Menu Function.
- Entering/Creating the Array.
- Print-Out or to Display the Array.
- Check If Array in Max-Heap.
- Convert Array to Max-Heap.

**I****n** this Part-4 we will cover another Two important Functions that we need to talk about in our mission to understand the **Heap Sorting Algorithm.** In a Max-Heap Array we may need to Add new Node to the Array and we may need to Delete a Node. Also I just add Item No.7 style=”color:#2662ee;”>print(‘ ‘*5,’ 7. Start Heap Sorting.’) to the main-menu so we can do Heap Sorting to a given Array.

Starting with Add New Node, Simply we Add the Node to the end of the Array using arrat.append(new_node) then we need to Check If still the Array in Max-Heap If NOT, We MUST Convert it to a Max-Heap.

**Scope of Work** Ask the user to Enter the New Node Value, Add The Node to the End of the Array, in While Loop Call convert_to_max_heap (arr,True), check_if_max_heap (arr,True) as following:

while not is_max:

arr = convert_to_max_heap (arr,True)

is_max = check_if_max_heap (arr,True)

this will keep check and convert the Array to Max-Heap. Here is the Full code and run screen ..

Now we will write a Function to Delete a Node from the Max-Heap Array. Deleting a Node is just by removing the first node in the Array (Array[0]), then moving the last element in the Array to it’s position, by doing this we may not having a Max-Heap Array any-more, so we need to convert the array to a Max-Heap. In our application here, we will have a while loop and calling the functions (check_if_max_heap and convert_to_max_heap) until we have the Array in a Max-Heap. Here is the code ..

We will stop here in this part. In Part-5 we will Sort any Array using the Max-Heap Sort Algorithm.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python Sorting Algorithm – Heap Sorting -P3

**Learning : Python, Math, Algorithm **

** Subject: Sorting Algorithm, Heap Sort P2**

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

First let’s just remember that in Part-1 we wort the Following Functions:

- Main Menu Function.
- Entering/Creating the Array.
- Print-Out or to Display the Array.
- Sections Header.

**I****n** this Part-3 we will cover another Two important Functions that we need to talk about in our mission to understand the **Heap Sorting Algorithm.**

__First Function__

**Check If The Array is in Max Heap:** After the user Giveing/Entering the Array [Selecting Option 1 in the Menu] we need to Examen/Check if it is in a Max-Heap, to do so we will call the Function def check_if_max_heap(arr, inside): the Function will take Two arguments:

arr : The Array.

inside: Boolean Flag showing are we calling the Function from within another Function or Not.

**Scope of Work:** We will check and compare each Node [__starting from last node in the leaves__] with it’s Parent using this formula parent_index = ((child_index-1)//2) to get the parent index, then comparing the Values of the Child and Parent, If the Child is __GRATER Than__ his Parent we SWAP them. Then going to the Next Child and so-on until the Root-Node. .. Here is the Code ..

for each print statement I am using this code __if not inside :__ then print ..

**Example:** if not inside : print(‘\n The Array is a Max-Heap Array.’)

So if the **inside = True ** then the print code will not work, that’s mean we are calling the Function from inside another function and we just want the return value, the return here will be a boolean True/False as is_max [if the array is in Max-Heap].

__Second Function__

**Convert to Max-Heap:** In this Function we will convert a given Array to a Max-Heap Array. The way this Function is working is by checking/Examining all the Childs starting from the Leaves, and if any Child is Grater than his Parent we do a SWAP. After we Finish, we will call the Function def check_if_max_heap(arr, inside): to check if the Array is in Max-Heap, If NOT we will call the convert Function and so-on until we get the is_max = True from the def check_if_max_heap(arr, inside):. Both Functions def check_if_max_heap(arr, inside): and def convert_to_max_heap (arr,inside): will be run in a while loop until def check_if_max_heap(arr, inside): will return **True.** .. Here is the code for **def convert_to_max_heap (arr,inside):**

And here is the while loop to keep Examining the Array until fully converted to a Max-Heap Array.

# While loop in Option 3 from the Main-Menu, In the main body code.. while not is_max: arr = convert_to_max_heap (arr,True) is_max = check_if_max_heap (arr,True)

We will stop here in this part. In Part-4 we will Add new Node to the Array, and Delete a Node from the Array.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python Sorting Algorithm – Heap Sorting -P2

**Learning : Python, Math, Algorithm **

** Subject: Sorting Algorithm, Heap Sort P2**

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

In this post we will start writing some codes for the Heap Sorting application, we will start with the following Functions:

- Main Menu Function.
- Entering/Creating the Array.
- Print-Out or to Display the Array.
- Sections Header.

So First: We will start with the Main_menu Function and will return user_choice also the main application body.. Here is the code ..

# Main Menu function and the main application body.. def main_menu(): os.system('clear') header() print("\n\n"," "*4,"==============[ Main Menu ]==============\n") print(' '*5,' 1. Enter the Binary Tree as an Array.') print(' '*5,' 2. Print out the Binary Tree. {Text Mode}') print(' '*5,' 3. Check if it is a Max Heap.') print(' '*5,' 4. Convert an Array (Binary Tree) to a Max-Heap.') print(' '*5,' 5. Add New Node to the Binary Tree.') print(' '*5,' 6. Delete a Node From the Binary Tree.') print(' '*5,' 9. Exit.') user_choice = input("\n Select from the Menu: > ") return user_choice # This is the Main application body. while True : user_select = main_menu() if user_select == '1' : print(' Enter the Binary Tree as a Array.') arr = create_array_node_b_node() if user_select == '2' : try: print_bt_text (arr) except : input('\n You Must First Enter/Create the Array... Press any key then Select Option 1. > ') if user_select == '3' : print(' Check if the Array is a Max Heap.') if user_select == '4' : print(' Convert an Array (Binary Tree) to a Max-Heap.') if user_select == '5' : print(' Add New Node to the Binary Tree.') #add_node(arr) if user_select == '6' : print(' Delete a Node from the Binary Tree.') #delete_node(arr) if user_select == '9' : print('\n\n Thank you for using this Appliation. ') input('\n Press any key .. ') break

**Next **we will write the function def create_array_node_b_node() in this function the user will start to enter the nodes in the Heap Tree starting from the Root and level-by-level. With every/each Node if the user just press Enter the Node will be as __None__,then will ask the user if there is any more nodes in the level and if the user answer with [N] then we will complete the level with __None__. Also in starting of each level we will ask the user if there is any more Nodes remain in the level.

Here is the code ..

**I****n** the last Function in this part, we will print-out the Heap-Array as text of Parents and Childs. Here is the code ..

# Function to print-out the Heap-Array Tree def print_bt_text (arr): """ Function will Write/Print-out the Tree as Text Showing the Parents and the Childs. Arguments: The Array as arr return None """ os.system('clear') header() print("\n\n==========[ Print out the Binary Tree. {Text Mode} ]==========\n\n") print(' The array we Have is: ',arr) for x in range (0,len(arr)): print(' ') if arr[x] != None : try: # For left childs l_child = 2 * x + 1 if arr[l_child] != None : print(f' Parent Node ({arr[x]}) has a Left Child ({arr[l_child]})',end="") elif arr[l_child] == None: print(f' Parent Node ({arr[x]}) has NO Left Child',end="") except: pass try: # For right Childs r_child = 2 * x + 2 if (arr[l_child] == None) and (arr[r_child] != None) : print(f' But it Has a Right Child ({arr[r_child]}).') elif (arr[l_child] != None) and (arr[r_child] != None) : print(f' and a Right Child ({arr[r_child]})') elif (arr[r_child] == None): print(f' and Has NO Rigth Child.') except: pass input(' DONE ... Here is a Print out of the Heap Tree Array in {Text Mode}')

We will stop here in this part and will do more Functions in Part 3

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python Sorting Algorithm – Heap Sorting -P1

**Learning : Python, Math, Algorithm **

** Subject: Sorting Algorithm, Heap Sort**

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

Once I start preparing and writing the code for Heap Sorting I fond that I can’t jump to the Heap Sorting without some introductions, So in this post we will cover the Array, Binary Tree, Binary Array, Max-Heap, how to know if a given Array is in Max-Heap or not, Add node to a Max-Heap and Delete a node from a Max-heap. For all this, we will have two or three posts to cover what i think we must know.

So First:

**Binary Tree:** A Binary Tree is a set of Nodes and each Node may have a Maximum of TWO Childs, called Left-Child and Right-Child. Going down to the next level, each of the Child’s (the left one and the right one) again may have TWO Child’s (Left and Right) .. and so on. The last level were there is no more child’s that level is the Leaves. Here are some sample of Binary Tree’s..

All the above are Binary Tree’s, But we will talk about Three Definitions for a Binary Trees:

Full Binary Tree, Complete Binary Tree, Perfect Binary Tree

**Full Binary Tree:**

A Tree is a __Full Binary Tree__ in which Every/All Nodes Except Leaf Nodes(last level) have __ Zero or Two__ Children.

**Complete Binary Tree:**

A Binary Tree called a {__complete binary tree__} in which All/Each levels are completely filled __except__ possibly the last level has all keys as left as possible

__Practical example of Complete Binary Tree is Binary Heap.__

**Perfect Binary Tree:**

A Binary Tree is {__a Perfect Binary Tree__} IF all the internal nodes have Two children **and** all leaf nodes are at the same level.

NOTE: Every Full Binary Tree is A Complete.

FULL BINARY TREE | FULL BINARY TRTEE |

COMPLETE BINARY TREE | COMPLETE BINARY TREE |

PERFECT BINARY TREE | PERFECT BINARY TREE Figure 1 |

**Binary Tree And Array:** To convert a binary tree into array or to present a Binary Tree as an Array we need to consider the following :

1. To Taking all the elements in the Binary Tree.

2. To Keeping the relations between the nodes, who is the parent and what are the childerns for each parents [Left child and Right child].

**1. Taking all the elements in the Binary Tree:**

So for a given tree as __Figure 1:[in above example] __, we can see that (A) is the First Element [Root] (First Parent) and has 2 childs (B) (Left Child) & (C) (Right Child), –> Then Element (B) as parent has Two childs (D) (Left Child) & (E) (Right Child), –> Then Element (C) as parent has Two Childs (F) (Left Child) & (G) (Right Child) .. this is the end of the tree, leaves level.

Now, IF we want to present this Tree as an Array we will start with (A) in index 0, then will write all the elements level by level, from Left to Right. So we will have the array **a1** as follow:

** a1 = [A,B,C,D,E,F,G]**

**2. Keeping the relations between the Nodes:** Using the Method of filling the Array as in point One (above) we Save the relations between the Parents and Childs. For a given Array **a1 = [A,B,C,D,E,F,G]** we can user three formulas to know the Parent and the Childs of any given Node as following:

Assuming we are at index (x) then:

1. Left Child Index of Node (x) : 2 * x + 1

2. Right Child Index of Node (x) : 2 * x + 2

3. Parent Index of Node (x) : x//2 (absolute value of the division)

So, if we refer to a1 Array and (Figure-1), and say we want to know the childrens of node (A), Node (A) is in index [0] so:

The Left child index of Node (A) is : 2 * 0 + 1 = 0 + 1 = 1, the Element in index 1 in the Array a1[1] = B.

The Right child index of Node (A) is : 2 * 0 + 2 = 0 + 2 = 2, the Element in index 2 in the Array a1[2] = C.

The Left child index of Node (C) is : 2 * 2 + 1 = 4 + 1 = 5, the Element in index 5 in the Array a1[5] = F.

The Right child index of Node (C) is : 2 * 2 + 2 = 4 + 2 = 6, the Element in index 6 in the Array a1[6] = (G).

The Parent of Node (E) will be: 4//2 = 2, so the parent of the Element (E) is a1[2] = (B)

**Heap Tree:** Is a Binary Essentially an almost Complete Tree. So a **Heap Tree is**: Tree with All/Each levels are completely Filled except possibly the last level has all keys as left as possible. In Heap The Nodes represents as Integer Numbers.

**Max-Heap:** In Max-Heap Tree the Child Node is Smaller than his Parent.

**Mini-Heap:** In Mini-Heap Tree the Child Node is Larger than his Parent.

We will stop here in this part and will start doing some coding in Python Sorting Algorithm – Heap Sorting – P2.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Python: Sorting Algorithm. 7- Radix Sorting

**Learning : Python Coding, Math, Algorithm **

** Subject: Python Code to Applying Radix Sorting Algorithm **

NOTE:To keep the code as simple as we can,We WILL NOT ADDany user input Varevecations. Assuming that our user will Enter the right inputs.]

**Sorting Algorithm** is a way to sort a given list/Array of numbers, there are several sorting Algorithm as follow:

**Type of Sorting Algorithm**

1. Quick Sort. [**Click to Read the Post.**]

2. Bubble Sort. [**Click to Read the Post.**]

3. Merge Sort. [**Click to Read the Post.**]

4. Insertion Sort. [Click to Read the Post.]

5. Selection Sort. [Click to Read the Post.]

6. Heap Sort. [Click to Read the Post.]

7. Radix Sort. [Click to Read the Post.]

8. Bucket Sort. [Click to Read the Post.]

Here in this post we will write a function to take a given list/Array and sort it then pass it back. We assume the user will enter a serial of numbers, that he want to sort, our function will sort it using Radix Sorting Algorithm and print out the original Array and the sorted one.

**Radix Sort Algorithm**: In Radix Sort, we will apply coming Steps:

1. Get the Maximum Number of Digits in the Array. [length of Maximum Number]

2. Add Zeros [0] to the Left of Each Number so All Numbers in the Array will be Same Lenght.

3. Sort the Array Based on The Most Right Digit [digit index] =[-i]. This was Iteration 1.

4. Repeat Step 3, and for each Iteration We Sort based on [digit index] = [-iteration].

5. If [digit index] = 0, Thats mean we did sort until Most left Digit in the Numbers. Then we Stop the Loop.

6. Return the Array.

Coding: In our Radix Sorting Application we will have several Functions to help us completing our task. First let’s see the functions:

Main-menu: To Show the Main Menu of the Application.

header: Just a Decoration Function to Print the Header of the Application.

digits_equalizer: To Add Zeros to the Left of Each Number in the Array.

create_list: Let the User to Enter the Array.

radix_sort: Applying Radix Sorting Algorithm in a Fast-Run

radix_sort_details: Applying Radix Sorting Algorithm Step-by-Step.

Just to be a short artical, i will not go thought Functions like the def main_menu() , def create_list() and def header().

So, let’s start with digits_equalizer() Function, in Radix Sorting we start comparing all numbers based on it’s digites and sorting cording that, but if a number has three digits and another one has two, then we may face an error [index out of range], so first we will convert the array to a string and will add zero.. Here is the code..

This Function will return two arguments, the Array after adding zeros and the maximum digits.

Now, we will write the function of Radix Sorting (Fast-Run) the details function will be a copy with some print-statement.

So here is the code..

# Radix Sort Fast-Run Function def radix_sort() : arr = create_list() temp_arr = [] # Convert to srting and Add Zeros to left side of each number in the array. arr,max_d = digits_equalizer(arr) # Loop for all digits of numbers. for d in range (1,max_d+1): # Loop for sort numbers 0 to 9. for sn in range (0,10): # Check each right digits of each number. for each in arr: if each[-d] == str(sn): temp_arr.append(each) arr = temp_arr temp_arr = [] return(arr)

End of this Post..

All Code as .py file format is available in Download Page.

..:: Have Fun with Coding ::.. 🙂

To Download my Python code (.py) files

Click-Here

By: Ali Radwani