Tuesday, October 11, 2022

Programming a Calculator using Python

In this Assignment, you will write a computer program from scratch using the Python programming language. This program will function as a simple calculator.

Objectives

  • Write a simple Python program that performs arithmetic operations based on the user input

Stage 1: A simple calculator

Your calculator should provide the following arithmetic and control operations.

  • Arithmetic Operations
    • Addition (+)                 add(a,b)
    • Subtraction (-)             subtract(a,b)
    • Multiplication (*)         multiply(a,b)
    • Division (/)                  divide(a,b)
    • Power (^)                    power(a,b)
    • Remainder (%)            remainder(a,b)
  • Control Operations
    • Terminate (#)
    • Reset ($)

Write a function select_op(choice) to select the appropriate mathematics function based on the users selection.

The behavior of the program should be as follows:

  • The program should ask the user to specify the desired operation (addition/subtraction/multiplication/division/power/remainder/terminate/reset). You can start with the code already given in the answer box. Also, check the example test cases given below.
  • Once the user inputs/selects an arithmetic operation, the program should ask the user to enter the two operands one by one, separated by Enter key. If the user made a mistake while entering the parameters, he can return to main menu by pressing ‘$’ key at the end of the input string, followed by the Enter key
  • Calculate the result and display the result. Inputs need to be processed as floating point values, even thought the values entered are integers. Example: 2.0 + 4.0 = 6.0
  • Return to main menu after displaying the calculation result
  • All possible errors (at input or at generation of result) should be handled by the program
    • Examples: 

  • Anything other than a number as operand input
  • Anything other than +, -, *, /, ^ and % as arithmetic operators
  • Anything other than # and $ as control operators
  • Division by zero
  • The program should keep running until it is stopped by the user (using the terminate command #)


Task 1: Get user input 

  • Section 1: 

  • Input Arithmetic operation
  • Reset or Termination
  • Section 2: 

  • Input first operand
  • Input second operand
  • Reset or Termination

Task 2: Implement functions that performs given arithmetic operation on the given operands and produces the result

  • Arithmetic operation and the two operands as parameters
  • Return the result of the arithmetic operation

Task 3: Call the calculation function by passing user input to select_op(choice) and display the result from within the select_op(choice) function

        Here are some of the messages you might want to display to the users at certain occasions. Copy and paste them as necessary in your code in appropriate situations to help with auto-grading.  If there is any differences between the output of your code and the expected output, it will be displayed once you click the "Check" button. You can click on "Show differences" button to highlight the difference between outputs. This will be helpful for you to change your code to match the expected output.

"Enter first number: "
"Enter second number: "
"Not a valid number,please enter again"
"Unrecognized operation"
"Something Went Wrong"

=======================================================================


while True:
    
    print("Select operation.")
    print("1.Add      : + ")
    print("2.Subtract : - ")
    print("3.Multiply : * ")
    print("4.Divide   : / ")
    print("5.Power    : ^ ")
    print("6.Remainder: % ")
    print("7.Terminate: # ")
    print("8.Reset    : $ ")

    # take input from the user
    choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
    print (choice)
    
    def select_op(choice): 
        
        return choice
    
    
    if(select_op(choice)==  " ") :  
        continue
        
    if(select_op(choice)==  "$") :  
        continue 
        print(select_op(choice))
    
    if(select_op(choice) == "#") : 
        print("Done. Terminating")
        break
       
    if(select_op(choice) == -1):
        print("Done. Terminating")
        exit()

    try:
        sno1= str(input("Enter first number: "))
        print(sno1)
        _f_num = float(sno1)
    except Exception as e:
        continue
        
    try:
        sno2= str(input("Enter second number: ")) 
        print(sno2)
        
        if(sno2 == "#"):
            print("Done. Terminating")
            exit()
        
        _s_num = float(sno2)
    
    except Exception as e:
        continue
    
    
    if(select_op(choice) == "+") : 
       
        res = _f_num + _s_num
        print(_f_num,"+",_s_num,"=",res)
    
    if(select_op(choice) == "-") : 
        
     
        
        res = _f_num - _s_num
        
        print(_f_num,"-",_s_num,"=",res)

    
    if(select_op(choice) == "*") : 
       
        res = _f_num * _s_num
        print(_f_num,"*",_s_num,"=",res)
        
    
    if(select_op(choice) == "/") : 
       
        try: 
            res = _f_num / _s_num
            print(_f_num,"/",_s_num,"=",res)
            
        except Exception as e:
            res1 = "None"
            print("float division by zero")
            print(_f_num,"/",_s_num,"=",res1)
      
    if(select_op(choice) == "^") : 
        
    
        res = _f_num ** _s_num
        print(float(_f_num),"^",float(_s_num),"=",res)

    
    if(select_op(choice) == "%") : 
         
      
        
        res = _f_num % _s_num
        print(_f_num,"%",_s_num,"=",res)



  
               

    
        


Sunday, October 9, 2022

Selected Sorting Algorithm Q & A Using Java Programming Language

Question 

Assume that a team of 50 players have to arrange in descending order, based on the date of the covid19 vaccine has been taken, to identify 15 players who have vaccinated first. 

(1) Design and develop a suitable sorting algorithm to sort these players based on their vaccination date.

(2) Implement the sorting algorithm using a java programming language. 

(3) Hand trace the algorithm using a completely different set of dates for five players. 

 (4) Calculate the complexity of the program you implemented above.


Answer

Used Bubble Sort Algorithm to Solve this problem.

1)



Bubble sort Pseudocode 




 2) Java code implementaion

import java.time.LocalDate;

      public class Players {

      public String name;

      public LocalDate vDate;

      public Players(String name, LocalDate d) {

            this.name = name;

            vDate = d;

       }

// Function

      public static void sortDesc(Players[] team) {

             int i, j;

            for (i = 0; i < (team.length - 1); i++) {

                  for (j = 0; j < team.length - i - 1; j++) {

 

                        if (team[j].vDate.isBefore(team[j + 1].vDate)) {

                              LocalDate temp = team[j].vDate;

                              team[j].vDate = team[j + 1].vDate;

                              team[j + 1].vDate = temp;

                               String tName = team[j].name;

                              team[j].name = team[j + 1].name;

                              team[j + 1].name = tName;

                        }

                  }

            }

      }

 

 

 //    main method

 public static void main(String[] args) {

            int i;

            Players[] team = new Players[15];

 //     insert 15 players

            team[0] = new Players("Nimal", LocalDate.of(2021, 4, 20));

            team[1] = new Players("Kamal", LocalDate.of(2021, 5, 7));

            team[2] = new Players("Sunimal", LocalDate.of(2021, 5, 1));

            team[3] = new Players("Amali", LocalDate.of(2021, 7, 2));

            team[4] = new Players("Sriua", LocalDate.of(2021, 8, 4));

            team[5] = new Players("Nisha", LocalDate.of(2021, 5, 20));

            team[6] = new Players("Nimala", LocalDate.of(2021, 3, 20));

            team[7] = new Players("Saman", LocalDate.of(2021, 4, 7));

            team[8] = new Players("Sunil", LocalDate.of(2021, 10, 5));

            team[9] = new Players("Shsheka", LocalDate.of(2021, 2, 2));

            team[10] = new Players("Udaya", LocalDate.of(2021, 4, 6));

            team[11] = new Players("Kasun", LocalDate.of(2021, 8, 15));

            team[12] = new Players("Kamani", LocalDate.of(2021, 7, 19));

            team[13] = new Players("Sumeda", LocalDate.of(2021, 6, 14));

            team[14] = new Players("Susan", LocalDate.of(2021, 7, 11));

 

      sortDesc(team);

      System.out.println("Sorted(Desc) vaccinated date players were vaccinated.");

      for (i = 0; i < team.length; i++) {

       System.out.println(" Name: " + team[i].name + " -> Vaccinated date: " +                 team[i].vDate);

      }

    }

 }

___________________________________________________-

Output

Sorted(Desc) vaccinated date players were vaccinated.

 Name: Sunil -> Vaccinated date: 2021-10-05

 Name: Kasun -> Vaccinated date: 2021-08-15

 Name: Sriua -> Vaccinated date: 2021-08-04

 Name: Kamani -> Vaccinated date: 2021-07-19

 Name: Susan -> Vaccinated date: 2021-07-11

 Name: Amali -> Vaccinated date: 2021-07-02

 Name: Sumeda -> Vaccinated date: 2021-06-14

 Name: Nisha -> Vaccinated date: 2021-05-20

 Name: Kamal -> Vaccinated date: 2021-05-07

 Name: Sunimal -> Vaccinated date: 2021-05-01

 Name: Nimal -> Vaccinated date: 2021-04-20

 Name: Saman -> Vaccinated date: 2021-04-07

 Name: Udaya -> Vaccinated date: 2021-04-06

 Name: Nimala -> Vaccinated date: 2021-03-20

 Name: Shsheka -> Vaccinated date: 2021-02-02

 

__________________________________________



   3) Hand trace Bubble sort




4) Complexity of Bubble sort Algorithm


 

           int i, j;

// first loop

                        for (i = 0; i < (team.length - 1); i++) {

// second loop

                                    for (j = 0; j < team.length - i - 1; j++) {

 

                                                if (team[j].vDate.isBefore(team[j + 1].vDate)) {

                                                            LocalDate temp = team[j].vDate;

                                                            team[j].vDate = team[j + 1].vDate;

                                                            team[j + 1].vDate = temp;

 

                                                            String tName = team[j].name;

                                                            team[j].name = team[j + 1].name;

                                                            team[j + 1].name = tName;

                          }

         }

         }


  • In the above code there are two for loops for example “for (i = 0; i < (team.length - 1); i++) “ outer and for (j = 0; j < team.length - i - 1; j++)  inner loop. 
  • The inner loop is executed the following number of times.
  • (n-1) + (n-2) +…+(n-ksorted) = ½(2n-ksorted-1)ksorted . Where ksorted is the number of executions of the outer loop before there is pass during which there are no exchanges.
  • The inner loop contains one comparison and sometimes an exchange.
  • The worst case is derived when ksorted is n-1. The inner loop is executed as follows,                    ½ (2n – (n1) 1)(n1) = ½ n(n1) = O (n2)

                    The main advantage of Bubble Sort is the simplicity of the algorithm.













 

 

 

 

 

 

 

 

 

 

 

 

 

 





Programming a Calculator using Python In this Assignment, you will write a computer program from scratch using the Python programming langua...