Archive

Archive for the ‘math’ Category

Python: Grade_2 Math Questions V1

October 31, 2022 Leave a comment

Learning : Python, Math
Subject: Math Questions for Grade-2 V.1

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

  • Start Play the Game. [All Math Lessons]
  • Re-set the Numbers Range.
  • Register New Kid to Play.
  • Questions Like: x (+ -) y = ??
  • Questions Like: x (+ -) ?? = y
  • Questions Like:
    x
    y (+ -)
    _______________
    ??

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



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

    By: Ali Radwani

    Python: Tower of Hanoi

    September 15, 2021 Leave a comment

    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')
    

    python project code Tower of Hanoi ali radwani



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

    To Download my Python code (.py) files Click-Here



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

    By: Ali Radwani

    Python: Generate your Data-Set

    August 8, 2021 1 comment

    Learning : Python, pandas, function
    Subject: Generate your CSV dataset 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.]

    The Story:
    last week i was reading about Data Cleaning, Deep Learning and Machine Learning, and for all we need some data to play with and testing our code. There are several sites providing a free (to certain limits) Data-set. But while i was working, it just come to my mind Why not to write a code to generate some Fake data-set.

    Before I start:
    The main question was “What is the subject of the data” or Data about What? This is the main question that will guide us to write our code, and tha answer was very..very fast 🙂 .. at that moment I was holding my Coffee Mug, and just jump to my mind, Data about Coffee … Coffee Consumption. So we are taking the data of Coffee Consumption from a Coffee-Shop, the coffee-shop is collecting the following data: Date-Time (of the order), Coffee-Name, Coffee-Type, Coffee-size, Sex, Rank. Here is in more details..

    Dat-Time: Date and Time of Order, Date format: dd-mm-yyyy, the Time format: hh:mm (24h)

    Coffee-Name: Such as: [black, latte, espresso, americano, cappuccino, mocha, lungo, flat white, irish, macchiato,ristretto, iced coffee]

    Coffee-Type: 3n1 , pods, grounded

    Coffee Size: samll, medium, large, venti  

    Sex: The person how order it male, female 

    Rank: if the customer drink the coffee in the shop, will ask for a ranks (1,10) 1:bad, 10:Grate

    Scope of Work: We will write several functions to generate random data for each attribute we have, saving the data into a list, then combining all the lists in a pandas dataframe df and save the data_set df to a csv file. Later on we can re-call the file using pandas command df.read_csv(file_name) and manipulate the data.

    .::.. Coding ..::.
    Let’s start with Date-Time Function: def fake_date_time(from_y,to_y): In this function we will use a random.randint() to generate numbers for day’s, months and years, also for hours and minites. The function will take two arguments from_y, to_y and will return a string like this: dd-mm-yyyy hh:mm … here is the code ..

    ali radwani python code project


    Now,Coffee Name: def fake_coffee_name() : for Coffee Name I create a list of Coffee Names (from the net) and use random.choice(coffee_name_list) to select one from the list. this function is a one-line code .. here it is ..

     # fake_coffee_name() function
    
    def fake_coffee_name() : 
        """
            Function to randomly select one from the list. 
            
            Return coffee_name 
            
         """ 
        
        coffee_name_list = ['black', 'latte', 'espresso', 'americano', 'cappuccino', 
                             'mocha', 'lungo', 'flat white', 'irish', 'macchiato', 'ristretto', 
                             'iced coffee'
                             ] 
        return random.choice(coffee_name_list) 
    



    Here are another two Functions def fake_coffee_type(): and def fake_coffee_size(): Both are using the random.choice to select from a list.. here is the code ..

    ]ali radwani python code project



    More over, in out dataset we need another two variables sex and rank, both are simple and we don’t need to put them in separate function, we will call the random.choice(‘f’,’m’) to select between Male and Female, and random.randint (1,11) to select a Rank between (1 and 10). Here is the main part of the application, we will use a for loop and append all the returns from the function’s in a list (a list for each attribute) after that we will combine all the list in a dataset using pandas command. Here is the code..

     # Main body of the application
    
    # empty lists of the columns
    d_d =[] 
    cn_d =[] 
    ct_d =[] 
    cs_d =[] 
    s_d =[] 
    r_d = [] 
    
    number_of_rows = 1000 
    
    for x in range(1,number_of_rows): 
        d_d.append(fake_date_time(2000,2022)) 
        cn_d.append(fake_coffee_name()) 
        ct_d.append(fake_coffee_type()) 
        cs_d.append(fake_coffee_size()) 
        s_d.append(random.choice(['f','m'])) 
        r_d.append(random.randint (1,11)) 
        
    
    the_data ={'date_time':d_d, 'c_name':cn_d, 'c_type':ct_d, 'c_size':cs_d, 'sex':s_d, 'rank':r_d } 
    
    df = pd.DataFrame (the_data) 
    
    # to create a CSV file and save the data in it. 
    file_name = 'coffee_consumption_v1.csv'
    df.to_csv(file_name, index=False)
    
    print(f'\n\n    The data been generated, a file named: {file_name} saved')
    



    Now we have a file called: coffee_consumption_v1.csv saved in the same directory of the .py code file. Here is a sample of the data.

    ali radwani python code dataset



    We will stop here, and we will do another post to apply pandas commands over the dataset.

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


    To Download my Python code (.py) files Click-Here
    Also the Date-Set coffee_consumption_v1 file (.csv) files is available in the same page.



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

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

    ali radwani ahradwani.com python code project draw color
    Here are some Out-put

    Run No.1python code project color pixcel ali radwani Run No.2
    python code project color pixcel ali radwani
    Run No.3
    python code project color pixcel ali radwani
    Run No.4
    python code project color pixcel ali radwani


    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



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

    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 TREEali radwani ahradwani.com python code heap sorting binary tree FULL BINARY TRTEEali radwani ahradwani.com python code heap sorting binary tree
    COMPLETE BINARY TREEali radwani ahradwani.com python code heap sorting binary tree COMPLETE BINARY TREEali radwani ahradwani.com python code heap sorting binary tree
    PERFECT BINARY TREEali radwani ahradwani.com python code heap sorting binary tree PERFECT BINARY TREEali radwani ahradwani.com python code heap sorting 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.

    ali radwani python code math sorting algorithm Heap



    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



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

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

    ali radwani ahradwani.com python project code radix sorting algorithm

    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



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

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

    Ali radwani python project code Kadane Algorithm



    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
    Ali radwani python project code Kadane Algorithm
    Here is the Main Application body code..

    Ali radwani python project code Kadane Algorithm



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

    Ali radwani python project code Kadane Algorithm
    Here is a Run-Time screen ..

    Ali radwani python project code Kadane Algorithm



    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



    ali radwani ahradwani.com python projects codeFollow me on Twitter..

    By: Ali Radwani

    Python: Sorting Algorithm (3. Merge Sort)

    June 3, 2021 3 comments

    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
    1. Quick Sort. [Click Here]
    2. Bubble Sort. [Click Here]
    3. Merge Sort. [Click Here]
    4. Insertion Sort. [Click Here]
    5. Selection Sort. [Click Here]
    6. Heap Sort. [Click Here]
    7. Radix Sort. [Click Here]
    8. Bucket Sort. [Click Here]

    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.

    Merge Sort: Steps of Merge Sorting Algorithm are:

    1. If the Array has 1 Element then return it.
    2. If the givin Array has more than 1 Element then we Divide it into 2 Parts.
    Left = from Element 0 T0 Element len(arr)//2
    and Right = from Element len(arr)//2 To Element len(arr). And we keep repeating step 2 for each part.
    3. Once we have All parts divided we tart merge them in a sorted order.

    Coding: In this Post we will write the Function for Main-Mnu, another one to collect the Array [Not Sorted] Elements from the user, then we will write the Main Function, here we will have One to Divide the Array into parts and One to Merge the Element together again. And as we done with Quick & Bubble Sort projects we will have one Fast-Run Function and another one with Details Step-By-Step run to show the Algorithm.

    NOTE: All the Code will be Available in the Download Page.

    Let’s start with the Main-menu to list down three option were the user will select one among them, the menu options are: 1. Merge Sort Algorithm – Fast Run. & 2. Merge Sort Algorithm – Step By Step and the last one is 3. Exit.
    Here is the code.

    python code project main menu by Ali Radwani merge sort Algorithm

    I will Not post the code for collecting the Array Element from the user [Find it in the .py file for this project]. Here is the code for merge_sort_divider Function, it takes two arguments the Array and the user_selection, so if the user selection is 2 (2. Merge Sort Algorithm – Step By Step) We will print-out the Dividing Steps and some other Text. [We are using If Statement to print-out Text lines]. Here is the Code ..

    ali radwani python code merge sort algorithm



    Now for merging function, for merging function we will have two copies, one as Fast-Run and another for Details to print-out the running Steps, this will make the Fast-Run Function short and easy to follow-up. So, here is the Fast-Run Function code for merge the two part of array returned from the merge_sort_divider. Here is the Code ..

    Run time screen ..

    ali radwani python code merge sort algorithm



    End of Merge Sorting Algorithm.

    To Download my Python code (.py) files Click-Here



    Follow me on Twitter..

    By: Ali Radwani

    Python Project: Disarium Number

    April 4, 2021 1 comment


    Learning : Python to solve Mathematics Problems
    Subject: Disarium Number

    In Mathematics there are some formulas or let say rules that generate a sequence of given a certen result, and accordingly we gave that number or that sequence a name, such as even numbers, odd numbers, prime numbers and so on.

    Here in this post we will talk about the Disarium Number and will write a code to check if a given number Disarium or Not.
    Defenition: A Number is a Disarium if the Sum of its digits powered with their respective position is equal to the original number. Example: If we have 25 as a Number we will say: if (2^1 + 5^2) = 25 then 25 is Disarium.
    So: 2^1 = 2, 5^2 = 25, 2+25 = 27; 25 NOT Equal to 27 then 25 is NOT Disarium.

    Let’s take n = 175:
    1^1 = 1
    7^2 = 49
    5^3 = 125
    (1 + 49 + 125) = 175 thats EQUAL to n so 175 is a Disarium Number.

    In the bellow code, we will write a function to take a number from the user the check if it is a Disarium Number or not. In this function we will print out the calculation on the screen. Let’s start by writing the function

    # is_disarium function.
    def is_disarium(num) :
    """
    Project Name: Disarium Number
    By: Ali Radwani
    Date: 2.4.2021
    """


    the_sum = []
    l = len(num)
    for x in range (0,l):
    print(num[x] , '^',x+1,'=', (int(num[x])**(x+1)))
    the_sum.append((int(num[x])**(x+1)))

    if int(num) == sum(the_sum) :
    print ("\n The sum is {}, and the original Number is {} So {} is a Disarium Number.".format(sum(the_sum),num,num))
    else:
    print ('\n The sum is {}, and the original Number is {} So it is NOT Disarium.'.format(sum(the_sum),num))


    num = input('\n Enter a Number to check if it is Disarium. > ')

    # Call the function and pass the num.
    is_disarium(num)
    ali radwani python project learning sql codeing

    To Download my Python code (.py) files Click-Here


    Follow me on Twitter..


    By: Ali Radwani