Unit – 1
Problem Solving, Programming and Python Programming
Problems are at the center of what many people do at work every day. Whether you're solving a problem for a client (internal or external), supporting those who are solving problems, or discovering new problems to solve, the problems you face can be large or small, simple or complex, and easy or difficult.
There are four basic steps in solving a problem:
- Defining the problem.
- Generating alternatives.
- Evaluating and selecting alternatives.
- Implementing solutions.
Fig: Problem solving with computers
Problem solving is the act of defining a problem; determining the cause of the problem; identifying, prioritizing, and selecting alternatives for a solution; and implementing a solution.
Aspects:
1. Define the problem
Diagnose the situation so that your focus is on the problem, not just its symptoms. Helpful problem-solving techniques include using flowcharts to identify the expected steps of a process and cause-and-effect diagrams to define and analyze root causes.
2. Generate alternative solutions
Postpone the selection of one solution until several problem-solving alternatives have been proposed. Considering multiple alternatives can significantly enhance the value of your ideal solution. Once you have decided on the "what should be" model, this target standard becomes the basis for developing a road map for investigating alternatives.
3. Evaluate and select an alternative
Skilled problem solvers use a series of considerations when selecting the best alternative.
4. Implement and follow up on the solution
Leaders may be called upon to direct others to implement the solution, "sell" the solution, or facilitate the implementation with the help of others.
Top-down design means to repeatedly divide a problem into (smaller) sub-problems, until they are directly solvable. A top-down design process can be represented by a STRUCTURE DIAGRAM.
Fig: Top-Down Design
a) Algorithm: An algorithm is a step-by-step procedure that will always produce a correct solution. A mathematical formula is a good example of a problem-solving algorithm. While an algorithm guarantees an accurate answer, it is not always the best approach to problem-solving. This strategy is not practical for many situations because it can be so time-consuming. For example, if you were trying to figure out all of the possible number combinations to a lock using an algorithm, it would take a very long time!
b) Heuristics: A heuristic is a mental rule-of-thumb strategy that may or may not work in certain situations. Unlike algorithms, heuristics do not always guarantee a correct solution. However, using this problem-solving strategy does allow people to simplify complex problems and reduce the total number of possible solutions to a more manageable set.
c) Trial and Error: A trial-and-error approach to problem-solving involves trying a number of different solutions and ruling out those that do not work. This approach can be a good option if you have a very limited number of options available. If there are many different choices, you are better off narrowing down the possible options using another problem-solving technique before attempting trial-and-error.
d) Insight: In some cases, the solution to a problem can appear as a sudden insight. According to researchers, insight can occur because you realize that the problem is actually similar to something that you have dealt with in the past, but in most cases, the underlying mental processes that lead to insight happen outside of awareness.
An algorithm is the finite set of English statements which are designed to accomplish the specific task. Study of any algorithm is based on the following four criteria
Characteristics of an Algorithm
a) Input: Algorithm must accept zero or more inputs.
b) Output: Algorithm must provide at least one quantity.
c) Definiteness: Algorithm must consist of clear and unambiguous instruction.
d) Finiteness: Algorithm must contain finite set of instruction and algorithm will terminates after a finite number of steps.
e) Effectiveness: Every instruction in algorithm must be very basic and effective.
Uses of Algorithm
a) Algorithm provide independent layout of the program.
b) It is easy to develop the program in any desired language with help of layout.
c) Algorithm representation is very easy to understand.
d) To design algorithm there is no need of expertise in programming language.
Representation of algorithm
Following is the representation of algorithm of addition of two numbers
a) A flow chart is a diagrammatic / pictorial representation of an algorithm. It is the simplest way of representation of algorithm.
b) Initially an algorithm is represented in the form of flowchart and then flowchart is given to programmer to express it in some programming language.
c) Logical error detection is very easy in flowchart as it shows the flow of operations in diagrammatic form.
d) Once flowchart is ready it is very easy to write a program in terms of statements of a programming language. Following are the symbols used in designing the flowcharts.
Sr. No. | Name of Symbol | Symbol | Meaning / Purpose |
1. | Terminal |
| To indicate START / STOP. Usually it is the first symbol and last symbol used in program logic. |
2. | Input / Output Statement |
| To indicate input / output of Data |
3. | Processing Statement |
| To indicate the processing of instructions. |
4. |
Decision Box |
| To indicate decision making and a branch to one or more alternatives. |
5. | Flow Lines | To indicate the direction of flow of information. | |
6. | Connector |
| It is used when flowchart becomes long and need to be continued. Shows the continuity of the algorithm on the next page. |
Pseudo code is the combination of English statements with programming methodology. In pseudo code, there is no restriction of following the syntax of the programming language. Pseudo codes cannot be compiled. It is just a previous step of developing a code for given algorithm.
Design of algorithm
This is the first step in the creation of an algorithm. Design of algorithm includes the problem statement which tell user about the area for which algorithm is required. After problem statement next important thing required is the information about available and required resources. The last thing required in design of algorithm phase is information about the expected output.
Validation of algorithm
Once an algorithm is designed, it is necessary to validate it for several possible input and make sure that algorithm is providing correct output for every input. This process is known as algorithm validation. The purpose of the validation is to assure us that this algorithm will work correctly independently of the issues concerning the programming language it will eventually be written in.
Analysis of algorithm
Analysis of algorithms is also called as performance analysis. This phase refers to the task of determining how much computing time and storage an algorithm requires. The efficiency is measured in best case, worst case and average case analysis.
Testing of algorithm
This phase is about to testing of a program which coded as per the algorithm. Testing of such program consists of two phases:
Debugging
It is the process of executing programs on sample data sets to determine whether faulty results occur or not and if occur, to correct them.
Profiling
Profiling or performance measurement is the process of executing a correct program on data sets and measuring the time and space it takes to compute the result
Python is a complete programming language with the following features.
1) Simple: Python is a simple and a small language Reading a program written in Python feels almost like reading English. This is in fact the greatest strength of Python which allows programmers to concentrate on the solution to the problem rather than the language itself.
2) Easy tolearn: A Python program is clearly defined syntax. This makes it easy for just anyone to pick up the language quickly.
3) Versatile: Python supports development of a wide range of applications ranging from simple text processing to www browser to games.
4) Free and open source: Python is an example of an open source s/w .Therefore, anyone can feely distribute it, read the source code, edit it and even use the code to write new (free) programs.
5) High-level Language: When writing programs, a Python, the programmer don’t have to worry about the low-level details like managing memory used by the program etc. They just need to concentrate on writing solutions of the current problem at hand.
6) Interactive: Programmer can easily interact with the interpreter directly at the Python prompt to write their programs.
7) Portable: Python is a portable language and hence the programs behave the same on a wide Varity of h/w platforms and has the same interface on all platforms.
8) Object Oriented: Python supports Object-Oriented as well as procedure-oriented style of programming. Python is a powerful yet a simple language for implementing OOP concepts, especially when compared to languages like C++ or Java.
9) Interpreted: Python is processed at run time by the interpreter. You can simply run the program.
10) Dynamic: Python executes dynamically.
11) Extensible: If you want a piece of code not to be accessible for everyone, then you can even code that part of your program in C or C++ and then use them from your Program.
12) Embeddable : Programmer can embedded Python with their C,C++,Active X,CORBA and Java program to give ‘scripting’ capabilities for user.
13) Extensive Libraries: Python has huge library
14) Easy maintenance: Code written in Python is easy to maintain.
15) Secure: The Python Language environment is secure from tampering.
16) Robust: Python programmers cannot manipulate memory directly.
17) Multi-threaded: Python supports multi-threading that is executing more than one process of a program simultaneously.
18) Garbage Collection: The Python run-time environment handles garbage collection of all Python Objects.
It would be surprising to know that Python is actually older than Java, R& JavaScript.
Machine Language - First Generation
Machine language is a programming language for computer. Computer is able to grasp and follow the machine language instructions. It is a low level language written in binary code. These instructions written in binary form are used to transfer into commands such that CPU can understand.
Machine language instructions are written in different lengths to identify the tasks such as transferring and storing of data. These instructions are consists of two parts i.e. the operator and operand. Initial few bits of the instruction is Operator, represents the operation to perform. The remaining bits of an instruction are operand. The operand represents the location where the operation is to perform.
Disadvantages of Machine Language
Machine language program is hard to debug.
Programs require architecture and platform.
Advantages of Machine Language.
Execution of machine language program is faster.
As the computer understands machine language directly, compiler is not required.
Assembly Language - Second Generation
An assembly language is a low level programming language like machine language. In machine language code are written in 0s and 1s.Assembly language provides words for instructions that a programmer can understand. Assembly language provides shorthand for machine language.
An assembler converts code written in assembly language into a machine language. Programming with machine level language is very hard and complex process. As the assembly language provides instructions in the form of words and symbols to program; it becomes more understandable and easy.
Examples of instructions
- ADD – Addition of two values.
- SUB – Subtraction of two values.
- MOV – Move data from one location to another.
- JMP- Jump to other location.
Disadvantage of an assembly language – programming with assembly language is time consuming process.
Advantages of an assembly language
Memory and execution time requirement is less.
Suits to write memory resident programs.
Higher Level Language – Third Generation
A high level language is a programming language constructed into simpler form for programming purpose. High level language provides easy syntax and it is hardware independent. High level language provides more focus on programming language instead of use of hardware components like memory addressing and register usage.
High level languages are closer to the humans than the computer. The source code of high level language is converted into low level language then run by the CPU as the computer is not able to understand the syntax of high level language.
Example C, C++, Java, PHP, Python.
Advantages of High Level Language
a) High level language is easy read, write and store.
b) It is a hardware independent language.
c) It is easy to program, to debug and to find the errors.
Disadvantages of High Level Language
a) It requires more time to convert source code to machine code.
b) High level language programs are slow than low level language.
c) These are less memory efficient.
d) High level language can’t communicate directly with hardware.
Very High-level Languages - Fourth generation language
This is called as very high-level programming languages needed a lot of time effort that affected the productivity of a programmer. To reduce the time, cost and effort needed to develop, the fourth generation programming languages were designed and developed for different types of software applications.
Advantages of fourth generation languages
a) Allow the efficient use of data by implementing the different types of database.
b) To develop different types of software applications, need less time, cost and effort.
c) The program develops using these languages are highly portable as compared to the programs in other languages of different generation.
Examples: SOL, CSS, coldfusion
5. Artificial Intelligence Language - Fifth generation language
The programming languages of this generation mainly focus on constraint programming. Artificial Intelligence and Artificial Neural Networks are the major fields in which the fifth generation programming language are employed
Advantages of fifth generation languages
a) These languages can be used to query the database.
b) In a simple and an easy manner the user can communicate with the computer system.
Examples: mercury, prolog, OPS5
Writing Python Programs & Executing then
Step 1 : Open an editor
Step 2: Write the instructions
Step 3: save it as a file with the filename having the extension .py
Step 4 : Run the interpreter with the command python program_name .py or use IDLE to run the program.
To execute the program at the command prompt simply change your working directory.
Literal constants
The value of a literal constant can be used directly in programs.
For example, 7,3.9, ‘A’, and “Hello” are literal constants.
A Constant value cannot be changed. Hence it is Known as literal constant.
Floating point numbers.
Number of a + bi form (like -3 + 7i) are complex number
Variables and identifiers
Variables are examples of identifier.
Identifiers as the name suggests, are name give to identify something.
This something can be a variable, function, class module or other object.
For naming any identifier, these are some bas rules that you must follow, These rules are
a) The First character of an identifier must be an underscore (‘_’) or a letter (upper or lower case).
b) The rest of the identifier name can be underscoring letter (upper or lower), or digits(0-a).
c) Identifier names are case-sensitive, for example,myvar and myVar are not the same.
d) Punctuation character such as @,$ and % are not allowed within identifier.
Examples of valid identifier names are sum,_my_var,num1,r,var_20,first.
Example of invalid identifier names are 1num,my_var,% check, Basic sal,H # R & A.
a) Variables can hold values of different types called data types.
b) Thus ,we need different data types to store different type of values in the variables.
c) The basic types are numbers & strings.
d) The five standard data types supported by Python includes numbers,string,List,tuple & Dictionary.
Input Operation:
Python makes use of input () function. The input () function prompts the user to provide some information on which the program can work and give the result.
Eg: - name = input (“What’s your name? “)
age = input (“Enter your age:”)
print (name + “, you are” + age + “years old”)
O/P : What’s your name ? Garansh
Enter your age : 10
Goransh,you are 10 years old
Comments
Comments are the non_executable statements is program.
They are just added to describe the statement is the program code .
Eg : # This is a comment
Print(“Hello”) # to display hello
# Program ends here
O / P : Hello
Reserved Words
In every programming language there are certain words which have a pre-defined meaning.
These words which are also known as reserved word or keywords cannot be used for naming identities.
Reserved Words
and assert break class continue def del |
exec finally for from global if import |
not or pass print raise return try |
elif else except |
in is lambda |
while with yield |
Indentation
a) Whitespace at the beginning of the line is called indentation .These whitespaces or the indentation are very important in Python.
Eg : age = 21
Print(“ You can vote”) # Error ! Tab at the
Traceback(most recent call last) : start of the line
File “ C :\Python 34 \ try.py”,Line 2
Print(“You can vote”)
Indentation Error : unexpected indent
b) Python very strictly checks the identification Level are gives an error if indentation is not correct. manipulate the value of operands.
c) Some exercise operator include + , - , * , / .
Eg : sum = a + b , a & b are operands and + is operator
d) Python supports different types of operations.
Comparison operators also known as relational operator are used to compare the values on its either sides and determines the relation between then .
Assuming a = 100 & b = 200
Operator Description Example O / P |
= = Returns true if the 2 values are >>>print(a = =b) False |
Exactly equal |
! = Return True if the 2 values are >>>print(a!=b) True |
Not equal |
> Return on L is greater than R >>>print(a>b) False |
< Return on R is greater than L >>>print(a<b) True |
>= Return T if the value on L is |
Either greater or equal than R >>>print(a>=b) False |
<= Return T if the value on R is |
Either greater or equal than L >>>print(a<=b) True |
Expression in Python
- An expression is any legal combination of symbols (like variables ,constant and operators that represent a value .
- Operand is the value on which operator is applied.
Types of Expressions
1) Based on position of operators in an expression
a) Infix Expression : Operator is placed in between the operands Eg : a = b – c
b) Prefix Expression : The Operator is placed before the operand Eg : a = bc
c) Postfix Expression : The Operator is placed after the operand Eg : a = bc
2) Based on the data types of the result obtained on evaluating an expression :
a) Constant Expressions : On that involves only constants.
Eg . 8 + 9 – 2
Integral Expression : One that produces an integer result after evaluating the expression
Eg. a = 10
b = 5
c = a * b
c) Floating Point Expression : One that produces floating point results .Example : a * b/2
d) Relational Expressions : One that returns either true or False value .Example : c = a > b.
e) Logical Expressions : One that combines two or more relational expressions and return a value as True or False Example : a > b && y != 0
f) Bitwise Expression : One that manipulates data at bit level . Ex : x = y & z
g) Assignment Expressions : One that assigns a values to a variable Eg. c = a + b or c = 10
Reference Books
- R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
- Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
- Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
- Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
- Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810