Archive
Python: Coffee Consumption – P3
Learning : Python, SQlite3, Dataset, Pandas,
Subject: Create Coffee Consumption Application.
[NOTE: To keep the code as simple as we can, We WILL NOT ADD any 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 part (Part-3) of Coffee Consumption App, we will fill in some code into selected Functions. We will do the following:
- Create Function: Show list.
- Create Function: is_available.
- Create Function: Manager Menu.
- Create Manager Coffee Name Functions: Add, Edit, Delete
So, let’s start with writing the Manager Menu Function and a while loop to take the user selection and trigger the corresponding Function… Here is the Code ..
![]() |
We have two functions to help us in this application, one of them called def show_list(dt,d_id) is to Display the Data we have in the Lookup Tables based on the user selection function. The Function will take two arguments:
dt: data-table (Coffee Name, Coffee Type, Coffee Size)
d_id: id column name, and returning nothing.
Fisrt, let’s look at this Function:
![]() |
The second Function will be used to check if the user selection is available in the database, we will call it def is_available (dt, d_id, check_id) this Function is to check if the passed ID available in the data-set or not. The Function will take three Arguments as:
dt: Data-Table, d_id : Name of id column, check_id : The id we want to search for, and it will Return the data-set. After return, if dataset is empty that’s mean selected id is not available.
Now let’s see the function code..
![]() |
Now we will start writing first three functions to manage the Coffee Name, and will start with Adding New Coffee Name to the lookup Table.
In coming code first we will call the header then show_list(‘coffee_name’,’cn_id’) passing Table Name:’coffee_name’ and id column:’cn_id’ to display the Coffee Names we have on the sccreen. Then we will ask the user to enter the New Name to be added to the database. Here is the Full code..
![]() |
Next we will write the Edit Function, and again after the header and show_list(‘coffee_name’,’cn_id’) we will ask the user to enter the ID of the Coffee Name to be change, here we will do a simple validation on user input. After that we will update the record that the user select. Here is the code..
![]() |
Last Function in this part is to Delete a selected Coffee Name by selection it’s ID, as in the Edit Fnction, the user will select an Id, we will check the availability the will execute the Delete command. Here is the code..
![]() |
What’s Coming: In Part-4 we will do the Follwing:
Writing three Function to Manage the Coffee Type, Functions are: Add New Coffee Type, Edit Coffee Type and Delete a Coffee Type.
..:: Have Fun with Coding ::.. 🙂
| Part 1 | Part 2 | Part 3 | Part 4 | Part 5 |
| Part 6 | Part – | Part – | Part – | Part – |
To Download my Python code (.py) files Click-Here
By: Ali Radwani
Python: Coffee Consumption – P2
Learning : Python, SQlite3, Dataset, Pandas,
Subject: Create Coffee Consumption Application.
[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]
In this part (Part-2) of Coffee Consumption App, we will fill in some code into selected Functions. We will do the following:
- Calling the Main-Menu Function.
- Create header function.
- Create the DataBase.
- Create the Tables.
- Insert the Zero records.
- Insert data into Lookups Table.
So, let’s start with writing the main application body and calling the Main-Menu to trigger a Function based on the user selection. This section will be a calling the main_menu() in a while loop .. here is the code ..
# Main application body
while True :
user_select = main_menu()
if user_select == '1' :
new_data()
if user_select == '2' :
edit_record()
if user_select == '3' :
delete_record()
if user_select == '4' :
#delete_record()
pass
if user_select == '6' :
c_name_type_size_manager()
if user_select == '7' :
create_data_base()
if user_select == '99' :
input('\n\n Thank you for using this Appliation. Press Enter.. > ')
break
If we run the application now, we will see the main-menu but nothing will work because we still did not write any real Functions in the application.
Tables and Zero records:
Now we will write tha function to create the Tables and inserting the Zero record in each of them. All the codes will be in a function called: def create_data_base () : here are the name of the tables we will create:
coffee_con
coffee_name
coffee_type
coffee_size
and here is the full code in the function, in first part we will create the tables, second part will insert the zero record, last we will insert data in the lookup tables (coffee_name, coffee_type and coffee_size)
# def create_data_base ()
def create_data_base () :
os.system('clear')
line2 ="Create Data Base"
header(line2,3,11)
print('\n All the data in the Data-Base will be removed, and can''t be retrieved. ')
if input('\n Press [Y] to Continue, anything else will Stop and Exite. > ') not in ['y','Y'] :
input('\n You Select to stop and Exit. Press any Key .. > ')
return
# Part 1: CREATE TABLE:
sql_coffee_con_t = "CREATE TABLE if not exists coffee_con (c_id INTEGER PRIMARY KEY AUTOINCREMENT, date_t,cn_id int, ct_id int, cs_id int, sex text, rank int )"
sql_coffee_name_t = "CREATE TABLE if not exists coffee_name (cn_id INTEGER PRIMARY KEY AUTOINCREMENT, c_name text )"
sql_coffee_type_t = "CREATE TABLE if not exists coffee_type (ct_id INTEGER PRIMARY KEY AUTOINCREMENT, c_type text )"
sql_coffee_size_t = "CREATE TABLE if not exists coffee_size (cs_id INTEGER PRIMARY KEY AUTOINCREMENT, c_size text )"
# Execute the commands
c.execute(sql_coffee_con_t)
db_conn.commit()
c.execute(sql_coffee_name_t)
db_conn.commit()
c.execute(sql_coffee_type_t)
db_conn.commit()
c.execute(sql_coffee_size_t)
db_conn.commit()
# Part 2: Inserting ZERO records.
c.execute ("INSERT INTO coffee_con (date_t , cn_id, ct_id, cs_id, sex, rank) VALUES(:date_t , :cn_id, :ct_id, :cs_id, :sex, :rank)",{'date_t':'0' ,'cn_id' :0,'ct_id' :0,'cs_id' :0,'sex' :'0','rank' :0})
db_conn.commit()
c.execute ("INSERT INTO coffee_name (c_name) VALUES(:c_name )",{"c_name":'0'})
db_conn.commit()
c.execute ("INSERT INTO coffee_type (c_type) VALUES(:c_type )",{"c_type":'0'})
db_conn.commit()
c.execute ("INSERT INTO coffee_size (c_size) VALUES(:c_size )",{"c_size":'0'})
db_conn.commit()
# Part 3: Inserting Basic Information
coffee_Name_list = ['Black','Latte','Espresso','Americano','Cappuccino','Mocha',
'Lungo', 'Flat white', 'Irish', 'Macchiato','Ristretto','Iced coffee']
coffeeType_list = ['3n1' ,'Pods','Grounded']
coffeeSize_list = ['Samll', 'Medium', 'Large', 'Venti']
for each in coffeeName_list:
c.execute ("INSERT INTO coffee_name (c_name) VALUES(:c_name )",{"c_name":each})
db_conn.commit()
for each in coffeeType_list:
c.execute ("INSERT INTO coffee_type (c_type) VALUES(:c_type )",{"c_type":each})
db_conn.commit()
for each in coffeeSize_list:
c.execute ("INSERT INTO coffee_size (c_size) VALUES(:c_size )",{"c_size":each})
db_conn.commit()
input('\n\n Data-Base Created, Basic Information Inserted. press any key to continue. > ')
[ The Full Code is Available in Download Page. ]
Last Function in this part is the header, it’s just a Title that will bee displayed in a box at the top of each page. Here is the code ..
# Header of the Application
def header(line2,b_l2,a_l2):
os.system('clear')
# The Project Name.
line_1 = "Coffee Consumption"
stars = 40
print('\n',' '*4,'*'*stars)
print(' '*5,'***',' '*5,line_1,' '*7,'***')
print(' '*5,'***',' '*(stars - 8),'***')
print(' '*5,'***',' '*b_l2,line2,' '*a_l2,'***')
print(' '*5,'***',' '*(stars - 8),'***')
print(' '*5,'*'* stars,'\n')
What’s Coming: In Part-3 we will do the Follwing:
- Writing a function show_list.
- Writing the function to Add New Coffee Name.
- Writing the function to Edit a Coffee Name.
- Writing the function to Delete a Coffee Name.
..:: Have Fun with Coding ::.. 🙂
| Part 1 | Part 2 | Part 3 | Part 4 | Part 5 |
| Part 6 | Part – | Part – | Part – | Part – |
To Download my Python code (.py) files Click-Here
By: Ali Radwani
Nikon S9900 Macro shot – 1
Subject: Nikon S9900 Macro shot
This Shot: A Macto-Shot on Fruit, using Nikon S9900. Camera in Hand, F:4.2, ISO:125, Shutter:1/4s
Camera in Hand, F:4.2, ISO:125, Shutter:1/4s
|
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 -P2
Learning : Python, Math, Algorithm
Subject: Sorting Algorithm, Heap Sort P2
[NOTE: To keep the code as simple as we can, We WILL NOT ADD any 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 ..
|
In 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 ADD any 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: 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 ADD any 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
Project: Knapsack Problem
Learning : Python, Math, Algorithm
Subject: Solving Knapsack Problem using Python
[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]
Definition: The knapsack problem is a Problem in Combinatorial Optimization: Given a set of Items, Each with a Weight and a Value or Profit, We need to Determine the Number of Each Item to Include in a Collection so that the Total Weight is Less than or Equal to a Given Limit and the Total Value is as Large as Possible. Source: Wikipedia
In this post we will write three Functions, The Main Menu, one to Collect the data and another to solve the problem. So first, let’s see the Main-Menu ..
# Main Menu of the Project
def main_menu ():
os.system('clear')
print('\n',' '*5,'******************************')
print(' '*5,' ***',' Knapsack Problem',' '*1,'***')
print(' '*5,' ***',' '*22,'***')
print(' '*5,' ******************************')
print('\n',' '*5,"==========[ Main Menu ]==========")
print(' '*5,' 1. About Knapsack Problem.')
print(' '*5,' 2. Collect the Items.')
print(' '*5,' 3. Solve the Problem.')
print(' '*5,' 9. Exit.')
user_choice = input("\n Select from the Menu: > ")
return user_choice
Above Menu will display three option that the user can select from:
1. About Knapsack Problem. [To give simple information about what is Knapsack Problem]
2. Collect the Items. [Will ask the user to Enter the Items and their coresponding Weights and Profits.]
3. Solve the Problem. [The user will Enter the Weight limit we have then we will Solve the problem]
Now we will write the Function to collect the Data from the user we will call it def collect_items(): the user will Enter the Item Name, the Weight and the Value or Profit and will save it in a list, then will return it as item_list. Here is the code and run-time screen.
![]() |
![]() |
After Collecting the Items, the user can select Number (3) from the Menu to Solve the Knapsack Problem. First we will ask user to Enter the Weights Limit we have, then calculating the Profit over Weight for each Items. In Knapsack we select the Items based on the Max w/p for each and store the indexs in a list, and with each selection we must not exceed the weight limits. Here is the code.. ..
![]() |
![]() |
So from the above example, we can achieve the Maximum Profit with weight limits to 50Kg if we take Full Amount of Item a, and Full Amount of Item b and 0.666666666 (0.67) amount of Item c.
1 * 60 = 60
1 * 100 = 100
0.67 * 120 = 80
60 + 100 + 80 = 240
NOTE: The Weight in Knapsack Problem can be weight in kg, or Number/Amount of the item (60 bags, 100 bags ..) or any Unit.
Have fun and do some coding .. 🙂
To Download my Python code (.py) files Click-Here
By: Ali Radwani
Another sketch challenge: Eagle Face
This week sketch challenge @1hour1sketch on Twitter is to Draw an Eagle Face, so here is my sketch using pencil then black Pen, it takes around 15min. More Sketches on my Sketch page ..
you may Follow me on Twitter @h_ta3kees
Here is my sketch..

Python Project: Disarium Numbers in Range
Learning : python code
Subject: Finding the Disarium number
in a range
[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]
Definition We call a Number as A Disarium Number if the Sum of it’s Ddigits Powered with their Respective Position is Equal to the Original Number.
So 89 is a Disarium Number, because 8^1 + 9^2 = 8 + 81 = (89 the original number)
and 135 is also a Disarium Number, because 1^1 = 1, 3^2 = 9, 5^3 = 125 and the Total is [1+3+125 = 135 the original number]
we have a previous post to check if a given number is a Disarium Number or not … Read The Post Here .. In this post we will write the Function to print-out all the Disarium Numbers in a given range.
So our application will ask the user to enter two Numbers as a range From and To, then the disarium_n_range(num1,num2) taking two argument will work through a For loop to check each number in the range and if it is a Disarium Number we will store it in a list (disarium_n =[]) .. Let’s start by the asking the user to Input the range numbers..
# Code to collect the Numbers from the User
print('\n\n This Project will Print-Out all the Disarium Numbers in a given range.')
num1 = input('\n Enter the From Number. > ')
num2 = input('\n Enter the To Number. > ')
And now let’s see the main Function of the application ..
![]() |
Run-Screen for the range From 10 To 99![]() |
Another Run for the Range From 100 To 999
|
End of the post ..
To Download my Python code (.py) files Click-Here
By: Ali Radwani






Follow me on Twitter..





























