How to step through and process the elements of a list

Assignment Help Python Programming
Reference no: EM131309008

Programming in Python CS21A

Lab I: Lists and Tuples - Files

Learning Objectives for this lab include:

- Understand list basics including elements and subscripts.
- Learn how to find high and low values of a list.
- Learn how to step through and process the elements of a list.
- Learn how to pass lists as arguments to a function.
- Learn how to write lists in Python code.
- Open a text file for output and write strings or numbers to the file
- Open a text file for input and read strings or numbers from the file

An array is called a list in Python. A list is an object that contains multiple data items. Lists are mutable, which means that their contents can be changed during a program's execution. Lists are dynamic data structures, meaning that items may be added to them or removed from them.

Index or subscript starts at 0 in Python.

Numeric Arrays

Elements of an array can be defined as follows if the values are known:

even_numbers = [2, 4, 6, 8, 10]

If the numbers are not known at the beginning, use the repetition operator (*) to create a list with a specific number of elements, each with the same example. The following will create an array of 10 elements all set to 0 in the beginning.

numbers = [0] * 10
String Arrays

Elements of a string array are initialized as follows:

names = ['Molly', 'Will', 'Alicia', 'Adriana']
Printing Values of the Array
This can be done in one sequence by the following:
print (even_numbers)
The will result in the list printing as follows: [2, 4, 6, 8, 10].
Using Loops and Index

In most cases, a loop should be used to get values in or out of an array. This will allow a specific index to be specified. A for loop or a while loop will work.

The for loop
numbers = [99, 100, 101, 102]
for n in numbers:
print(n)

The while loop
index = 0
while index < 4:
print (my_list[index])
index += 1

Lists and Tuples

- Lists are mutable; tuples are immutable.
- Lists and tuples are sequences.
- Lists allow assignment: L[3] = 7

Tuples do not.

Standard operations:

- length function: len(L)
- membership: in
- max and min: max(L) and min(L)
- sum: sum(L)

Indexing and Slicing

Given: L = ['b', 7, 6, 5,[2,9,1],5.5]

- Tuples work the same with indexing and slicing.
- Indexing starts at 0: L[0] is ‘b'.
- Negative indices work backward from the end: L[-1] is 5.5.
- Slicing selects a subset up to but not including the ?nal index: L[1:4] is [7,6,5].
- Slicing default start is the beginning, so L[:3] is ['b', 7, 6].
- Slicing default end is the end, so L[4:] is [[2, 9, 1], 5.5].
- Using both defaults makes a copy: L[:].
- Slicing's optional third argument indicates step: L[:6:2] is ['b', 6, [2, 9, 1]].
- The idiom to reverse a list: L[::-1] is [5.5, [2, 9, 1], 5, 6, 7, 'b'].

List Methods (partial list)

Given: L1 = [1,3,2] and L2 = [7,8]

- L1.append(0) changes L1 to be [1,3,2,0].
- L1.append(L2) changes L1 to be [1,3,2,[7,8]].
- L1.extend(L2) changes L1 to be [1,3,2,7,8].
- L1.sort() changes L1 to be [1,2,3].
- L1.insert(2,11) inserts 11 before index 2, so L1 becomes [1,3,11,2].
- L1.remove(3) removes 3, so L1 becomes [1,2].
- L1.reverse() changes L1 to be [2,3,1].
- L1.pop() pops 2 off, so L1 becomes [1,3] and returns 2.

Programming in Python

Methods Shared by Lists and Tuples (partial list)

Given: L1 = [1,3,2] and L2 = [7,8]

- L1.index(3) returns the index of item 3, which is 1.
- L1.count(1) counts the number of 1's in L1: 1 in this case.

Writing to a File

When writing to a file, an internal file name must be created, such as outFile.

This file must then be opened using two arguments. The first argument is the name of the file and the second is the mode you want to open the file in. You can select either the ‘a' append mode or the ‘w' write mode. For example:

outFile = open('filename.txt', 'w')
Files must then be closed. This works the same for both input and output.
outFile.close() or inFile.close()
Reading from a File

When reading from a file, an internal file name must be created such as inFile.

This file must then be opened using two arguments. The first argument is the name of the file and the second is the mode you want to open the file in, ‘r' for read. For example:

inFile = open('filename.txt', 'r')

Reading from a file is done sequentially in this lab, and a call to read must occur. If a string header is done first, that must be read into a string variable. That variable can then be used for processing within the program.

A string literal can be read from a file and displayed to the screen such as:

str1 = inFile.read()
print (str1)

Arrays and variables can be read as a single input such as:

arrayName = inFile.read()
print (arrayName)

Lab 1: Total Sales

1. Open the program TotalSales.py file.
2. Fill in the code so that the program will do the following:

- Ask the user to enter a store's sales for each day of the week.
- The amounts should be stored in a list.
- Use a loop to calculate the total sales for the week and display the result.

Python Code:

def main():

# Variables
total_sales = 0.0
# Initialize lists
daily_sales = [0.0,0.0,0.0,0.0,0.0,0.0,0.0]
days_of_week = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]

'''Fill in this space to ask the user to enter a store's sales for each day of the week. The amounts should be stored in a list.

Use a loop to calculate the total sales for the week and display the result'''

print ("Total sales for the week: tiny_mce_markerquot;, format(total_sales, '.2f'), sep='')
main()

Here is a sample run of the program:

Enter the sales for Sunday: 56
Enter the sales for Monday: 23
Enter the sales for Tuesday: 67
Enter the sales for Wednesday: 23
Enter the sales for Thursday: 42
Enter the sales for Friday: 78
Enter the sales for Saturday: 23
Total sales for the week: $312.00

Lab 2 - Charge Account Validation

1. Open the program AccountValidation.py file.
2. Fill in the code so that the program will do the following:

- Read the contents of the file into a list.
- Ask the user to enter a charge account number.
- Determine whether the number is valid by searching for it in the list. If the number is in the list, the program should display a message indicating the number is valid. If the number is not in the list, the program should display a message indicating the number is invalid.

The file charge_accounts.txt has a list of a company's valid charge account numbers. Each account number is a seven-digit number, such as 5658845.

Save the code to a file by going to File Save.

Python Code:

def main():
# Local variables
test_account = ''

# Open the file for reading
input_file = open('charge_accounts.txt', 'r')

# Read all the lines in the file into a list
accounts = input_file.readlines()

# Strip trailing '\n' from all elements of the list
for i in range(len(accounts)):
accounts[i] = accounts[i].rstrip('\n')

# Fill in this space to get user input

# Fill in this space to use in operator to search for the
# account specified by user

# Call the main function.
main()
Here is a sample run of the program:
Enter the account number to be validated: 56
Account number 56 is not valid.
Enter the account number to be validated: 5658845
Account number 5658845 is valid.

Submission

1. Include the standard program header at the top of your Python file.
2. Submit your files to Etudes under the "Lab 04" category.

TotalSales.py

AccountValidation.py
Standard program header

Each programming assignment should have the following header, with italicized text appropriately replaced.

Note: You can copy and paste the comment lines shown here to the top of your assignment each time. You will need to make the appropriate changes for each lab (lab number, lab name, due date, and description).

Lab II: Strings - sets and dictionaries

This lab will give you some experience with strings and sets.

Lab 1: Character Analysis

1. Open the Python program CharacterAnalysis.py.
2. Fill in the code so that the program will do the following:

- Read the file's contents (text.txt) and determines the following:

o The number of uppercase letters in the file
o The number of lowercase letters in the file
o The number of digits in the file
o The number of whitespace characters in the file

3. Save the code to a file by going to File Save.

Python File:
def main():
# Local variables
num_upper = 0
num_lower = 0
num_space = 0
num_digits = 0
data = ''

# Open file text.txt for reading.
infile = open('text.txt', 'r')

# Read in data from the file.
data = infile.read()

# Fill in this space to step through each character in
# the file.
# Determine if the character is uppercase,
# lowercase, a digit, or space, and keep a
# running total of each.

# Close the file.
infile.close()

# Display the totals.

# Call the main function.
Main()
Here is a sample run:
Uppercase letters: 29
Lowercase letters: 1228
Digits: 30
Spaces: 260

Lab 2: Unique Words

1. Open the Python program UniqueWords.py.
2. Fill in the code so that the program will do the following:

- Open a specified text file
- Then displays a list of all the unique words found in the file.

Hint: Store each word as an element of a set.

3. Save the code to a file by going to File Save.

Python File:
def main():
# Get name of input file.
input_name = input('Enter the name of the input file: ')

# Open the input file and read the text.
input_file = open(input_name, 'r')
text = input_file.read()
words = text.split()

# Fill in this space to create set of unique words.

# Fill in this space to print the results.

# Close the file.
input_file.close()

# Call the main function.
main()

Submission

1. Include the standard program header at the top of your Python file.
2. Submit your files to Etudes under the "Lab 5 " category.

CharacterAnalysis.py
UniqueWords.py
Standard program header

Each programming assignment should have the following header, with italicized text appropriately replaced.

Note: You can copy and paste the comment lines shown here to the top of your assignment each time. You will need to make the appropriate changes for each assignment (assignment number, due date, and description).

Reference no: EM131309008

Questions Cloud

Draw conclusions about geographic concentration of prospects : Draw conclusions about the geographic concentration of prospects. Write a brief report-within the body of an email-to the CEO; include your table and your conclusion.
Executive information systems : Read the journal article, "Executive Information Systems: Their impact on Executive Decision Making". Based on the information presented in the article, discuss the following:
What is before-tax cost of capital for this debt financing : Black Hill Inc. sells $100 million worth of 19-year to maturity 9.56% annual coupon bonds. The net proceeds (proceeds after flotation costs) are $995 for each $1,000 bond. What is the before-tax cost of capital for this debt financing?
Challenges in designing a pay for performance : Define the challenges in designing a Pay for Performance (P4P) program. Discuss the impacts of P4P on provider payment reform. Describe the health care providers' reactions to Value-Based Purchasing Programs. Determine the benefits of P4P on patients..
How to step through and process the elements of a list : Programming in Python CS21A- Learn how to find high and low values of a list. Learn how to step through and process the elements of a list. Learn how to pass lists as arguments to a function. Learn how to wr..
Discuss the decision process of what makes retail customer : The article discusses the decision process of what makes retail customers prefer one product over another. It also argues that because of the increase in technology such as social media, consumers now have immense access to information more than t..
What does your client need to know about the company : What does your client need to know about the company?- Does the company align with the foundation's mission?
Why is m2 sometimes a more stable measure of money than m1 : Why is M2 sometimes a more stable measure of money than M1? Explain in your own words using the definitions of M1 and M2.
Explain the purpose of background investigations : 1. Explain the purpose of background investigations? 2. Explain why employee training is important? Also, discuss why career development is valuable to organization?

Reviews

Write a Review

Python Programming Questions & Answers

  Development on windows and linux systems

develop a simple, data-intensive application in Python - Data Analysis of a Document Tracker

  Develop and test a python program

Develop and test a Python program that displays the day of the week that the following holidays fall on for a year entered by the user New Year's Eve

  Generate a plot with a point for every charging station

After you have imported your data, you should use matplotlib to generate a plot with a point for every charging station. Note that the first column of data is longitude, i.e., the y-values, and the second column is latitude, i.e., the x-values

  Asign true to the variable has_dups

Asign True to the variable has_dups if the string s1 has any duplicate character (that is if any character appears more than once) and False otherwise

  Programming exercise - routing of telephone

programming exercise - routing of telephone callsdescriptionsome telephone operators have submitted their price lists

  Design and implement an english test

CSP1150 - Programming Principles - You are required to design and implement an "English Test" program in which the user is presented with a word and then asked to answer a simple question about the word. After 5 words, the program shows the user's..

  Write a function rmduplic(l), where l is any list

Write a function rmDuplic(L), where L is any list. The function should return a list M that contains the same items as L, except that repetitions (duplicates) have been removed: only the first occurrence of each entry is kept (i.e., order is prese..

  Evaluate a user''s expression

Write a function that will evaluate a user's expression. It should call the getExpression function that you previously wrote to get the expression to evaluate from the user. You should evaluate the expression step-by-step.

  Write program that read a text file and prints only odd line

Write a program that reads a text file and prints out only odd lines to the screen. Thus, lines 1, 3, 5,... only printed. Update your odd lines program (Q1) to write odd lines to the screen and write then lines to another file.

  Fill in the python code

Fill in the Python code to play Tic Tac Toe. I won't award points unless it runs succesfully. # Tic-Tac-Toe Game def drawBoard(board): # Draws the board using the list of numbers print(" ") print(" ",board[0]," | ",board[1]," | ", board[2]) print("--..

  Write a program that generates two integers

Write a program that generates two integers under 100, show them on screen, and prompts the user to enter the sum of these two integers. The program then reports true if the answer is correct, false otherwise.

  Q1if we knew all the ecological social and competitive

q1if we knew all the ecological social and competitive forces that regulate populations and in reality we couldnt what

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd