-
-
Save guestPK1986/dfadc3ffe900dae77e86bae4a5af80bd to your computer and use it in GitHub Desktop.
#Read in the contents of the file SP500.txt which has monthly data for 2016 and 2017 | |
#about the S&P 500 closing prices as well as some other financial indicators, | |
#including the “Long Term Interest Rate”, which is interest rate paid on 10-year U.S. government bonds. | |
#Write a program that computes the average closing price (the second column, labeled SP500) | |
#and the highest long-term interest rate. Both should be computed only for the period from June 2016 through May 2017. | |
#Save the results in the variables mean_SP and max_interest | |
with open("SP500.txt", "r") as file: | |
new = file.readlines() | |
closing_price = [] | |
interest_rate = [] | |
for x in new[6:18]: | |
y = x.split(",") | |
closing_price.append(y[1]) | |
interest_rate.append(y[5]) | |
sum_of_numbers = 0 | |
for each in closing_price: | |
sum_of_numbers = sum_of_numbers + float(each) | |
mean_SP = sum_of_numbers/len(closing_price) | |
print(float(mean_SP)) | |
max_interest = 0 | |
for i in interest_rate: | |
if float(i) > max_interest: | |
max_interest = float(i) | |
print(max_interest) | |
#Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro. | |
#Only the first letter of each word should be used, each letter in the acronym should be a capital letter, | |
#and there should be nothing to separate the letters of the acronym. | |
#Words that should not be included in the acronym are stored in the list stopwords | |
stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', "The"] | |
org = "The organization for health, safety, and education" | |
new=org.split() | |
acro='' | |
for word in new: | |
if word not in stopwords: | |
acro=acro + str.upper(word[0]) | |
print(acro) | |
#Write code that uses the string stored in sent and creates an acronym which is assigned to the variable acro. | |
#The first two letters of each word should be used, each letter in the acronym should be a capital letter, | |
#and each element of the acronym should be separated by a “. ” (dot and space). | |
#Words that should not be included in the acronym are stored in the list stopwords | |
stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The'] | |
sent = "The water earth and air are vital" | |
new = sent.split() | |
print(new) | |
acro = '' | |
for word in new: | |
if word not in stopwords: | |
acro = acro + str.upper(word[:2]) + "." + " " | |
acro = acro[0:-2] | |
print(acro) | |
#Provided is a list of data about a store’s inventory where each item in the list represents the name of an item, | |
#how much is in stock, and how much it costs. Print out each item in the list with the same formatting, | |
#using the .format method (not string concatenation). | |
#For example, the first print statment should read The store has 12 shoes, each for 29.99 USD. | |
inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", | |
"sweatpants, 25, 15.00", "scarves, 13, 7.75"] | |
for x in inventory: | |
y = x.split(",") | |
instock = y[1] | |
item_name = y[0] | |
price = y[2] | |
statement = 'The store has{} {}, each for{} USD.'.format(instock, item_name, price) | |
print(statement) | |
#A palindrome is a phrase that, if reversed, would read the exact same. | |
#Write code that checks if p_phrase is a palindrome by reversing it | |
#and then checking if the reversed version is equal to the original. | |
#Assign the reversed version of p_phrase to the variable r_phrase so that we can check your work. | |
p_phrase = "was it a car or a cat I saw" | |
r_phrase=''.join(reversed(p_phrase)) | |
print(r_phrase) | |
#OR | |
p_phrase = "was it a car or a cat I saw" | |
stringlength = len(p_phrase) | |
p_phrase[stringlength::-1] | |
r_phrase = p_phrase[stringlength::-1] | |
print(r_phrase) | |
#The string module provides sequences of various types of Python characters. | |
#It has an attribute called digits that produces the string ‘0123456789’. | |
#Import the module and assign this string to the variable nums. | |
#Below, we have provided a list of characters called chars. | |
#Using nums and chars, produce a list called is_num that consists of tuples. | |
#The first element of each tuple should be the character from chars, | |
#and the second element should be a Boolean that reflects whether or not it is a Python digit | |
import string | |
chars = ['h', '1', 'C', 'i', '9', 'True', '3.1', '8', 'F', '4', 'j'] | |
nums=string.digits | |
print(nums) | |
is_num =[] | |
for char in chars: | |
is_num.append((char,char in nums)) | |
print(is_num) | |
#Below are a set of scores that students have received in the past semester. | |
#Write code to determine how many are 90 or above and assign that result to the value a_scores | |
scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" | |
new_scores = [] | |
new = scores.split() | |
for x in new: | |
new_scores.append(int(x)) | |
b_scores = [] | |
for each in new_scores: | |
if each >= 90: | |
b_scores.append(each) | |
a_scores = len(b_scores) | |
print(a_scores) | |
#Ex 10.14 #Create a list called destination using the data stored in travel_plans.txt. | |
#Each element of the list should contain a line from the file that lists a country and cities inside that country. | |
#Hint: each line that has this information also has a colon : in it. | |
file = open("travel_plans.txt", "r") | |
line = file.readlines() | |
destination = [] | |
for words in line: | |
if ":" in words: | |
destination.append(words) | |
print (destination) | |
#Create a list called j_emotions that contains every word in emotion_words.txt that begins with the letter “j”. | |
file = open("emotion_words.txt", "r") | |
f = file.read() | |
j_emotions = [] | |
words = f.split() | |
for line in words: | |
if "j" in line: | |
j_emotions.append(line) | |
print(j_emotions) | |
#Ex 11.6 #Provided is a string saved to the variable name sentence. | |
#Split the string into a list of words, then create a dictionary that contains each word and | |
#the number of times it occurs. Save this dictionary to the variable name word_counts. | |
sentence = "The dog chased the rabbit into the forest but the rabbit was too quick." | |
txt = sentence.split() | |
word_counts = {} | |
for c in txt: | |
if c not in word_counts: | |
word_counts[c] = 0 | |
word_counts[c] = word_counts[c] + 1 | |
for c in word_counts.keys(): | |
print(c+ " -" + str(word_counts[c]) + " times") | |
#Create a dictionary called char_d from the string stri, so that the key is a character and | |
#the value is how many times it occurs. | |
stri = "what can i do" | |
char_d = {} | |
for x in stri: | |
if x not in char_d: | |
char_d[x] = 0 | |
char_d[x] = char_d[x] +1 | |
print(char_d[x]) | |
print(char_d.keys()) | |
print(char_d.values()) | |
#Create a dictionary called lett_d that keeps track of all of the characters in the string product | |
#and notes how many times each character was seen. Then, find the key with the highest value in this dictionary | |
#and assign that key to max_value. | |
product = "iphone and android phones" | |
lett_d = {} | |
for x in product: | |
if x not in lett_d: | |
lett_d[x]=0 | |
lett_d[x] = lett_d[x] + 1 | |
list1 = list(lett_d.keys()) | |
print(list1) | |
max_value = list1[0] | |
for key in list1: | |
if lett_d[key] > lett_d[max_value]: | |
max_value = key | |
print(max_value) | |
#Write a program that finds the most used 7 letter word in scarlet3.txt | |
f = open('scarlet3.txt', 'r') | |
contents = f.read() | |
d = {} | |
for w in contents.split(): | |
if len(w) == 7: | |
if w not in d: | |
d[w] = 1 | |
else: | |
d[w] = d[w] + 1 | |
dkeys = d.keys() | |
print(dkeys) | |
most_used = dkeys[0] | |
for k in dkeys: | |
if d[k] > d[most_used]: | |
most_used = k | |
print("The most used word is '" + most_used + "', which is used " + str(d[most_used])+ " times") | |
#Challenge For each word in words, add ‘d’ to the end of the word if the word ends in “e” to make it past tense. | |
#Otherwise, add ‘ed’ to make it past tense. | |
#Save these past tense words to a list called past_tense | |
words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"] | |
past_tense = [] | |
for word in words: | |
if word[len(word)-1] == 'e': | |
past_tense.append(word + 'd') | |
else: | |
past_tense.append(word + 'ed') | |
print(past_tense) | |
#For each word in the list verbs, add an -ing ending. Save this new list in a new list, ing | |
verbs = ["kayak", "cry", "walk", "eat", "drink", "fly"] | |
ing = [] | |
for w in verbs: | |
x = w + "ing" | |
ing.append(x) | |
print(ing) | |
#Challenge | |
#Overwrite the list numbs so that each of the original numbers are increased by 5 | |
numbs = [5, 10, 15, 20, 25] | |
for i in range(0,5): | |
numbs[i] = numbs[i]+ 5 | |
print(numbs) | |
#For each number in lst_nums, multiply that number by 2 and append it to a new list called larger_nums | |
lst_nums = [4, 29, 5.3, 10, 2, 1817, 1967, 9, 31.32] | |
larger_nums = [] | |
for i in lst_nums: | |
x = i*2 | |
larger_nums.append(x) | |
print(larger_nums) | |
#Display the image below to the right hand side where the 0 is going to be ' ', and the 1 is going to be '*'. This will reveal an image! | |
picture = [ | |
[0,0,0,1,0,0,0], | |
[0,0,1,1,1,0,0], | |
[0,1,1,1,1,1,0], | |
[1,1,1,1,1,1,1], | |
[0,0,0,1,0,0,0], | |
[0,0,0,1,0,0,0] | |
] | |
for row in picture: | |
for each in row: | |
if (each == 1): | |
print('*', end ="") | |
else: | |
print(' ', end ="") | |
print('') | |
# Check for duplicates in list | |
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] | |
duplicates = [] | |
for value in some_list: | |
if some_list.count(value) > 1: | |
if value not in duplicates: | |
duplicates.append(value) | |
print(duplicates) | |
# Write a function to return highest even number from a list | |
def highest_even(li): | |
max = 0 | |
for i in li: | |
if i % 2 == 0 and i > max: | |
max = i | |
i = i+1 | |
return max | |
print (highest_even([10,1,2,3,4,12])) |
"""
Read in the contents of the file SP500.txt which has monthly data for 2016 and
2017 about the S&P 500 closing prices as well as some other financial
indicators, including the “Long Term Interest Rate”, which is the interest rate
paid on 10-year U.S. government bonds.
Write a program that computes the average closing price (the second column,
labeled SP500) and the highest long-term interest rate. Both should be
computed only for the period from June 2016 through May 2017. Save the results
in the variables mean_SP and max_interest.
"""
I used accumulator pattern.
with open('SP500.txt', 'r') as fileref:
total_SP = 0
count_SP = 0
max_interest = None
for idx, line in enumerate(fileref):
# If it is a header, then go back to the for loop line to look for
# the row containing the actual data.
if idx == 0:
continue
# Work on each row containing the actual data.
# Each line of the fileref is a string. To get the list of strings or
# better to say the list of cells in each row, we have to use split
# method.
columns = line.strip().split(',')
# print('columns', columns, type(columns))
# We should only compute for the period from June 2016 through May
# 2017.
date = columns[0]
# print('date', date, type(date))
month_date = int(date.split('/')[0])
year_date = int(date.split('/')[2])
# First, we have to check for the given period.
if ((year_date == 2016 and month_date >= 6)
or (year_date == 2017 and month_date <= 5)):
# Now, that we are in the right row we can work on computing the
# average closing price (the second column,labeled SP500) and the
# highest long-term interest rate.
# we need to "extract" those values. Because each value is a
# string, we have to convert it to float.
current_SP = float(columns[1])
current_long_interest_rate = float(columns[5])
# Computing the two components of mean SP; total SP and the number
# of cells.
total_SP += current_SP
count_SP += 1
# Looking for the max value of Long Interest Rate. This is a
# typical way of looking for max value.
if (max_interest is None
or max_interest < current_long_interest_rate):
max_interest = current_long_interest_rate
mean_SP = total_SP / count_SP
print('mean_SP', mean_SP)
print('max_interest', max_interest)
Using csv module makes it easier to solve this problem, but it is not supported in runestone interactive textbook environment.
import csv
total_SP = 0
count_SP = 0
max_interest = None
with open('SP500.txt', 'r') as csv_fileref:
csv_reader = csv.DictReader(csv_fileref)
for row in csv_reader:
month, day, year = (row['Date'].split('/'))
month = int(month)
day = int(day)
year = int(year)
if (year == 2016 and month >= 6) or (year == 2017 and month <= 5):
total_SP += float(row['SP500'])
count_SP += 1
if (max_interest is None
or max_interest < float(row['Long Interest Rate'])):
max_interest = float(row['Long Interest Rate'])
mean_SP = total_SP / count_SP
print('mean_SP', mean_SP)
print('max_interest', max_interest)
"""
Create a list called j_emotions that contains every word in emotion_words.txt that begins with the letter “j”.
"""
with open('emotion_words.txt', 'r') as fileref:
j_emotions = []
for line in fileref:
words = line.strip().split()
for word in words:
if word[0] =='j':
j_emotions.append(word)
print(j_emotions)
Read in the contents of the file SP500.txt which has monthly data for 2016 and 2017 about the S&P 500 closing prices as well as some other financial indicators, including the “Long Term Interest Rate”, which is interest rate paid on 10-year U.S. government bonds.
Write a program that computes the average closing price (the second column, labeled SP500) and the highest long-term interest rate. Both should be computed only for the period from June 2016 through May 2017. Save the results in the variables mean_SP and max_interest.
This is the most concise solution that I was able to come up with:
stock_prices = []
interest_rates = []
with open("SP500.txt", "r") as file:
file = file.readlines()[6:18]
for line in file:
line = line.split(",")
stock_prices.append(float(line[1]))
interest_rates.append(float(line[5]))
mean_SP = sum(stock_prices) / len(stock_prices)
max_interest = max(interest_rates)
Hi. For SP500.txt i did my own version of code.
I'm starting to learning python so if anyone want to see it then great:)
with open('SP500.txt','r') as sp_file:
#podzielenie pliku do listy
sp_file=sp_file.readlines()
close_price=[]
interest_rate=[]
count=0
acc_int=0
#dla wierszy od 6 do 18 (June 2016 through May 2017)
for x in sp_file[6:18]:
y=x.split(',')
close_price.append(y[1])
interest_rate.append(y[5])
count+=1
for i in range(count):
close_price[i]=float(close_price[i])
acc_int=acc_int+close_price[i]
mean_SP=acc_int/count
print(mean_SP)
for a in range(count):
interest_rate[a]=float(interest_rate[a])
max_interest=interest_rate[0]
for z in range(count):
#print("max_interest={} ; interest_rate={}".format(max_interest,interest_rate[z]))
if interest_rate[z]>max_interest:
max_interest=interest_rate[z]
print(max_interest)
#Write a program that finds the most used 7 letter word in scarlet3.txt
And in your code, the following line causes an error because dkeys = d.keys() is not a list. It's a view object.
The keys() method returns a view object rather than a list of keys. This object is iterable so you can view its contents using a for statement. But, in this case, it is necessary to convert this object to a list.
Therefore, in the second line of the code, it should be most_used = list(dkeys)[0].
Instead of
it should be