1.1. Traverse a String Using a while Loop
The following code traverses a string using a for loop:
Create a function that traverses a string using a while Loop. Do NOT use a for loop!
Function name: traverse_string_with_while()
Parameters/arguments: a string
1.2. Read a Text File: Count Words
Create a function that reads a text file consisting of natural language and counts the number of words. The file to read is titled count_words.txt.
Function name: count_words() Parameters/arguments: a filename Returns: the number of words in the file
TIPS
Algorithm:
open file
read text contents from file
close file
break large text (book, chapter, article?) into paragraphs:
text.split('\n')
or break large text into sentences:
text.split('.')
text.split('?')
text.split('!')
or break large text into words
remove tokens that aren’t words
count remaining tokens (also known as words)
1.3. Read a Text File: Count Sentences
Create a function that reads a text file consisting of natural language and counts the number of sentences. The file to read is titled count_sentences.txt.
Function name: count_sentences() Parameters/arguments: a filename Returns: the number of sentences in the file
1.4. Write To a Text File
Create a function that writes to a text file whatever data the user enters via keyboard. The user will first be asked to give the filename. Keep asking the user to enter data until they type Return without entering text. If the text file already exists then the data en- tered by the user is appended to the existing text file.
The file you will write to will be named write_to_text_file.txt.
Function name: create_text_file()
Parameters/arguments: a filename
Returns: 1 if a new text file was created, 0 if an existing text file was appended to
TIPS
Algorithm:
ask user to input filename (txt)
to check if a file already exists use the os module (there are other ways too do this):
import os
file_exists = os.path.exists("test.txt") print("Does file exist?: " + str(file_exists))
open file
ask user to input text data
write user’s text data to file
repeat the previous two steps until user is done entering data
close file
return 1 if a new text file was created, or return 0 if an existing text file was appended to
1.5. Move A Character In A Video Game
Create a function that moves a character in a video game. You are given the character’s name, its initial x and y positions, and the amount the character will move in the x di- rection and the y direction. Compute the character’s new location in the game.
Function name: move_game_character()
Parameters/arguments: character name, initial x position, initial y position, move- ment in the x direction, movement in the y direction (5 arguments)
Returns: character’s new x & y coordinates after moving
1.6. Recommend a Movie
Create a function that counts how many keywords are similar in a set of movie reviews and recommend the movie with the most similar number of keywords.
The solution to this task will require the use of dictionaries.
The film reviews & keywords are in a file called film_reviews.txt, separated by commas. The first term is the movie name, the remaining terms are the film’s keyword tags (i.e., “amazing", “poetic", “scary", etc.).
Function name: similar_movie()
Parameters/arguments: name of a movie
Returns: a list of movies similar to the movie passed as an argument
TIPS
Algorithm:
open txt file
read contents of file
close file
parse file into a dictionary of the form
{"movie":["keyword1", "keyword2", "keyword3"...]}}
get movie’s keywords
go through the rest of the movies to see which have the most key- words in common
return a list of the movies similar to the movie passed as an argu- ment
1.7. Check Type
Create a function that checks if a variable is of type String.
Function name: check_type_is_string() Parameters/arguments: one variable of any type Returns: True if the variable is a String, False otherwise
1.8. Check If Player Can Buy Items In A Video Game
Create a function that determines whether a video game character has enough money to buy items from a shop. You are given the amount of coins the character has and a dictionary of items the shop has for sale (along with each item’s price).
Determine the items in the shop available for the character to purchase. If no items are available then the function returns None.
Function name: shop_items_player_can_buy()
Parameters/arguments: amount of coins the character has, dictionary of shop items (item names are the dictionary keys, item prices are the dictionary values)
Returns: a list of items in the shop the player can purchase, None if no items can be afforded
TIPS
Algorithm:
check how much money player has
find all shop items that cost less than or equal to the amount of money the player has
display the list of items the player can purchase
1.9. Opinion of A Sentence
Create a function that determines whether a sentence has a positive or negative opin- ion of a topic.
The sentences are read from a file called opinions.txt.
Function name: sentence_opinion()
Parameters/arguments: a sentence
Returns: +1 if the sentence expresses positive sentiment or opinion, -1 if the sentence expresses a negative sentiment or opinion, 0 if the sentence is neutral (neither positive or negative)
This one requires some thought before we begin even the algorithm:
how do we determine whether a sentence is positive or negative about some topic?
can we use the words of a sentence to determine if something is positive or negative?
does a list of positive & negative words exist?
if not, can I quickly make up a list of positive & negative words? List of positive & negative words (example):
positive_words = ["good", "happy", "cool", "fun", "amazing",...]
negative_words = ["bad", "unhappy", "boring", "simple", "yawn",...]
Algorithm:
find negative words in sentence
find positive words in sentence
TODO: complete the ..
1.10. Astronomy
The stars.txt dataset1 consists of temperatures and magnitudes for 7860 nearby stars. The magnitude of stars corresponds to a star’s brightness. A star’s temperature is esti- mated by the color of light the star emits.
Write functions that read the stars.txt file and:
find the hottest star
find the coldest star
find the brightest star
find the darkest star
Function name: find_hottest_star() Parameters/arguments: filename Returns: temperature
Function name: find_coldest_star() Parameters/arguments: filename Returns: temperature
Function name: find_brightest_star() Parameters/arguments: filename Returns: magnitude
Function name: find_darkest_star() Parameters/arguments: filename Returns: magnitude
TIPS
Algorithm:
open txt file
read contents of file
close file
parse file contents into two lists: a list of temperatures and a list of brightness magnitudes
find the hottest star from the list of temperatures
find the coldest star from the list of temperatures
find the brightest star from the list of temperatures
find the darkest star from the list of temperatures
1.11. Transform A String
Create a function that takes a string and changes its letters according to a set of rules. For example
This transformation is known as encoding/coding (i.e., encrypting & decrypting).
Function name: transform_string
Parameters/arguments: a string
Returns: a string that has been transformed (encoded)
TIPS
Algorithm:
get original string
create empty new string
for each letter of the original string, transform the letter
store (append) each transformed letter to the new string
return the new string
1.12. Parsing Bioinformatics Data
Create a function that reads bioinformatics data from a file and parses the data, then prints the information in a human-readable format. The file you will read your biose- quence data is ls_orchid.fasta. The file contains 94 sequence records. The sequences in the file are formatted similar to the following:
>gi|129295|sp|P01013|OVAX_CHICK GENE X PROTEIN (OVALBUMIN-RELATED) QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE KMKILELPFASGDLSMLVLLPDEVSDLERIEKTINFEKLTEWTNPNTMEKRRVKVYLPQMKIEEKYNLTS FLFLIKHNPTNTIVYFGRYWSP
You will format and display the above sequence record to the console screen as follows:
DESCRIPTION:
gi 129295
sp P01013
OVAX_CHICK GENE X PROTEIN (OVALBUMIN-RELATED)
SEQUENCE:
QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE KMKILELPFASGDLSMLVLLPDEVSDLERIEKTINFEKLTEWTNPNTMEKRRVKVYLPQMKIEEKYNLTS FLFLIKHNPTNTIVYFGRYWSP
Some properties of text in FASTA format (see the Appendix FASTA Format for info):
a sequence in FASTA format begins with a single-line description (or defline)
there is no space between the ">" and the first letter of the sequence description
the bar ("|") separates different fields
after the definition line are lines of sequence data
the definition line (defline) is distinguished from the lines containing sequence data by a greater-than (>) symbol at the beginning of the line
all lines of text should be shorter than 80 characters in length
Function name: read_bio_data()
Parameters/arguments: a filename
Returns: a list of sequence records (the above example is one sequence record) For example, executing the following code produces:
|
)
Function name: print_bio_data()
Parameters/arguments: one of the records from ls_orchid.fasta
Returns: function displays one sequence record to the screen formatted to improve readability, does not return a value
TIPS
This is the more complex task since it requires strict adherence to the for- matting of the file. Parsing is the process of taking data and structuring it to improve readability/interpretation/analysis/etc. In this task, the tool you will primarily use is split().
String Method |
Description |
split(’|’) |
splits the text at every instance of | |
split(’>’) |
splits the text at every instance of > |
split(’\n\n’) |
splits the text at every instance of two carriage returns |
Algorithm:
open fasta file
read contents of file
close file
parse file into individual records
for each record, parse into sequence data & the sequence descrip- tion line
for the sequence description line, parse into strings separated by |
display the parsed sequence description line
display the raw sequence data
DescriptionIn this final assignment, the students will demonstrate their ability to apply two ma
Path finding involves finding a path from A to B. Typically we want the path to have certain properties,such as being the shortest or to avoid going t
Develop a program to emulate a purchase transaction at a retail store. Thisprogram will have two classes, a LineItem class and a Transaction class. Th
1 Project 1 Introduction - the SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of
1 Project 2 Introduction - the SeaPort Project series For this set of projects for the course, we wish to simulate some of the aspects of a number of