### Archive

Posts Tagged ‘Lesson’

## 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: PythonIntro 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: Random Pixel Color – P2

Learning : Python, Math
Subject: Random Coloring Pixels

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

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

Here are some Out-put

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 ::.. 🙂 Follow me on Twitter..

## Python: Sort Algorithm – 3 – Insertion Sort

Learning : Python coding, Math, Algorithm,
Subject: Writing Merge Sorting Algorithm in 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.]

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

Here in this post we will write a function to take a given list 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 and print out the original numbers and the sorted one.

Insertion Sort: Steps of Insertion Sorting Algorithm are:

1. Start with index (x = 1), Compare the Element (k) in index [x] with the Element in index [x-1].
1.1 If Element in [x-1] SMALLER than Element in [x] we swap the two elements.
1.2 Once we Swap we will have new index for k , and again we will compare the (k) in (new index) with element before it (new index -1), and keep moving it to left until we stop at index  or we face an Element GRATER than k.

2. If the Element k GRATER than the element before it, we left k and take the Next Element (to be k) and start comparing K [in x index] with Element in [x-1] index.

3. We do this until k will be in index (length on the list)

Now starting with the codes, as our standard we follow in Sorting Algorithm Applications we will have a Main-Menu and three Items the user will chose among them, and Function to let the user to enter the Numbers [The List or the Array] to be sorted. The Options in the Main-Menu are :
1. Insertion Sort Algorithm – Fast Run.
2. Insertion Sort Algorithm – Step By Step.
9. Exit.

The Fasr-Run we call the create_list(): Function first so the user will Enter the Numbers in the Array, then the Fast-Run will show the sorted Array on the screen.
In the Step-By-Step (Option 2 in the Menu) again calling create_list(): Function first, after the user Enters the Array, we will print-out on the screen each steps of selecting the index, and index-1, the k values and when/if we will SWAP or not.
The last option in the Menu is to Exit the Application (option 9).

Now we start coding.. Here is the Main-Menu.

``` # Main-Menu

os.system('clear')
print('\n\n',' '*5,'******************************')
print(' '*5,' ***','  Sorting Algorithm ',' '*1,'***')
print(' '*5,' ***','     Insertion Sort     ',' '*1,'***')
print(' '*5,' ***',' '*22,'***')
print(' '*5,' ******************************\n\n')
print(' '*7,'1. Insertion Sort Algorithm - Fast Run.')
print(' '*7,'2. Insertion Sort Algorithm - Step By Step.')
print(' '*7,'9. Exit.')

user_choice = input('\n   Select your choice.  > ')
return user_choice ```

Here is the codes for create_list(): to collect the Array from the user..

Finaly, here is the code for the Step-by-Step running for the Insetion Sort Algorithm. It is the same copy of the Fast-Run but with some print statements to show what is happening.

We Done another coding for Sorting Algorithms, another one will be published in coming days..

… Have fun with Coding … 🙂 Follow me on Twitter..

Categories: Learning, Lesson

## 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
os.system('clear')
print('\n',' '*5,'******************************')
print(' '*5,' ***','   Knapsack Problem','   '*1,'***')
print(' '*5,' ***',' '*22,'***')
print(' '*5,' ******************************')
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 .. 🙂 Follow me on Twitter..

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

End of the post .. Follow me on Twitter..

## Python Project: Drawing Cloud Number

Learning : Python, Drawing
Subject: Using Python to Draw Cloud Number

In this project we will write a code to draw a cloud of number, we will do this as layers each layer with different font size and different color density.

To do this we will write a function def draw_cloud(tcolor,max_r,sr,lr) : to fill the screen with max_r random numbers from sr to lr (small range, large ramge) using tcolor color. We will recall the function several time each time we will change the tcolor,max_r,sr,lr. Here is the code .. Follow me on Twitter..

## Python: My Orders Tracker P-4

Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this last part we will write the code to Edit an Order, in editing an order function first we will show all orders and will ask the user to select the one to be EDIT, then we will display that order detail on the screen and ask the user to confirm the action by entering ‘Y’ [our code will handel both y and Y]. We will ask the user about each attribute in the Order details if it need to be change or [Just press Enter to Keep the Current Data], also if the user enter ‘e’ or ‘E’ we will exit from the Editing mode.

Here is the code ..

```# Function to Edit an Order

def edit_order():
os.system('clear')
print("\n==========[ Edit Orders ]==========")

show_order('yes')

edit_order = input('   Select the Order ID to be Edited. [E to Exit] > ')

if edit_order in ['e','E'] :
return
elif not edit_order.isnumeric() :
input('\n   You need to enter an Order''s ID [Numeric]. .. Press any Key .. ')
return

try:

c.execute ("select * from orders where o_id ={}".format(edit_order))
order_list = c.fetchone()

if order_list == [] :
input('\n   ID {} Not Exsist. .. Press any key to continue.  '.format(edit_order))
return

os.system('clear')
print("\n==========[ Edit Orders ]==========\n")
print('\n   Details of the Order you select:\n ')

print(" "*15,"ID: ",order_list)
print(" "*13,"Date: ",order_list)
print(" "*5,"Order Number: ",order_list)
print(" "*12,"Price: ",order_list)
print(" "*9,"Quantity: ",order_list)
print(" "*3,"Shipment Price: ",order_list)
print(" "*7,"Total Cost:  {:.2f}".format((order_list*order_list) + order_list))
print(" "*6,"Description: ",order_list)
print(" "*12,"Image:",order_list)

user_confirm = input("\n\n   You Select to EDIT the above Order, Enter Y to confirm, E to Exit. > ")
if user_confirm in ['e','E'] :
input('\n   You entered ''E'' to Exit. Nothing  will be change. Press any key. ')
return

if user_confirm in ['y','Y'] :
#To Edit the order..

print("#"*57)
print("##"," "*51,"##")
print("##   NOTE: Enter E any time to EXIT/Quit."," "*12,"##")
print("##     OR  JUST Press Enter to keep the Current data."," ##")
print("##"," "*51,"##")
print("#"*57,)

while True :

new_date = input (f'\n   The current date is: {order_list}, Enter the New date as[dd-mm-yyyy] > ')

if e_to_exit(new_date) =='e' : return
if new_date =="" : break   # Break the while loop if the user want to keep the current Date.

if date_validation (new_date) == 'valid' :
break
else :
print(date_validation (new_date))

new_onum = input (f'\n   The current Order Number is: {order_list}, Enter the New Order Number. [E to Exit]. > ')
if e_to_exit(new_onum) =='e' : return

new_qunt = input (f'\n   The current Quantity is: {order_list}, Enter the New Quantity. [E to Exit]. > ')
if e_to_exit(new_qunt) =='e' : return

new_price = input (f'\n   The current Price is: {order_list}, Enter the New Price. [E to Exit]. > ')
if e_to_exit(new_price) =='e' : return

new_ship_price = input (f'\n   The current shipment Price is: {order_list}, Enter the New Quantity. [E to Exit]. > ')
if e_to_exit(new_ship_price) =='e' : return

new_link = input (f'\n   The current link is: {order_list}, Enter the New Link. [E to Exit]. > ')

new_image = input (f'\n   The current Image is: {order_list}, Enter the New Image (path). [E to Exit]. > ')
if e_to_exit(new_image) =='e' : return

new_desc = input (f'\n   The current Description is:\n     {order_list}.\n\n      Enter the New Description. [E to Exit]. > ')
if e_to_exit(new_image) =='e' : return

# Updating the record in the DataBase.
if new_date > '' and new_date != "e" :
c.execute("update orders set order_date = '{}' where o_id = {}".format(new_date,int(order_list)))
db_conn.commit()

if new_onum > '' and new_onum != "e" :
c.execute("update orders set order_num = '{}' where o_id = {}".format(new_onum,int(order_list)))
db_conn.commit()

if new_qunt > '' and new_qunt != "e" :
c.execute("update orders set order_quantity = '{}' where o_id = {}".format(new_qunt,int(order_list)))
db_conn.commit()

if new_price > '' and new_price != "e" :
c.execute("update orders set order_price = '{}' where o_id = {}".format(new_price,int(order_list)))
db_conn.commit()

if new_ship_price > '' and new_ship_price != "e" :
c.execute("update orders set order_price = '{}' where o_id = {}".format(new_ship_price,int(order_list)))
db_conn.commit()

db_conn.commit()

if new_image > '' and new_image != "e" :
c.execute("update orders set order_img = '{}' where o_id = {}".format(new_image,int(order_list)))
db_conn.commit()

if new_desc > '' and new_image != "e" :
new_desc = " ".join([word.capitalize() for word in new_desc.split(" ")])

c.execute("update orders set order_desc = '{}' where o_id = {}".format(new_desc,int(order_list)))
db_conn.commit()

input('\n   One record has been EDITED and Saved... \n      ... Press any key to Continue ...')

else:
input('\n      Wrong input ... Press any key to continue ..')

except:
pass

```

Finish: Now we have an application that will store and retrieve our simple order data.
Enhancement:
We can do some enhancement in [link and image] data part to show and display them in better way.

 Part 1 Part 2 Part 3 Part 4 Follow me on Twitter..

## Python: My Orders Tracker P-3

March 10, 2021 1 comment

Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this part we will write the code to Delete an Order that we have from our system, also we will add some validations on the user input, like if the user enter something not from the menu, or to do so, first we will re-call the show_orders() function that we have and passing the ‘yes’ parameter which means we are calling the function from inside another function [we will not print the function header, and will not clear the screen]. Then we will ask the user to select/Enter the ID of the order to be Deleted, after that we will print tha order details again on the screen and ask the user to confirm Deleting command by entering ‘Y’ … thats it.. let’s write the code..

`# Delete Orderdef del_order():    os.system('clear')    print("\n==========[ Delete Orders ]==========\n")        show_order('yes')        del_order = input('   Select the Order ID to be Deleted. [E to Exit] > ')        if not del_order.isnumeric() :        input('\n   You need to enter an Orders ID [Numeric]. .. Press any Key .. ')        return         elif del_order in ['e','E'] :         return                try:                c.execute ("select * from orders where o_id ={}".format(del_order))          order_list = c.fetchone()                 if order_list == [] :            input('\n   ID {} not exsist.'.format(del_order))            return                os.system('clear')        print("\n==========[ Delete Orders ]==========\n")        print('\n   Details of the Order you select:\n ')            print("   ID: ",order_list)          print("   Date: ",order_list)        print("   Order Number: ",order_list)        print("   Price: ",order_list)        print("   Quantity: ",order_list)        print("   Shipment Price: ",order_list)        print("   Total Cost: {:.2f}".format((order_list*order_list) + order_list))        print("\n   Description:",order_list)        print("   Image:",order_list)        print("   Link:",order_list)            user_confirm = input("\n\n   You Select to DELETE the above Order, Enter Y to confirm, E to Exit. > ")         if user_confirm in ['y','Y'] :            #To Delete the order..             c.execute ("delete from orders where o_id ={}".format(int(del_order)))             db_conn.commit()                         input('\n   One record has been DELETED ... \n      ... Press any key to Continue ...')               elif user_confirm in ['n','N']:            input("\n    You select not to DELETE any thing.   Press any key to Continue .. ")                elif user_confirm in ['e','E']:            input("\n    You select stop the process and EXIT.    ... Press any key to Continue .. ")            return              else:                    input('\n      Wrong input ... Press any key to continue ..')                except:        pass        `
 The user select #3 from the menu to Delete an Order The screen display the list of orders we have in the system, and the user select Order ID Number 3 to delete it. The screen display the details of the order ID 3 and ask the user to confirm the deleting by entering ‘Y’ In Next Post: In the coming post P4 , we will write the codes to Edit an order information.

 Part 1 Part 2 Part 3 Part 4 Follow me on Twitter..

## Python: Data Visualization Part-1

January 6, 2021 1 comment

Learning : python, pygal, Data Visualization, Bar Chart
Subject: Data visualization using pygal library

pygal is a Data Visualization library in python to help us showing our Data as a graph. In coming several posts we will discover and learn how to use the pygal library in simple and easy configuration and style.

First we need to install pygal packeg, to do so write this:
pip install pygal

Now we need some Data to show, in this leson I am using aGalaxy Tab S4, so all the codes will be tested and applyed on trinket.io website [trinket.io alow us to use pygal package online so we don’t need to install it on our divice]

Type of Chart:
pygal has several types of charts that we can use, here we will list them all then in coming posts will use each one with simple data. So what we have:
Line, Bar, Histogram, XY,
Funnel, SolidGauge, Gauge, Pyramid,
Treemap, Maps

Some of those charts has a sub-types such as in Bar char we have: Basic, Stacked and Horizontal. Also for each chart we can add a title and labels and we can use some styles.

So let’s start ..
First we will go for the Bar chart, and we have three sub-types as Basic, Stacked and Horizontal.

First chart: Bar chart:
In this part we will demonstrate the Bar Chart, it has three sub-types as Basic, Stacked and Horizontal.

We assume that our data is the Males and Female ages on first marage, the data will be as dictionary (later we will see how to customize each bar)

``` # Basic Bar Chart using pygal

import pygal
bar_chart = pygal.Bar() # To create a bar graph object

bar_chart.title = "Males and Females First Marage Age"
bar_chart.x_labels=(range(1,6))

bar_chart.render()
```

 Sample code for Basic bar chart Another sub-type in Bar chart is Horizontal-Bar, it is semelar to the Basic but as if fliped 90 degree. Here is the code ..

``` # Horizontal Bar Chart using pygal

import pygal

# HorizontalBar()
HBar = pygal.HorizontalBar()

HBar.title = "Males and Females First Marage Age"

HBar.x_labels=(range(1,6))

HBar.render()
```

 Sample code for Horizontal Bar chart Last sub-type in Bar chart is Stacked Bar were all data of each element will be in one bar. Here is the code and example..

``` # Stacked Bar Chart using pygal

import pygal
# StackedBar()
stackedbar = pygal.StackedBar()
stackedbar.x_labels=(range(1,0))
stackedbar.title = "Males and Females First Marage Age"

stackedbar.render()
```

If we say we have another data-set as “age in First-Divorces” and we want to add this set to the Stacked Bar chart, then we first will create the data-set as:
and we will arrange the code line to be at top,middle or bottom of the bar. Here is the code..

 Sample code for stacke Bar chart with Divorce data Next we will talk about Line chart.

:: Data Visualization using pygal ::

 Part-1Bar-Chart Part-2 Part-3 Part-4 Follow me on Twitter..

Learning : Python Project

In this function we will use the string library to select a random X numbers of letters as a Password length and print it on the screen.

First: We create a list of letters type l_type that hold the following: lowercase, uppercase, digits, punctuation and we will use the (random.choice) to select from the list.
Then we will call the ‘password Generator’ pass_generator function torandomly select a letter based on the selected type, we will do so for a X time (X is the length of the password). In this project we will print the password on the screen, in real-life we can send the password via email or SMS. Here is the Code ..

```# Password Generator Function

"""

Date: Des-2020

This function will use the string library to select a random X numbers of letters as a Password and print it on the screen.

We create a list of letter type l_type that hold the following lowercase, uppercase, digits, punctuation and we will
use the (random.choice) to select from the list, then we will call the 'password Generator' pass_generator function to
randomly select a letter, we will do so for a X time (X is the length of the password). In this project we will print
the password on the screen, in real-life we can send the password via email or SMS.

"""

import random, string

l_type = ["lowercase","uppercase","digits","punctuation"]

def pass_generator(lt) :
if lt =="lowercase":

elif lt =="uppercase" :

elif lt =="digits" :

elif lt =="punctuation":

pass_length = int(input("\n   Enter the password Length: > "))

pass_generator(random.choice(l_type))

``` Follow me on Twitter..