Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Problem solving and python programming language unit-1, Study notes of Computer Programming

Question and answer are shortened. Easy to study.

Typology: Study notes

2021/2022

Available from 04/14/2023

fasil-fasil
fasil-fasil 🇮🇳

3 documents

1 / 30

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING
SYLLABUS
OBJECTIVES:
To know the basics of algorithmic problem solving
To read and write simple Python programs.
To develop Python programs with conditionals and loops.
To define Python functions and call them.
To use Python data structures - lists, tuples, dictionaries.
To do input/output with files in Python.
UNIT I ALGORITHMIC PROBLEM SOLVING 9
Algorithms, building blocks of algorithms (statements, state, control flow, functions),
notation (pseudo code, flow chart, programming language), algorithmic problem solving, simple
strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in a
list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi.
UNIT II DATA, EXPRESSIONS, STATEMENTS 9
Python interpreter and interactive mode; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
modules and functions, function definition and use, flow of execution, parameters and arguments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables,
distance between two points.
UNIT III CONTROL FLOW, FUNCTIONS 9
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values, parameters, local and global scope, function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum an array of numbers, linear search, binary search.
UNIT IV LISTS, TUPLES, DICTIONARIES 9
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing - list comprehension; Illustrative programs: selection sort, insertion sort,
mergesort, histogram.
UNIT V FILES, MODULES, PACKAGES 9
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs:
word count, copy file.
TOTAL : 45 PERIODS
TEXT BOOKS
Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updatedfor Python 3,Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python Revised and updated for
Python 3.2, Network Theory Ltd., 2011.
REFERENCES:
John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and
expanded Edition, MIT Press , 2013
Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An
Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Partial preview of the text

Download Problem solving and python programming language unit-1 and more Study notes Computer Programming in PDF only on Docsity!

GE8151 PROBLEM SOLVING AND PYTHON PROGRAMMING

SYLLABUS

OBJECTIVES:

  • To know the basics of algorithmic problem solving
  • To read and write simple Python programs.
  • To develop Python programs with conditionals and loops.
  • To define Python functions and call them.
  • To use Python data structures – - lists, tuples, dictionaries.
  • To do input/output with files in Python. UNIT I ALGORITHMIC PROBLEM SOLVING 9 Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart, programming language), algorithmic problem solving, simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence of operators, comments; modules and functions, function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance between two points. UNIT III CONTROL FLOW, FUNCTIONS 9 Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and global scope, function composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary search. UNIT IV LISTS, TUPLES, DICTIONARIES 9 Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced list processing - list comprehension; Illustrative programs: selection sort, insertion sort, mergesort, histogram. UNIT V FILES, MODULES, PACKAGES 9 Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file. TOTAL : 45 PERIODS TEXT BOOKS Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updatedfor Python 3,Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/) Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011. REFERENCES : John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013 Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.

UNIT I ALGORITHMIC PROBLEM SOLVING

INTRODUCTION

PROBLEM SOLVING

Problem solving is the systematic approach to define the problem and creating number of solutions. The problem solving process starts with the problem specifications and ends with a correct program. PROBLEM SOLVING TECHNIQUES Problem solving technique is a set of techniques that helps in providing logic for solving a problem. Problem solving can be expressed in the form of

  1. Algorithms.
  2. Flowcharts.
  3. Pseudo codes.
  4. Programs

1 .ALGORITHM

It is defined as a sequence of instructions that describe a method for solving a problem. In other words it is a step by step procedure for solving a problem

  • Should be written in simple English
  • Each and every instruction should be precise and unambiguous.
  • Instructions in an algorithm should not be repeated infinitely.
  • Algorithm should conclude after a finite number of steps.
  • Should have an end point
  • Derived results should be obtained only after the algorithm terminates. Qualities of a good algorithm The following are the primary factors that are often used to judge the quality of the algorithms. Time – To execute a program, the computer system takes some amount of time. The lesser is the time required, the better is the algorithm. Memory – To execute a program, computer system takes some amount of memory space. The lesser is the memory required, the better is the algorithm. Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of these may provide more accurate results than others, and such algorithms may be suitable Building Blocks of Algorithm As algorithm is a part of the blue-print or plan for the computer program. An algorithm is constructed using following blocks.
  • Statements
  • States
  • Control flow
  • Function
  1. Read b
  2. If a>b then 4.1. Print a is greater else 4.2. Print b is greater
  3. Stop Repetition control flow Repetition control flow means that one or more steps are performed repeatedly until some condition is reached. This logic is used for producing loops in program logic when one one more instructions may need to be executed several times or depending on condition. Basic Structure: Repeat until CONDITION is true Statements Example Description: to print the values from 1 to n
  4. Start
  5. Read the value of ‘n’
  6. Initialize i as 1
  7. Repeat step 4.1 until i< n 4.1. Print i
  8. Stop Function A function is a block of organized, reusable code that is used to perform a single, related action. Function is also named as methods, sub-routines. Elements of functions:
  9. Name for declaration of function
  10. Body consisting local declaration and statements
  11. Formal parameter
  12. Optional result type. Basic Syntax function_name(parameters) function statements end function Algorithm for addition of two numbers using function Main function() Step 1: Start Step 2: Call the function add() Step 3: Stop sub function add() Step1: Functionstart

Step2: Geta,bValues Step 3: add c=a+b Step 4: Printc Step 5: Return

2 .NOTATIONS OF AN ALGORITHM

Algorithm can be expressed in many different notations, including Natural Language, Pseudo code, flowcharts and programming languages. Natural language tends to be verbose and ambiguous. Pseudocode and flowcharts are represented through structured human language. A notation is a system of characters, expressions, graphics or symbols designs used among each others in problem solving to represent technical facts, created to facilitate the best result for a program Pseudocode Pseudocode is an informal high-level description of the operating principle of a computer program or algorithm. It uses the basic structure of a normal programming language, but is intended for human reading rather than machine reading. It is text based detail design tool. Pseudo means false and code refers to instructions written in programming language. Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. The pseudocode is written in normal English language which cannot be understood by the computer. Example: Pseudocode: To find sum of two numbers READ num1,num sum=num1+num PRINT sum Basic rules to write pseudocode:

  1. Only one statement per line. Statements represents single action is written on same line. For example to read the input, all the inputs must be read using single statement.
  2. Capitalized initial keywords The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE, ENDIF, WHILE, REPEAT, UNTIL Example: Pseudocode: Find the total and average of three subjects RAED name, department, mark1, mark2, mark Total=mark1+mark2+mark Average=Total/ WRITE name, department,mark1, mark2, mark
  3. Indent to show hierarchy Indentation is a process of showing the boundaries of the structure.
  4. End multi-line structures Each structure must be ended properly, which provides more clarity. Example:
  1. Connector Circle A connector symbol is represented by a circle and a letter or digit is placed in the circle to specify the link. This symbol is used to connect flowcharts. Rules for drawing flowchart
  2. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
  3. The flow chart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart.
  4. The usual directions of the flow of a procedure or system is from left to right or top to bottom. Only one flow line should come out from a process symbol.
  5. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, cap leave the decision symbol.
  6. Only one flow line is used in conjunction with terminal symbol.
  7. If flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines.
  8. Ensure that flowchart has logical start and stop. Advantages of Flowchart Communication: Flowcharts are better way of communicating the logic of the system. Effective Analysis With the help of flowchart, a problem can be analyzed in more effective way. Proper Documentation Flowcharts are used for good program documentation, which is needed for various purposes. Efficient Coding

The flowcharts act as a guide or blue print during the system analysis and program development phase. Systematic Testing and Debugging The flowchart helps in testing and debugging the program Efficient Program Maintenance The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part. Disadvantages of Flowchart Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchart becomes complex and difficult to use. Alteration and Modification: If alterations are required the flowchart may require re- drawing completely. Reproduction: As the flowchart symbols cannot be typed, reproduction becomes problematic. Control Structures using flowcharts and Pseudocode Sequence Structure Pseudocode Flow Chart General Structure Process 1 …. Process 2 … Process 3 Example READ a READ b Result c=a+b PRINT c Process 1 Process 3 Process 2 Start a=10,b= c=a+b print c Stop

READ a READ b IF a>b THEN PRINT a is greater Iteration or Looping Structure

  • Looping is generally used with WHILE or DO...WHILE or FOR loop.
  • WHILE and FOR is entry checked loop
  • DO…WHILE is exit checked loop, so the loop will be executed at least once. Pseudocode Flow Chart General Structure WHILE condition Body of the loop ENDWHILE Example Start a=10,b= Stop Print a is greater Yes if (a>b) No Print b is greater Yes if(condition) No Body of the loop

o In python DO…WHILE is not supported. o If the loop condition is true then the loop gets into infinite loop, which may lead to system crash Programming Language

  • A programming language is a vocabulary and set of grammatical rules for instructing a computer or computing device to perform specific tasks. In other word it is set of instructions for the computer to solve the problem.
  • Programming Language is a formal language with set of instruction, to the computer to solve a problem. The program will accept the data to perform computation. Program= Algorithm +Data Need for Programming Languages
  • Programming languages are also used to organize the computation
  • Using Programming language we can solve different problems
  • To improve the efficiency of the programs. Types of Programming Language In general Programming languages are classified into three types. They are
  • Low – level or Machine Language
  • Intermediate or Assembly Language
  • High – level Programming language Machine Language: Machine language is the lowest-level programming language (except for computers that utilize programmable microcode). Machine languages are the only languages understood by computers. It is also called as low level language. Example code: 100110011 111001100 Assembly Language: An assembly language contains the same instructions as a machine language, but the instructions and variables have names instead of being just numbers. An assembler language consists of mnemonics, mnemonics that corresponds unique machine instruction. Example code: start addx,y subx,y INITIALIZE a= WHILE a<10 THEN PRINT a a=a+ ENDWHILE Start a= Stop No if (a<10) Yes Print a a=a+

Interpreted vs. Compiled Programming Language Interpreted Programming Language Compile Programming Language Translates one statement at a time Scans entire program and translates it as whole into machine code It takes less amount of time to analyze the source code but the overall execution time is slower It takes large amount of time to analyze the source code but the overall execution time is comparatively faster No intermediate object code is generated, hence are memory efficient Generates intermediate object code which further requires linking, hence requires more memory Continues translating the program until first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Eg: Python, Ruby Eg: C,C++,Java

3 .ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an algorithm for the solution. Understanding the Problem  It is the process of finding the input of the problem that the algorithm solves.  It is very important to specify exactly the set of inputs the algorithm needs to handle.  A correct algorithm is not one that works most of the time, but one that works Correctly for all legitimate inputs. Interpreted vs. Compiled Programming Language Interpreted Programming Language Compile Programming Language Translates one statement at a time Scans entire program and translates it as whole into machine code It takes less amount of time to analyze the source code but the overall execution time is slower It takes large amount of time to analyze the source code but the overall execution time is comparatively faster No intermediate object code is generated, hence are memory efficient Generates intermediate object code which further requires linking, hence requires more memory Continues translating the program until first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Eg: Python, Ruby Eg: C,C++,Java

3 .ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an algorithm for the solution. Understanding the Problem  It is the process of finding the input of the problem that the algorithm solves.  It is very important to specify exactly the set of inputs the algorithm needs to handle.  A correct algorithm is not one that works most of the time, but one that works Correctly for all legitimate inputs. Interpreted vs. Compiled Programming Language Interpreted Programming Language Compile Programming Language Translates one statement at a time Scans entire program and translates it as whole into machine code It takes less amount of time to analyze the source code but the overall execution time is slower It takes large amount of time to analyze the source code but the overall execution time is comparatively faster No intermediate object code is generated, hence are memory efficient Generates intermediate object code which further requires linking, hence requires more memory Continues translating the program until first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Eg: Python, Ruby Eg: C,C++,Java

3 .ALGORITHMIC PROBLEM SOLVING:

Algorithmic problem solving is solving problem that require the formulation of an algorithm for the solution. Understanding the Problem  It is the process of finding the input of the problem that the algorithm solves.  It is very important to specify exactly the set of inputs the algorithm needs to handle.  A correct algorithm is not one that works most of the time, but one that works Correctly for all legitimate inputs.

Ascertaining the Capabilities of the Computational Device If the instructions are executed one after another, it is called sequential algorithm Choosing between Exact and Approximate Problem Solving

  • The next principal decision is to choose between solving the problem exactly or solving it approximately.
  • Based on this, the algorithms are classified as exact algorithm and approximation algorithm.
  • Data structure plays a vital role in designing and analysis the algorithms.
  • Some of the algorithm design techniques also depend on the structuring data specifying a problem’s instance
  • Algorithm+ Data structure=programs. Algorithm Design Techniques
  • An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving problems algorithmically that is applicable to a variety of problems from different areas of computing.
  • Learning these techniques is of utmost importance for the following reasons.
  • First, they provide guidance for designing algorithms for new problems, Second, algorithms are the cornerstone of computer science. Methods of Specifying an Algorithm
  • Pseudocode is a mixture of a natural language and programming language-like constructs. Pseudocode is usually more precise than natural language, and its usage often yields more succinct algorithm descriptions.In the earlier days of computing, the dominant vehicle for specifying algorithms was a flowchart , a method of expressing an algorithm by a collection of connected geometric shapes containing descriptions of the algorithm’s steps.
  • Programming language can be fed into an electronic computer directly. Instead, it needs to be converted into a computer program written in a particular computer language. We can look at such a program as yet another way of specifying the algorithm, although it is preferable to consider it as the algorithm’s implementation.
  • Once an algorithm has been specified, you have to prove its correctness. That is, you have to prove that the algorithm yields a required result for every legitimate input in a finite amount of time.
  • A common technique for proving correctness is to use mathematical induction because an algorithm’s iterations provide a natural sequence of steps needed for such proofs.
  • It might be worth mentioning that although tracing the algorithm’s performance for a few specific inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively. But in order to show that an algorithm is incorrect, you need just one instance of its input for which the algorithm fails. Analyzing an Algorithm
  1. Efficiency. Time efficiency: indicating how fast the algorithm runs, Space efficiency : indicating how much extra memory it uses

Recursions:

 A function that calls itself is known as recursion.

 Recursion is a process by which a function calls itself repeatedly until some specified condition has

beensatisfied. Algorithm for factorial of n numbers using recursion: Main function: Step1: Start Step2: Get n Step3: call factorial(n) Step4: print fact Step5: Stop Sub function factorial(n): Step1: if(n==1) then fact=1 return fact Step2: else fact=n*factorial(n-1) and return fact

FLOW CHART

Pseudo code for factorial using recursion: Main function : BEGIN GET n CALL factorial(n) PRINT fact BIN Sub function factorial(n): IF(n==1) THEN fact= RETURN fact ELSE RETURN fact=n*factorial(n-1)

Flowchart: Read n Read Guess number Guess=input If Guess>n If Guess<n If Guess==n nope Your guess is too high Your guess is too low Good job Stop Start

2 .Find minimum in a list Algorithm: Step 1: Start Step 2: Read n Step 3:Initialize i= Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5 Step4.1: Read a[i] Step 4.2: i=i+1 goto step 4 Step 5: Compute min=a[0] Step 6: Initialize i= Step 7: If i<n, then go to step 8 else goto step 10 Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8. Step 8.1: min=a[i] Step 8.2: i=i+1 goto 7 Step 9: Print min Step 10: Stop Pseudocode: BEGIN READ n FOR i=0 to n, then READ a[i] INCREMENT i END FOR COMPUTE min=a[0] FOR i=1 to n, then IF a[i]<min, then CALCULATE min=a[i] INCREMENT i ELSE INCREMENT i END IF-ELSE END FOR PRINT min END