This document provides an overview of files, lists, and other Python concepts related to text parsing and file I/O. It discusses opening and reading files, searching through file contents, writing to files, and common list operations like traversing, slicing, and modifying lists. It also covers parsing text from files into lists, the difference between objects and values in Python, and how to work with dictionaries. The overall topics covered are files, lists, text parsing, and basic data structures in Python.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
.
This document discusses Python lists and their uses. Lists are a mutable data type that allows storing multiple values in a single variable. Values in a list can be accessed by index and lists can be sliced, concatenated, and modified using built-in methods. Lists are commonly used with for loops to iterate over elements. Strings can be split into lists of substrings using the split() method.
The document discusses files and file handling in Python. It describes the different types of files (text and binary), how to open and close files, the various modes for opening files, and methods for reading and writing data to files. It also covers built-in file attributes, standard files, and exception handling related to file operations.
This document discusses Python lists and loops. It begins by explaining how lists allow storing multiple values in a single variable, unlike separate variables. Lists can hold any data types and values can be accessed by index like strings. The document then demonstrates how to create and manipulate lists using various methods like append, sort, and join. It also introduces for loops, which are commonly used to iterate through lists. Range functions are described that can generate integer sequences to loop over. In the last section, some additional string methods are covered like startswith, endswith, strip, and find.
I have question in c++ program I need the answer as soon as possible.docxdelciegreeks
I have question in c++ program I need the answer as soon as possible
I attached the file
1.1
Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
//
//
//
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2
Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3
Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2.
Lab3D – Two Dimensional Arrays
2.1
Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If we want to visit or process every ele ...
This document discusses lists in Python. It defines lists as sequences that can contain elements of any type. Lists are created using square brackets and their elements can be accessed and modified using indices. Some key list methods mentioned include append(), sort(), and pop(). The document provides many examples of how to construct, access, modify, and perform common operations on lists in Python.
15CS664- Python Application Programming - Module 3Syed Mustafa
This document discusses Python lists and dictionaries. It covers list methods like append(), extend(), sort(), pop(), del(), remove(), as well as built-in functions like len(), max(), min(), sum(). It discusses how lists can be used to store user input and calculate averages. It also covers dictionaries, how they map keys to values, and dictionary methods like len() and the in operator. Finally, it discusses aliasing of mutable objects and how changes made through one reference are visible through other references.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
With pdf.
I wrote anything.
Python elements lists you can study
This is help you to study the python programing.This is useful for your learning.
Happy bro.
.
This document discusses Python lists and their uses. Lists are a mutable data type that allows storing multiple values in a single variable. Values in a list can be accessed by index and lists can be sliced, concatenated, and modified using built-in methods. Lists are commonly used with for loops to iterate over elements. Strings can be split into lists of substrings using the split() method.
The document discusses files and file handling in Python. It describes the different types of files (text and binary), how to open and close files, the various modes for opening files, and methods for reading and writing data to files. It also covers built-in file attributes, standard files, and exception handling related to file operations.
This document discusses Python lists and loops. It begins by explaining how lists allow storing multiple values in a single variable, unlike separate variables. Lists can hold any data types and values can be accessed by index like strings. The document then demonstrates how to create and manipulate lists using various methods like append, sort, and join. It also introduces for loops, which are commonly used to iterate through lists. Range functions are described that can generate integer sequences to loop over. In the last section, some additional string methods are covered like startswith, endswith, strip, and find.
I have question in c++ program I need the answer as soon as possible.docxdelciegreeks
I have question in c++ program I need the answer as soon as possible
I attached the file
1.1
Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
//
//
//
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2
Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3
Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2.
Lab3D – Two Dimensional Arrays
2.1
Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If we want to visit or process every ele ...
This document discusses lists in Python. It defines lists as sequences that can contain elements of any type. Lists are created using square brackets and their elements can be accessed and modified using indices. Some key list methods mentioned include append(), sort(), and pop(). The document provides many examples of how to construct, access, modify, and perform common operations on lists in Python.
15CS664- Python Application Programming - Module 3Syed Mustafa
This document discusses Python lists and dictionaries. It covers list methods like append(), extend(), sort(), pop(), del(), remove(), as well as built-in functions like len(), max(), min(), sum(). It discusses how lists can be used to store user input and calculate averages. It also covers dictionaries, how they map keys to values, and dictionary methods like len() and the in operator. Finally, it discusses aliasing of mutable objects and how changes made through one reference are visible through other references.
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
This document discusses Python lists and dictionaries. It covers list methods like append(), extend(), sort(), pop(), del(), remove(), as well as built-in functions like len(), max(), min(), sum(). It discusses how lists can be used to store user input and calculate averages. It also covers dictionaries, how they map keys to values, and dictionary methods like len() and the in operator. Finally, it discusses aliasing of mutable objects and how changes made through one reference are visible through other references.
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docxchristiandean12115
1.1 Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
// <Your Name>
// <Your Section>
// <Your student id>
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2 Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3 Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2. Lab3D – Two Dimensional Arrays
2.1 Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If.
Python is a programming language developed in 1989 that is still actively developed. It draws influences from languages like Perl, Java, C, C++, and others. Python code is portable, free, and recommended for tasks like system administration scripts, web development, scientific computing, and rapid prototyping. It has a simple syntax and is optionally object-oriented and multi-threaded. Python has extensive libraries for tasks like string manipulation, web programming, databases, and interface design. Popular applications of Python include web development, data analysis, scientific computing, and scripting.
This document provides an introduction to Python programming. It demonstrates how to open a Python terminal or IDE, use basic data types like integers, floats, strings, lists, tuples and dictionaries. It shows how to take user input, read and write files, use conditional and loop statements, define functions, and more. Some key points covered include:
- Python uses indentation rather than braces to define code blocks for conditionals and loops.
- All variables are references to objects, and objects have dynamic types.
- Common data types include integers, floats, strings, lists, tuples, dictionaries, booleans, and None.
- Lists and dictionaries are mutable, while tuples are immutable.
- Functions
This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.
Lists allow storing and manipulating multiple values in a single variable. A list is a mutable collection that can hold elements of any type, accessed by index. Key characteristics of lists include: using square brackets to define lists; mutable elements that can be added, removed, or modified; built-in functions like len(), min(), max(), and sum(); slicing to extract portions; and splitting strings into lists of substrings. Lists are widely used in Python for tasks like collecting related data, looping through elements, and parsing structured data.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and commonly used string and list methods.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and commonly used string and list methods.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
The document provides information about getting started with iPython. It discusses how to install iPython, start iPython, use tab completion and help features. It also demonstrates basic math operations in iPython like addition, subtraction, multiplication, division and rounding numbers. The document then covers plotting graphs using iPython, embellishing plots, multiple plots and loading/plotting data from files. It also introduces key concepts in Python like lists, strings, files, arrays, conditionals, loops, tuples, dictionaries and sets. Finally, the document discusses functions and lambda functions in Python.
Given below is the completed code along with comments. Output of the.pdfaparnacollection
Given below is the completed code along with comments. Output of the program is shown at the
end. You will need to create an input file containing multiple lines of input as specified in the
question. I have given a sample input file with just 1 line of input.
Please do rate the answer if it helped. Thank you very much.
#include
/*
extractBits extracts the specified number of bits starting specified start location from left.
bit numbering starts with 0 from left. len specifies the number of bits to extract.
So extract leftmost 4 bits of a number n, the call should be extractBits(n, 0, 4). Here start = 0
means the 0th bit from left.
Similarly to extract bit 16 through 20 (i.e 5 bits), we use extractBits(n, 16, 5)
The way this function works is - First calculate the remaining number of bits on the rightside .
Since int takes 32 bits, we subtract (start+len) from 32 to get remaining bits on right.
it first clears all the bits upto starting bit by left shift <<
by start bits. Now we shift back the same number of times to right +
*/
int extractBits(unsigned n, int start, int len)
{
int rightRemaining = 32 - (start + len);
//shift left and then right by start no. of bits clears leftside bits
n = (n << start) >> start;
//now shifting by remaining number of bits on right will extract only needed bits
n = n >> rightRemaining;
return n;
}
int main (int argc, char *argv[]) {
// Get the filename to open, then open the file. If we can\'t
// open the file, complain and quit.
char *filename;
// *** Your Code *** if argv[1] exists, set filename to it,
// otherwise set filename to \"Lab3_data.txt\";
if(argv[1] != NULL)
filename = argv[1];
else
filename = \"Lab3_data.txt\";
// Open the file; if opening fails, say so and return 1.
// otherwise say what file we\'re reading from.
FILE *in_file;
in_file = fopen(filename, \"r\"); // NULL if the open failed
// *** Your Code *** if in_file is NULL, complain and quit
// otherwise say that we\'ve opened the filename
if (in_file == NULL){
printf(\"Couldn\'t open file %s\ \", filename);
return 1;
}
printf(\"Opened file %s for reading...\ \", filename);
// Repeatedly read and process each line of the file. The
// line should have a hex integer and two integer lengths.
int val, len1, len2, len3;
int nbr_vals_on_line
= fscanf(in_file, \"%x %d %d\", &val, &len1, &len2);
// Read until we hit end-of-file or a line without the 3 values.
while (nbr_vals_on_line == 3) {
// We\'re going to break up the value into bitstrings of
// length len1, len2, and len3 (going left-to-right).
// The user gives us len1 and len2, and we calculate
// len3 = the remainder of the 32 bits of value.
// All three lengths should be > 0, else we complain
// and go onto the next line.
//
len3 = 32 - (len1 + len2);
// *** Your Code***
// if any of the lengths aren\'t > 0,
// print out the value and the lengths and complain
// about the lengths not all being positive
if(len1 <= 0 || len2 <= 0 || len3 <= 0)
{
printf(\"Invalid lengths : len1=%d, len2=%d, len.
File handling in Python allows programs to read from and write to files stored on the file system. There are different modes for opening files, such as read ("r"), write ("w"), and append ("a"). Common file operations include reading, writing, updating, deleting, and creating files. Files can be opened, read from and written to, then closed. Python supports various data types that can be read from or written to files, such as text, binary, images, and audio files. File handling is an important part of building applications that need to persist data.
This document outlines the objectives and content of a chapter on sequences in Python programming. It discusses strings as a sequence data type and how they can be indexed, sliced, concatenated, and operated on using built-in functions. It introduces lists as another type of sequence that can contain heterogeneous data types. Various string and list operations like indexing, slicing, length calculation, and mutation are demonstrated. The document also covers using strings and lists to represent and look up month abbreviations and names. It concludes by discussing encoding of text as Unicode numbers and providing pseudocode for programs to encode and decode text-based messages.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
More Related Content
Similar to UNIT III PYTHON.pptx python basic ppt ppt
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
This document discusses Python lists and dictionaries. It covers list methods like append(), extend(), sort(), pop(), del(), remove(), as well as built-in functions like len(), max(), min(), sum(). It discusses how lists can be used to store user input and calculate averages. It also covers dictionaries, how they map keys to values, and dictionary methods like len() and the in operator. Finally, it discusses aliasing of mutable objects and how changes made through one reference are visible through other references.
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docxchristiandean12115
1.1 Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
// <Your Name>
// <Your Section>
// <Your student id>
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2 Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3 Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2. Lab3D – Two Dimensional Arrays
2.1 Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If.
Python is a programming language developed in 1989 that is still actively developed. It draws influences from languages like Perl, Java, C, C++, and others. Python code is portable, free, and recommended for tasks like system administration scripts, web development, scientific computing, and rapid prototyping. It has a simple syntax and is optionally object-oriented and multi-threaded. Python has extensive libraries for tasks like string manipulation, web programming, databases, and interface design. Popular applications of Python include web development, data analysis, scientific computing, and scripting.
This document provides an introduction to Python programming. It demonstrates how to open a Python terminal or IDE, use basic data types like integers, floats, strings, lists, tuples and dictionaries. It shows how to take user input, read and write files, use conditional and loop statements, define functions, and more. Some key points covered include:
- Python uses indentation rather than braces to define code blocks for conditionals and loops.
- All variables are references to objects, and objects have dynamic types.
- Common data types include integers, floats, strings, lists, tuples, dictionaries, booleans, and None.
- Lists and dictionaries are mutable, while tuples are immutable.
- Functions
This document provides an overview of lists in Python. It defines what a list is, how to create and access list elements, and common list operations like slicing, concatenation, and modification. It also covers list methods such as append(), insert(), remove(), and sort(). The document discusses lists as mutable objects and the concepts of aliasing and passing lists to functions.
Lists allow storing and manipulating multiple values in a single variable. A list is a mutable collection that can hold elements of any type, accessed by index. Key characteristics of lists include: using square brackets to define lists; mutable elements that can be added, removed, or modified; built-in functions like len(), min(), max(), and sum(); slicing to extract portions; and splitting strings into lists of substrings. Lists are widely used in Python for tasks like collecting related data, looping through elements, and parsing structured data.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and commonly used string and list methods.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and commonly used string and list methods.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction to the Python programming language. It discusses installing Python and interacting with it through command line and IDLE modes. It covers basic Python data types like numbers, strings, lists, and booleans. It demonstrates how to perform operations and call functions on these data types. It also discusses Python modules, getting input from users, and assigning values to variables.
The document provides information about getting started with iPython. It discusses how to install iPython, start iPython, use tab completion and help features. It also demonstrates basic math operations in iPython like addition, subtraction, multiplication, division and rounding numbers. The document then covers plotting graphs using iPython, embellishing plots, multiple plots and loading/plotting data from files. It also introduces key concepts in Python like lists, strings, files, arrays, conditionals, loops, tuples, dictionaries and sets. Finally, the document discusses functions and lambda functions in Python.
Given below is the completed code along with comments. Output of the.pdfaparnacollection
Given below is the completed code along with comments. Output of the program is shown at the
end. You will need to create an input file containing multiple lines of input as specified in the
question. I have given a sample input file with just 1 line of input.
Please do rate the answer if it helped. Thank you very much.
#include
/*
extractBits extracts the specified number of bits starting specified start location from left.
bit numbering starts with 0 from left. len specifies the number of bits to extract.
So extract leftmost 4 bits of a number n, the call should be extractBits(n, 0, 4). Here start = 0
means the 0th bit from left.
Similarly to extract bit 16 through 20 (i.e 5 bits), we use extractBits(n, 16, 5)
The way this function works is - First calculate the remaining number of bits on the rightside .
Since int takes 32 bits, we subtract (start+len) from 32 to get remaining bits on right.
it first clears all the bits upto starting bit by left shift <<
by start bits. Now we shift back the same number of times to right +
*/
int extractBits(unsigned n, int start, int len)
{
int rightRemaining = 32 - (start + len);
//shift left and then right by start no. of bits clears leftside bits
n = (n << start) >> start;
//now shifting by remaining number of bits on right will extract only needed bits
n = n >> rightRemaining;
return n;
}
int main (int argc, char *argv[]) {
// Get the filename to open, then open the file. If we can\'t
// open the file, complain and quit.
char *filename;
// *** Your Code *** if argv[1] exists, set filename to it,
// otherwise set filename to \"Lab3_data.txt\";
if(argv[1] != NULL)
filename = argv[1];
else
filename = \"Lab3_data.txt\";
// Open the file; if opening fails, say so and return 1.
// otherwise say what file we\'re reading from.
FILE *in_file;
in_file = fopen(filename, \"r\"); // NULL if the open failed
// *** Your Code *** if in_file is NULL, complain and quit
// otherwise say that we\'ve opened the filename
if (in_file == NULL){
printf(\"Couldn\'t open file %s\ \", filename);
return 1;
}
printf(\"Opened file %s for reading...\ \", filename);
// Repeatedly read and process each line of the file. The
// line should have a hex integer and two integer lengths.
int val, len1, len2, len3;
int nbr_vals_on_line
= fscanf(in_file, \"%x %d %d\", &val, &len1, &len2);
// Read until we hit end-of-file or a line without the 3 values.
while (nbr_vals_on_line == 3) {
// We\'re going to break up the value into bitstrings of
// length len1, len2, and len3 (going left-to-right).
// The user gives us len1 and len2, and we calculate
// len3 = the remainder of the 32 bits of value.
// All three lengths should be > 0, else we complain
// and go onto the next line.
//
len3 = 32 - (len1 + len2);
// *** Your Code***
// if any of the lengths aren\'t > 0,
// print out the value and the lengths and complain
// about the lengths not all being positive
if(len1 <= 0 || len2 <= 0 || len3 <= 0)
{
printf(\"Invalid lengths : len1=%d, len2=%d, len.
File handling in Python allows programs to read from and write to files stored on the file system. There are different modes for opening files, such as read ("r"), write ("w"), and append ("a"). Common file operations include reading, writing, updating, deleting, and creating files. Files can be opened, read from and written to, then closed. Python supports various data types that can be read from or written to files, such as text, binary, images, and audio files. File handling is an important part of building applications that need to persist data.
This document outlines the objectives and content of a chapter on sequences in Python programming. It discusses strings as a sequence data type and how they can be indexed, sliced, concatenated, and operated on using built-in functions. It introduces lists as another type of sequence that can contain heterogeneous data types. Various string and list operations like indexing, slicing, length calculation, and mutation are demonstrated. The document also covers using strings and lists to represent and look up month abbreviations and names. It concludes by discussing encoding of text as Unicode numbers and providing pseudocode for programs to encode and decode text-based messages.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
Similar to UNIT III PYTHON.pptx python basic ppt ppt (20)
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
2. UNIT III
Files - Persistence - Opening files - Text files and lines -
Reading files - Searching through a file - Letting the user
choose the file name - Using try, except, and open -
Writing files - Lists - A list is a sequence - Lists are
mutable - Traversing a list - List operations - List slices -
List methods - Deleting elements - Lists and functions -
Lists and strings - Parsing lines - Objects and values -
Aliasing - List arguments - Dictionaries - Dictionary as a
set of counters - Dictionaries and files - Looping and
dictionaries - Advanced text parsing.
4. PERSISTENCE
Secondary memory is not erased when the power is turned
off. Or in the case of a USB flash drive, the data we write
from our programs can be removed from the system and
transported to another system.
5. OPENING FILES
When we want to read or write a file (say on your hard drive), we first must
open the file. Opening the file communicates with your operating system,
which knows where the data for each file is stored.
When you open a file, you are asking the operating system to find the file by
name and make sure the file exists.
>>> fhand = open('mbox.txt')
>>> print(fhand)
<_io.TextIOWrapper name='mbox.txt' mode='r' encoding='cp1252'>
If the open is successful, the operating system returns us a file handle. The file handle is
not the actual data contained in the file, but instead it is a “handle” that we can use to
read the data.
If the file does not exist, open will fail with a traceback and you will not get a handle to
access the contents of the file:
>>> fhand = open('stuff.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
6. READING FILES
While the file handle does not contain the data for the file, it is quite
easy to construct a for loop to read through and count each of the lines
in a file:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
If we know the file is relatively small compared to the size of your main memory, we
can read the whole file into one string using the read method on the file handle.
>>> fhand = open('mbox-short.txt')
>>> inp = fhand.read()
>>> print(len(inp))
94626
>>> print(inp[:20])
From stephen.marquar
7. SEARCHING THROUGH A FILE
if we wanted to read a file and only print out lines which started
with the prefix “From:”, we could use the string method startswith
to select only those lines with the desired prefix:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
if line.startswith('From:'):
print(line)
When this program runs, we get the following output:
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
...
8. We could use line slicing to print all but the last character, but
a simpler approach is to use the rstrip method which strips
whitespace from the right side of a string as follows:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if line.startswith('From:'):
print(line)
When this program runs, we get the following output:
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
From: cwen@iupui.edu
...
9. We can structure the loop to follow the pattern of skipping
uninteresting lines as follows:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
# Skip 'uninteresting lines'
if not line.startswith('From:'):
continue
# Process our 'interesting' line
print(line)
we can write the following loop to show lines which contain the string
“@uct.ac.za” (i.e., they come from the University of Cape Town in South Africa):
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if line.find('@uct.ac.za') == -1: continue
print(line)
10. Which produces the following output:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
X-Authentication-Warning: set sender to
stephen.marquard@uct.ac.za using -f
From: stephen.marquard@uct.ac.za
Author: stephen.marquard@uct.ac.za
From david.horwitz@uct.ac.za Fri Jan 4 07:02:32 2008
X-Authentication-Warning: set sender to
david.horwitz@uct.ac.za using -f
From: david.horwitz@uct.ac.za
Author: david.horwitz@uct.ac.za
...
11. LETTING THE USER CHOOSE THE FILE NAME
reading the file name from the user using input as follows:
fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)
We read the file name from the user and place it in a variable named fname and open that file. Now
we can run the program repeatedly on different files.
python search6.py
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt
python search6.py
Enter the file name: mbox-short.txt
There were 27 subject lines in mbox-short.txt
12. USING TRY, EXCEPT, AND OPEN
We need to assume that the open call might fail and add recovery
code when the open fails as follows:
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)
Now when our user (or QA team) types in silliness or bad file names, we “catch” them
and recover gracefully:
python search7.py
Enter the file name: na na boo boo
File cannot be opened: na na boo boo
13. WRITING FILES
To write a file, you have to open it with mode “w” as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print(fout)
<_io.TextIOWrapper name='output.txt' mode='w' encoding='cp1252'>
The write method of the file handle object puts data into the file, returning the
number of characters written. The default write mode is text for writing (and
reading) strings.
>>> line1 = "This here's the wattle,n"
>>> fout.write(line1)
24
The print statement automatically appends a newline, but the write method does not add the newline
automatically.
>>> line2 = 'the emblem of our land.n'
>>> fout.write(line2)
24
When you are done writing, you have to close the file to make sure that the last bit of data is
physically written to the disk so it will not be lost if the power goes off.
>>> fout.close()
15. A LIST IS A SEQUENCE
A list is a sequence of values. In a list, the values can be any type. The values in
list are called elements or items.
Example
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
A list within another list is nested.
['spam', 2.0, 5, [10, 20]]
A list that contains no elements is called an empty list
empty=[ ]
you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = [ ]
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [17, 123] [ ]
16. LISTS ARE MUTABLE
The syntax for accessing the elements of a list is the bracket
operator
The expression inside the brackets specifies the index. The indices
start at 0.
>>> print(cheeses[0])
Cheddar
Lists are mutable because we can change the order of items in a
list or reassign an item in a list. When the bracket operator appears
on the left side of an assignment, it identifies the element of the list
that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
17. A list as a relationship between indices and elements. This
relationship is called a mapping; each index “maps to” one of
the elements.
List indices work the same way as string indices:
Any integer expression can be used as an index.
If you try to read or write an element that does not exist, you get
an IndexError.
If an index has a negative value, it counts backward from the end
of the list.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
18. TRAVERSING A LIST
The most common way to traverse the elements of a list is with a
for loop.
for cheese in cheeses:
print(cheese)
If you want to write or update the elements, you need the indices. A
common way to do that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
A for loop over an empty list never executes the body:
for x in empty:
print('This never happens.')
Although a list can contain another list, the nested list still counts
as a single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
19. LIST SLICES
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the
second, the slice goes to the end. So if you omit both, the slice is a copy of
the whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
A slice operator on the left side of an assignment can update multiple
elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print(t)
['a', 'x', 'y', 'd', 'e', 'f']
20. LIST METHODS
Python provides methods that operate on lists.
For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e‘]
21. DELETING ELEMENTS
Using index of the element one can delete elements from a list
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
pop modifies the list and returns the element that was removed. If you
don’t provide an index, it deletes and returns the last element. If you
don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
['a', 'c']
22. If you know the element you want to remove (but not the
index), you can use remove. The return value from remove
is None.
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']
To remove more than one element, you can use del with a
slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f‘]
23. LISTS AND FUNCTIONS
There are a number of built-in functions that can be used on
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
6
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25
24. total = 0
count = 0
while (True):
inp = input('Enter a number: ')
if inp == 'done': break
value = float(inp)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
numlist = list()
while (True):
inp = input('Enter a number: ')
if inp == 'done': break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
The program to compute an
average without a list:
The program to compute an
average using a list:
25. LISTS AND STRINGS
A string is a sequence of characters and a list is a sequence of
values, but a list of characters is not the same as a string. To
convert from a string to a list of characters, we can use list:
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
The list function breaks a string into individual letters. If you
want to break a string into words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
the
26. You can call split with an optional argument called a delimiter that
specifies which characters to use as word boundaries. The
following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and
concatenates the elements. join is a string method, so you have
to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
27. PARSING LINES
If we want to print out the day of the week from those lines that start with
“From”? The split method is used
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Write a small program that looks for lines where the line starts with “From”,
split those lines, and then print out the third word in the line:
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print(words[2])
The program produces the following output:
Sat
Fri
Fri
Fri
...
28. OBJECTS AND VALUES
If we execute these assignment statements:
a = 'banana'
b = 'banana‘
we know that a and b both refer to a string, but we don’t know whether they refer
to the same string. There are two possible states:
Variables and Objects
In one case, a and b refer to two different objects that have the same value. In the
second case, they refer to the same object.
29. To check whether two variables refer to the same object,
you can use the is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object,
and both a and b refer to it.
But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
30. ALIASING
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object. An object with more than one reference has more than one name,
so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when
you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana'
b = 'banana'
it almost never makes a difference whether a and b refer to the same string or not.
31. LIST ARGUMENTS
When you pass a list to a function, the function gets a
reference to the list. If the function modifies a list parameter,
the caller sees the change. For example, delete_head removes
the first element from a list:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print(letters)
['b', 'c']
The parameter t and the variable letters are aliases for the same
object.
32. It is important to distinguish between operations that modify
lists and operations that create new lists. For example, the
append method modifies a list, but the + operator creates a
new list:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False
33. This difference is important when you write functions that are
supposed to modify lists. For example, this function does not delete
the head of a list:
def bad_delete_head(t):
t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes t
refer to it, but none of that has any effect on the list that was passed
as an argument.
An alternative is to write a function that creates and returns a new
list. For example, tail returns all but the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is
used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print(rest)
['b', 'c']
35. DICTIONARY
A dictionary is like a list, but more general. In a list, the index
positions have to be integers; in a dictionary, the indices can be
(almost) any type.
It is a mapping between a set of indices (which are called keys) and
a set of values. Each key maps to a value. The association of a key
and a value is called a key-value pair or sometimes an item.
As an example, we’ll build a dictionary that maps from English to
Spanish words, so the keys and the values are all strings.
The function dict creates a new dictionary with no items
>>> eng2sp = dict()
>>> print(eng2sp)
{}
The curly brackets, {}, represent an empty dictionary.
36. To add items to the dictionary, you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key 'one' to the
value “uno”. If we print the dictionary again, we see a key-
value pair with a colon between the key and value:
>>> print(eng2sp)
{'one': 'uno'}
This output format is also an input format. For example, you
can create a new dictionary with three items. But if you print
eng2sp, you might be surprised:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print(eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
37. If the key isn’t in the dictionary, you get an exception:
>>> print(eng2sp['four'])
KeyError: 'four'
The len function works on dictionaries; it returns the number of key-
value pairs:
>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether
something appears as a key in the dictionary (appearing as a value
is not good enough).
>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
38. To see whether something appears as a value in a
dictionary, you can use the method values, which
returns the values as a type that can be converted
to a list, and then use the in operator:
>>> vals = list(eng2sp.values())
>>> 'uno' in vals
True
The in operator uses different algorithms for lists
and dictionaries. For lists, it uses a linear search
algorithm. As the list gets longer, the search time
gets longer in direct proportion to the length of the
list.
For dictionaries, Python uses an algorithm called a
hash table.
39. DICTIONARY AS A SET OF COUNTERS
Suppose you are given a string and you want to count how many
times each letter appears.
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)
We are effectively computing a histogram, which is a statistical term
for a set of counters (or frequencies).
The output of the program:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters “a” and “b” appear once; “o”
appears twice, and so on.
40. Dictionaries have a method called get that takes a key and a default value. If
the key appears in the dictionary, get returns the corresponding value;
otherwise it returns the default value. For example:
>>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
>>> print(counts.get('jan', 0))
100
>>> print(counts.get('tim', 0))
0
We can use get to write our histogram loop more concisely. Because the get
method automatically handles the case where a key is not in a dictionary, we
can reduce four lines down to one and eliminate the if statement.
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
41. DICTIONARIES AND FILES
One of the common uses of a dictionary is to count the
occurrence of words in a file with some written text.
Let’s start with a very simple file of words taken from
the text of Romeo and Juliet.
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
42. fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
43. When we run the program, we see a raw dump of all of the
counts in unsorted hash order.
python count1.py
Enter the file name: romeo.txt
{'and': 3, 'envious': 1, 'already': 1, 'fair': 1,
'is': 3, 'through': 1, 'pale': 1, 'yonder': 1,
'what': 1, 'sun': 2, 'Who': 1, 'But': 1, 'moon': 1,
'window': 1, 'sick': 1, 'east': 1, 'breaks': 1,
'grief': 1, 'with': 1, 'light': 1, 'It': 1, 'Arise': 1,
'kill': 1, 'the': 3, 'soft': 1, 'Juliet': 1}
44. LOOPING AND DICTIONARIES
If you use a dictionary as the sequence in a for
statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding
value:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
print(key, counts[key])
The output looks like:
jan 100
chuck 1
annie 42
45. If you want to print the keys in alphabetical order, you first make a
list of the keys in the dictionary using the keys method available in
dictionary objects, and then sort that list and loop through the
sorted list, looking up each key and printing out key-value pairs in
sorted order as follows:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
lst = list(counts.keys())
print(lst)
lst.sort()
for key in lst:
print(key, counts[key])
The output looks like:
['jan', 'chuck', 'annie']
annie 42
chuck 1
jan 100
46. ADVANCED TEXT PARSING
In file romeo.txt, we made the file as simple as possible by
removing all punctuation by hand. The actual text has lots of
punctuation, as shown below.
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
The translate is the most subtle of the methods.
line.translate(str.maketrans(fromstr, tostr, deletestr))
Replace the characters in fromstr with the character in the same
position in tostr and delete all characters that are in deletestr. The
fromstr and tostr can be empty strings and the deletestr parameter
can be omitted.
47. import string
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
48. The following is an abbreviated version of the output:
Enter the file name: romeo-full.txt
{'swearst': 1, 'all': 6, 'afeard': 1, 'leave': 2, 'these': 2,
'kinsmen': 2, 'what': 11, 'thinkst': 1, 'love': 24, 'cloak': 1,
a': 24, 'orchard': 2, 'light': 5, 'lovers': 2, 'romeo': 40,
'maiden': 1, 'whiteupturned': 1, 'juliet': 32, 'gentleman': 1,
'it': 22, 'leans': 1, 'canst': 1, 'having': 1, ...}