cse160_checkin4
.py
keyboard_arrow_up
School
University of Washington *
*We aren’t endorsed by this school
Course
160
Subject
Computer Science
Date
Dec 6, 2023
Type
py
Pages
2
Uploaded by UltraTeamNewt33
# Name:
# CSE 160
# Autumn 2023
# Checkin 4
# Problem 1
def first_letter(filename):
'''
Given a file name, return a string containing the first letter of
each line in the file
Arguments:
filename: a string representing a filename
Returns: a string made up of the first letter of each line of the
file in order
'''
result = ""
with open(filename, 'r') as file:
for line in file:
if line.strip():
result += line[0]
return result
assert first_letter("numbers.txt") == "ottffs"
assert first_letter("animals.txt") == "cspgcdchrm"
# Problem 2
def num_lower_val(max_val, input_dict):
'''
Return the number of values in the dictionary that are lower than the
given int
All values in the dictionary will be integers
Arguments:
max_val: an integer
input_dict: a dictionary with int values
Returns: An integer representing the number of key-value pairs in the
dictionary where the value is smaller than max_val
'''
count = 0
for value in input_dict.values():
if value < max_val:
count += 1
return count
assert num_lower_val(5, {"one": 1, "two": 2, "three": 3}) == 3
assert num_lower_val(-5, {"one": 1, "two": 2, "three": 3}) == 0
assert num_lower_val(5, {"five": 5, "two": 2, "three": 3}) == 2
assert num_lower_val(21, {"panda": 20}) == 1
assert num_lower_val(18, {"panda": 20}) == 0
assert num_lower_val(2, {10: 1, 11: 1, 5: 1, 99: 1}) == 4
assert num_lower_val(6, {10: 7, 6: 25, 3: 1, 2: 2, 3: 1}) == 2
assert num_lower_val(1000, {1: 1001, 2: 999, 3: 1002}) == 1
# Problem 3
def duck_dict(duck_names, duck_ages):
'''
Given a list of strings representing the names of ducks
and a list of integers representing their age,
construct a dictionary containing a mapping of the ducks names
to its age
Arguments:
duck_names: A list of strings
duck_age: A list of ints where the int at index i
represents the age of the duck from
duck_names at index i
Returns: An dictionary that maps the name of the ducks to their ages
'''
duck_info = {}
for i in range(len(duck_names)):
duck_info[duck_names[i]] = duck_ages[i]
return duck_info
assert duck_dict(["Bri"], [5]) == {"Bri": 5}
assert duck_dict(["Bri", "Kim"], [5, 6]) == {"Bri": 5, "Kim": 6}
assert duck_dict(["A", "B", "C"], [5, 8, 1]) == {"A": 5, "B": 8, "C": 1}
assert duck_dict(["A", "B", "C"], [1, 1, 1]) == {"A": 1, "B": 1, "C": 1}
assert duck_dict(["A1", "A2", "A3"], [100, 15, 55]) == \
{"A1": 100, "A2": 15, "A3": 55}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
Challenge Activity 1: Word List File Writer and Reader
(a)Write a console and GUI program using *PYTHON* that asks the user how many words they would like to write to a file, and then asks the user to enter that many words, one at a time. The words should be written to a file.
(b) Write another program that reads the words from the file and displays the following data:
The number of words in the file.
The longest word in the file.
The average length of all of the words in the file.
arrow_forward
Data File:
Example #1AAAAABBBBBCCCCCDDDDDAAEBCBAFBBCDCECDADDEFEEFFFExample #2AAATAABTBBBBCCCCTCDDTDDDAASAABBSBBCCSCCDSDDDEEEAEEFBFFFDDF
Write a program that will give the user a brief introduction, then allow the user to type in the name of the file to be analyzed, the name of the data file to generate, and then process the data to match the output that is shown below.
This DNA test measures the various parts of the sequence and assigns them a letter. While the letters could be anything from A to Z, the only letters that matter for this test are the letters {A,B,C,D} all other letters can be ignored completely. A sample will be tested, given a length of time and then tested again. Each time the scientist will generate a line of data. Here is one Example: Example #1 AAAAABBBBBCCCCCDDDDD AAEBCBAFBBCDCECDADDEFEEFFF At first glance the sample looks significantly different after the second test. But if you look at the data, you will note that since we only care about A,B,C,D’s that the…
arrow_forward
C programming language
Criteria graded:
Declare file pointers Open file Read from file Write to file Close file
Instructions:
Write a segment of code that opens a file called “numbers.txt” for reading. This file is known to have 10 numbers in it. Read in each number and print a ‘*’ to the screen if the number is even. If the number is odd, do nothing. Conclude by closing this file.
arrow_forward
istream member function__________ repositions the fileposition pointer in a file.
arrow_forward
TRUE
FALSE
The dereference
operator * is
used to obtain
the address of a
variable.
The void
functions return
noting when
called.
the flag eof() is
FALSE at the
beginning of a
text file.
There is no way
to show text on
graphic
screen
The reserved
word struct is
used when
declaring a void
function.
arrow_forward
#function read file and display reportdef displayAverage(fileName):#open the fileinfile = open(fileName, "r")#variable declaration and initializationtotal = 0count = 0#read filefor num in infile:total = total + float(num)count = count + 1#close the fileinfile.close()#calculate averageaverage = total / count#display the resultprint("Average {:.1f}".format(average))
#method callingdisplayAverage("numbers.txt")
arrow_forward
Programming language is C#
arrow_forward
Programming language : C++
Note : you have to use file handling
Question :
you are asked to make a program in c ++ in which you have to Write a function to search for student details ( name and class ) from a file using the enrollment of student.
arrow_forward
Q3:IN SML language how would I write a string to integer function that inputs a filename and returns zero if the contents inside the file is blank.
arrow_forward
In C# create an application that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user specify how many random numbers the file will hold.
arrow_forward
Write code that opens an output file with the filename number_list.txt, but does not erase the file’s contents if it already exists.
arrow_forward
Print Person Information from file
In this lab you are asked to complete the function : print_person_from_file(person_name, filename). This function should
read in data from the file filename and print the information for person_name if it is found in the file.
The file filename contains lines, in comma separated format (with a 'csv' extension) For each line, the items in each field are as follows:
Field
1
3
4
Name
Place of Birth Date of Birth Children
For Children:
• a person can have 0, 1 or multiple Children
Multiple children are semi-colon separated
If a person has no children the field contains 'NA'
For example, consider the following lines froma .csv file, where Fletcher_Margaret has 3 children, and Baker_Jill has 0 children
(field 4 contains the string 'NA')
Fletcher Margaret,Sydney,30-09-1921,Green Bob;Green Nancy;William Tom
Baker_Jill, Melbourne,08-09-1973, NA
Format for Printing
If the person_name is found in the file, the format for printing the person information is as…
arrow_forward
CENT 110 Homework 6
This assignment involves writing a program that takes reads from a text file containing
multiple lines of floating numbers separated by commas. The program will ask for the
user to enter file name of the text file. The program will read each line of numbers, use
the split() function to put the numbers in lists. For each line of numbers, the program
will calculate the total of the numbers, the average value, the smallest number, and the
largest number. For each line of numbers, it will then display each number, the total,
average, smallest number, and the largest number.
The numbers are in a text file named numbers.txt and contains the following:
1.0, 2.0, 3.0
4.0, 3.0, 2.0, 1.0
5.0, 5.0, 5.0, 5.0, 5.0
arrow_forward
C programming
c language
arrow_forward
Topics: Functions, Files Read and write, DictionarySuppose you are given an input file of a document that only contains English words, spaces, commas(always followed with one space) and periods (always followed with one space). Your task is to readthe file, count the word frequency by ignoring the letter case, output the frequently used words (i.e.,the words occurred more than once) and the most frequently used word among all of them.Lab Scenario: Count the word in a document1. The program reads from an already provided input file: “document.txt”, which containsseveral paragraphs separated by an empty line.2. You will perform the file open operation. And then perform the read operation with your choice ofread functions and read the content of the file.3. Once you are done reading, start processing the contents of the file using a dictionary where thekey would be the word in lowercase and the corresponding values would be word frequency whichwill be the number of occurrences in the…
arrow_forward
Python - Next Birthdate
In this task, we will write a program that reads birthdate data from a given CSV file, and given the current date, determines which person's birthday will be celebrated next.
Create a function with the following signature:
nextBirthdate(filename, date)
filename: parameter, which represents the CSV filename.
date: parameter, which represents the current date.
The function should open the CSV file, read the birthdate data, and determine which person's birthday will be celebrated next, given the current date. The name of the person should be returned. In other words, given a date, find the person whose birthday is next.
Sample Run
birthdates.csv
Draven Brock, 01/21/1952
Easton Mclean, 09/02/1954
Destiny Pacheco, 10/10/1958
Ariella Wood, 12/20/1961
Keely Sanders, 08/03/1985
Bryan Sloan,04/06/1986
Shannon Brewer, 05/11/1986
Julianne Farrell,01/29/2000
Makhi Weeks, 03/20/2000
Lucian Fields, 08/02/2018
Function Call
nextBirthdate("birthdates.csv", "01/01/2022")
Output…
arrow_forward
Function ________repositions the file position pointer to a specific location in the file
arrow_forward
Password validation
Write a program password.py that reads a file containing multiple passwords and checks the validity of the passwords. The file format is identical to one of the sample passwords.txt provided below. Your program must contain the following functions:
Function name
Function description
Function input(s)
Function return value(s)
validate()
This function takes a password string as input and returns a boolean that determines if the password is valid or invalid.
The requirements for a valid password are:
The password must be at least 9 characters long and at most 18 characters long (included).
The password must end with a letter.
The ending letter must be uppercase.
The password must contain `62`
The password must not start with `@`
The password must contain at least 4 digits
Password string
Boolean
main()
This function prompts for a file of passwords.
Next, it opens the file.
Next, it checks for the validity of every password in…
arrow_forward
Note: The code should be written in Python
arrow_forward
File redirection allows you to redirect standard input (keyboard) and instead read from a file specified at the command prompt. It requires the use of the < operator (e.g. java MyProgram < input_file.txt)
True or False
arrow_forward
Write the code in python
Create an application that can create, display, search and maintain the book information for a bookstore.
Requirements:
1) you need to use functions to write code for each menu item.
2) Information of books will be saved in a file, e.g,, books.txt.
3)User can add any number of books to the booklist. There can be 5 books or 500 books. In order for your program to handle it without any changes in the code, you cannot hardcode the number of books in your program.
arrow_forward
Line Numbers
Write a program that asks the user for the name of a file. The program should display the
contents of the file with each line preceded with a line number followed by a colon. The
line numbering should start at 1.
Python
arrow_forward
C++arrays, c-strings, functions with arrays as parameters
1. Create a file that contains 20 integers or download the attached file twenty_integers.txt
Create a program that:
2. Declares a c-style string array that will store a filename.
3. Prompts the user to enter a filename. Store the file name declared in the c-string.
4. Opens the file. Write code to check the file state. If the file fails to open, display a message and exit the program.
5. Declare an array that holds 20 integers. Read the 20 integers from the fileinto the array.6. Write a function that accepts the filled array as a parameter and determines the MAXIMUM value in the array.Return the maximum value from the function (the function will be of type int).7. Print ALL the array values AND print the maximum value in the array using a range-based for loop. Use informational messages.Ensure the output is readable.
arrow_forward
Problem description
Write a program that will read in a file of student academic credit data and create a list
of students on academic warning. The list of students on warning will be written to a file.
Each line of the input file will contain the student name (a single String with no spaces), the
number of semester hours earned (an integer), the total quality points earned (a double).
The program should compute the GPA (grade point or quality point average) for each student
(the total quality points divided by the number of semester hours) then write the student
information to the output file if that student should be put on academic warning. A student
will be on warning if he/she has a GPA less than 1.5 for students with fewer than 30 semester
hours credit, 1.75 for students with fewer than 60 semester hours credit, and 2.0 for all other
students. Do the following:
1. Create a text data file "students.dat". The following shows part of a typical data file:
Smith 27 83.7
Jones 21 28.35…
arrow_forward
Problem description
Write a program that will read in a file of student academic credit data and create a list
of students on academic warning. The list of students on warning will be written to a file.
Each line of the input file will contain the student name (a single String with no spaces), the
number of semester hours earned (an integer), the total quality points earned (a double).
The program should compute the GPA (grade point or quality point average) for each student
(the total quality points divided by the number of semester hours) then write the student
information to the output file if that student should be put on academic warning. A student
will be on warning if he/she has a GPA less than 1.5 for students with fewer than 30 semester
hours credit, 1.75 for students with fewer than 60 semester hours credit, and 2.0 for all other
students. Do the following:
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage
C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr
Related Questions
- Challenge Activity 1: Word List File Writer and Reader (a)Write a console and GUI program using *PYTHON* that asks the user how many words they would like to write to a file, and then asks the user to enter that many words, one at a time. The words should be written to a file. (b) Write another program that reads the words from the file and displays the following data: The number of words in the file. The longest word in the file. The average length of all of the words in the file.arrow_forwardData File: Example #1AAAAABBBBBCCCCCDDDDDAAEBCBAFBBCDCECDADDEFEEFFFExample #2AAATAABTBBBBCCCCTCDDTDDDAASAABBSBBCCSCCDSDDDEEEAEEFBFFFDDF Write a program that will give the user a brief introduction, then allow the user to type in the name of the file to be analyzed, the name of the data file to generate, and then process the data to match the output that is shown below. This DNA test measures the various parts of the sequence and assigns them a letter. While the letters could be anything from A to Z, the only letters that matter for this test are the letters {A,B,C,D} all other letters can be ignored completely. A sample will be tested, given a length of time and then tested again. Each time the scientist will generate a line of data. Here is one Example: Example #1 AAAAABBBBBCCCCCDDDDD AAEBCBAFBBCDCECDADDEFEEFFF At first glance the sample looks significantly different after the second test. But if you look at the data, you will note that since we only care about A,B,C,D’s that the…arrow_forwardC programming language Criteria graded: Declare file pointers Open file Read from file Write to file Close file Instructions: Write a segment of code that opens a file called “numbers.txt” for reading. This file is known to have 10 numbers in it. Read in each number and print a ‘*’ to the screen if the number is even. If the number is odd, do nothing. Conclude by closing this file.arrow_forward
- istream member function__________ repositions the fileposition pointer in a file.arrow_forwardTRUE FALSE The dereference operator * is used to obtain the address of a variable. The void functions return noting when called. the flag eof() is FALSE at the beginning of a text file. There is no way to show text on graphic screen The reserved word struct is used when declaring a void function.arrow_forward#function read file and display reportdef displayAverage(fileName):#open the fileinfile = open(fileName, "r")#variable declaration and initializationtotal = 0count = 0#read filefor num in infile:total = total + float(num)count = count + 1#close the fileinfile.close()#calculate averageaverage = total / count#display the resultprint("Average {:.1f}".format(average)) #method callingdisplayAverage("numbers.txt")arrow_forward
- Programming language is C#arrow_forwardProgramming language : C++ Note : you have to use file handling Question : you are asked to make a program in c ++ in which you have to Write a function to search for student details ( name and class ) from a file using the enrollment of student.arrow_forwardQ3:IN SML language how would I write a string to integer function that inputs a filename and returns zero if the contents inside the file is blank.arrow_forward
- In C# create an application that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user specify how many random numbers the file will hold.arrow_forwardWrite code that opens an output file with the filename number_list.txt, but does not erase the file’s contents if it already exists.arrow_forwardPrint Person Information from file In this lab you are asked to complete the function : print_person_from_file(person_name, filename). This function should read in data from the file filename and print the information for person_name if it is found in the file. The file filename contains lines, in comma separated format (with a 'csv' extension) For each line, the items in each field are as follows: Field 1 3 4 Name Place of Birth Date of Birth Children For Children: • a person can have 0, 1 or multiple Children Multiple children are semi-colon separated If a person has no children the field contains 'NA' For example, consider the following lines froma .csv file, where Fletcher_Margaret has 3 children, and Baker_Jill has 0 children (field 4 contains the string 'NA') Fletcher Margaret,Sydney,30-09-1921,Green Bob;Green Nancy;William Tom Baker_Jill, Melbourne,08-09-1973, NA Format for Printing If the person_name is found in the file, the format for printing the person information is as…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageC++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology Ptr
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage
C++ for Engineers and Scientists
Computer Science
ISBN:9781133187844
Author:Bronson, Gary J.
Publisher:Course Technology Ptr