## Python: Coffee Consumption P10

**Learning : Python, SQlite3, Dataset, Pandas, **

** Subject: Create Coffee Consumption Application. **

[

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.]

[ IF THE IS FIRST TIME DOWNLOADING THE CODE FILE, SELECT OPTION 7 FROM MAIN-MENU TO CREATE THE DATABASE]

In this Last part (Part-10) of **Coffee Consumption App**, we will write a Function to **Export the Data to an Excel Fiel**, So this will be the __Last__ part of this application and any other Enhancement will be added as new version of the application.

**Exporting The Data:** To Export the data to or say “writing into” Excel file we need to import New library Named: **xlsxwriter** [if you don’t have the library then you need to install it first, using this command: pip install xlsxwriter]. After installing we will call it into our python file using this command: import xlsxwriter. The Excel file [in this case] will have four Sheets, named as follow:

coffee_con, coffee_name, coffee_type, coffee_size

each sheet will contains the table header and the date.

File Name: The file name will be as: coffee_consumption_[Current Date & Time].xlsx, the date and time will be formated as: yyyymmdd_HM, the python code to generate this is:

now = datetime.now()

date_t = now.strftime(“%Y%m%d_%H%M”)

Also we need to know that the file will be saved in the same directory of the application or (python .py file)

New Function: from our back_up function we will call another Function called: write_data(data_set,col_list,the_sheet): this Function will write the data-set into Excel file sheet, so we need to pass the data_set, column list and the Sheet Name as arguments to the function and it will use the command: write(row,col,data) to write the row to the sheet. Here is the code

# Writing the data into the sheet def write_data(data_set,col_list,the_sheet): """ Function to write the data-set into Excel file sheet. Argument: data_set: col_list: List of the columns in the data_set. the_sheet: the Sheet Name. """ # write the Table Header for x in range (0,len(col_list)): the_sheet.write(0,x,col_list[x]) rows = len(data_set) for row in range (1,rows) : for col in range (0,len(col_list)) : the_sheet.write(row,col,data_set[row][col])

In our main back-up function, we prepare the data-set and column list, then we call the new Function **write_data **passing the variable. Here is two parts of the code, first one is generating the file name, and calling the datetime function, second part is dealing with the data tables in the database, fetching the data, listing the columns and passing this to write_data function.. Here is the code

… Done. We finish the Coffee Consumption Application using Python and Sqlite. Next Week we will start New Application ..

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

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

Part 6 | Part 7 | Part 8 | Part 9 | Part 10 |

To Download my Python code (.py) files

Click-Here

By: Ali Radwani

## Nikon S9900 # 11

Title: Nikon S9900 # 11

** Subject: Drawer Side with Nikon S9900 **

**[:. Read more about my cameras and lenses Here .:]**

__This Shot:__ In one of my indoor photo-session i take this shot of an old drawer in my living room, using Black and White option, lights coming from the window & Camera in hand

…Click Image to Enlarge…Camera in Hand, F:4 , ISO:400 , Shutter:1/10s
Focal-Point:6mm |

**::..** To see all my Nikon S9900 Photos **Click-Here**

**::..** To see all my Nikon D7100 Photos **Click-Here**

**::..** To see all my Nikon D90 Photos **Click-Here**

By: Ali Radwani

## 30 day of ML with Kaggle

Last week during some search on YouTube, I fond a Two Minutes video talking about a new course on Kaggle that will start on 2nd of August, the Course is about Machine Learning ML with Python in a 30 Day’s. I was not sure if it is Free or Not, later on I fond that it is FREE, so I register to it.

And as a part of the program, we will complete three courses: Python, Intro to Machine Learning, and Intermediate Machine Learning.

My time is very tight, and I don’t know if I can continue to complete the required stages/assignments on time for each stage of the program.. Sure I will Try my best.

Now, I am writing this post in 3rd of August 2021, 6:00pm (GMT+3) .. First want to say they did not start on time, delay 1 day! so today was Day 1 , we start with introduction on Kaggle, the participate in first competition and submitting our solution.

I will try to summarize and drop a post every two-three days .. or so ..

:: Have Fun .. Code with Python ..::

Ali,

## 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

## Sketch: Crane Bird Landing

Here is another sketch using pencil & black ink pen to sketch a Crane Bird Landing on the shores of a Lake. I am sketching to improve my skill .. 🙂

By: Ali..

**Follow me on Twitter: @h_ta3kees**

## 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

## Sketch: The Shark

**The Shark** To keep improve my drawing skills i keep my self busy with sketching every day .. OK .. trying to stick to this challenge #asketchaday, also i keep searching the web and learning from other people. Days ago i fond an instagram account for an amazing artist with reall talent and has a beautiful style in coloring, i go though here paints and the Shark just catch my eye’s, I send her a message asking **if she allow me** to just try to re-drawing her work.. **and she say ” YES .. “** so here she is on the Net

**On Instagram .. Click Here
On Twitter .. Click Here**

**and this is her website: https://sophielongart.co.uk/
**

Back to the Shark I start with pencil, adding some marks and points, then with a 005 very fine black pen draw or say sketched the Shark .. I try to do some coloring .. so here is my draw .. and again Thanks to **Sophielongart **for her kind.

you may Follow me on Twitter **@h_ta3kees**

Here is my sketch.. [ Click to Enlarg]

## 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

## Python: Kadane’s Algorithm

**Learning : Python, Algorithm, Math **

** Subject: Implement the Kadane’s Algorithm**

**Definition:** Kadane’s Algorithm is to search in a one Dimensional Array [integer positive and negative numbers] for a we will largest Sum of contiguous subarray.

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.]

**Algorithm** To find the largest subset sum, we apply coming step:

We will use two variables:

current_max: to hold the max sum of thesub-set

start_again: will be as a flag to re-set the current_max

__ Algorithm: __

1. Start from Element in the array index = 1, save it as start_again. Set Current_max to Array Element in index = 0.

2. Do sumation of start_again with the next element index + 1.

3. If current_max < start_again then re-set current_manx = start_again

4. If start_again < 0 then re-set start_again = 0

5. Repeat from 2 to 4 until the end of the array.

6. If we reach end of the Array, then return the current_max

More from Kadane’s Algorithm:

The aim of Kadane’s Algorithm is to return the Maximum sum of sub-set. But in our code here we will return the following:

1. Maximum sum of largest subset

2. The start Index and the End Index of the subset.

3. printing out the subset.

We will have three options in our application, as following:

1. Kadane’s Algorithm – Fast Run.

2. Kadane’s Algorithm – Step By Step.

9. Exit.

As we are doing in our Algorithms coding, we will use a Main-Menu, and a Function to help the user to enter the Array.

**Coding**

We will start with def create_array(): and will return the Array that the user will enter. here is the code..

Now, here is the code for the Main-Menu and the Main application body. In Main application body code, we will use the while True : loop and calling the main_menu() function then with if statement we will check on the user_selection

The Main-Menu |

Here is the Main Application body code.. |

Last, we will write the Function to get the Kadane’s Sum in a Fast-Run, the details one will be a copy with mode print-out statement to show the steps .. __[All code is in Download Page.]__

As we mentioned, Our Kadane’s function will return three things, the Grates Sum of a sub-set, and to position of that sub-set as start index and end index. Here is the code ..

Here is a Run-Time screen .. |

We done with another Algorithm, looking forwards to solve new one in coming days.

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

To Download my Python code (.py) files

Click-Here

By: Ali Radwani