Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
from collections import Counter
from matplotlib import pyplot as plt
import math

# -*- coding: utf-8 -*-
print("""Problem 1: Replace the word EXAMPLE three times in the next line 
with three examples of problems that can be solved by data science.""")
print("Answer 1: EXAMPLE, EXAMPLE, EXAMPLE  ")
print()

#The test continues after the Gettysburg Address.
gettysburg= """Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.

Abraham Lincoln
November 19, 1863
"""

#The next statement removes punctuation
text=gettysburg.replace(',','').replace('.','').replace(':','').replace("-","")

print("""Problem 2: Complete the next line so that uppercase letters in text 
will be replaced by lower case letters in lowtext.""")
lowtext=text

print("Answer 2:",lowtext[:30], " etc.")
print() 

#the next line splits the text into a list of words.
words=lowtext.split()

print("words=", words[:6], "etc.")
print()

print("""Problem 3: Replace the {} in the next line so that word_counts 
will be a counter with the number of times each word appears.""")
word_counts = {}

print("Answer 3:", list(zip(list(word_counts.keys())[:3], list(word_counts.values())[:3])), "etc.")
print()

print("""Problem 4: Make two replacements  in the list important_words in the
next line.  Use a word that you think is imporant in the Gettysburg. Address""")
important_words=['nation', 'REPLACE','REPLACE']

print("Answer 4:", important_words)
print()

print("""Problem 5: Replace 0 in the third line below with an expression to 
print the number of times each 'important' word appears in the Address.""")
print("Answer 5:")
for word in important_words:
    print(word, 0)
print()

print("""Problem 6:  Replace the [] in the next line so that top10 will be a 
list of the 10 most frequent words in the Address and their frequencies.""") 
top10=[]

print("Answer 6:", top10)
print()

#The next line creates a list of the top 10 words.  
top_words=[word for word,_ in top10]
print("top words=", top_words)
print()

print("""Problem 7: Insert code inside the [] in the next line so that 
top_freqs will be a list of the frequencies (or counts) for the top 10 words.""") 
top_freqs=[]

print("Answer 7:", top_freqs)
print()

#the next line creates a list of indices for the top 10 words (0 to 9)
indices=[i for i,_ in enumerate(top_words)]
print("indices=",indices)
print()

#Bar Graph

print("""Problem 8: Repace the [] in the next line so the bar heights will be 
the frequencies.""")  
graph1=plt.bar(indices, [],.9)
plt.xticks(indices, top_words)
plt.ylabel("Frequency")
plt.title("Top ten words in the Gettysburg Address")
print("Answer 8:")
plt.show(graph1)

print()

#Historgram

print("""Problem 9: Replace the 0 and [] in the next line with appropriate code
so that world_lengths will be a list of the lengths of the words in the Address.""")
word_lengths=[0 for word in []]

print("Answer 9:", word_lengths[:10], "etc.")
print()

#the next two functions can be used to create a historgram
def bucketize(point, bucket_size):
    """floor the point to the next lower multiple of bucket_size"""
    return bucket_size * math.floor(point / bucket_size)
def make_histogram(points, bucket_size):
    """buckets the points and counts how many in each bucket"""
    return Counter(bucketize(point, bucket_size) for point in points)
 
length_count= make_histogram(word_lengths, 3)
print("""Problem 10: Replace the [] in the next line with appropriate code to 
create a histogram of the word lengths.""") 
graph2=plt.bar(length_count.keys(), [], 2.9, align='edge')

print("Answer 10:")
plt.xticks(list(length_count.keys()))
plt.xlabel('Word length (with bucketsize 3)')
plt.ylabel('Frequency')
plt.title("Histogram of word lengths")
#plt.show(graph2)


What I have tried:

from collections import Counter
from matplotlib import pyplot as plt
import math

# -*- coding: utf-8 -*-
print("""Problem 1: Replace the word EXAMPLE three times in the next line 
with three examples of problems that can be solved by data science.""")
print("Answer 1: Civil, War, Nation  ")
print()

#The test continues after the Gettysburg Address.
gettysburg= """Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.

Abraham Lincoln
November 19, 1863
"""

#The next statement removes punctuation
text=gettysburg.replace(',','').replace('.','').replace(':','').replace("-","")

print("""Problem 2: Complete the next line so that uppercase letters in text 
will be replaced by lower case letters in lowtext.""")
lowtext=text

print("Answer 2: lowtext=tolower(text)",lowtext[:30], " etc.")
print() 

#the next line splits the text into a list of words.
words=lowtext.split()

print("words=", words[:6], "etc.")
print()

print("""Problem 3: Replace the {} in the next line so that word_counts 
will be a counter with the number of times each word appears.""")
word_counts = Counter(text)
for word, count in word_counts.most_common(6):
 print(word, count)
print()
 
print(word_counts)
print()

for letter in word_counts:
    print(word, '\t', word_counts[word])

print("Answer 3:", list(zip(list(word_counts.keys())[:3], list(word_counts.values())[:3])), "etc.")
print()

print("""Problem 4: Make two replacements  in the list important_words in the
next line.  Use a word that you think is imporant in the Gettysburg. Address""")
important_words=['nation', 'Civil','War']

print("Answer 4:", important_words)
print()

print("""Problem 5: Replace 0 in the third line below with an expression to 
print the number of times each 'important' word appears in the Address.""")
print("Answer 5:")
for word in important_words:
    print(word, 3)
print()

print("""Problem 6:  Replace the [] in the next line so that top10 will be a 
list of the 10 most frequent words in the Address and their frequencies.""") 
top10=[]

print("Answer 6:", top10)
print()

#The next line creates a list of the top 10 words.  
top_words=[word for word,_ in top10]
print("top words=", top_words)
print()

print("""Problem 7: Insert code inside the [] in the next line so that 
top_freqs will be a list of the frequencies (or counts) for the top 10 words.""") 
top_freqs=[]

print("Answer 7:", top_freqs)
print()

#the next line creates a list of indices for the top 10 words (0 to 9)
indices=[i for i,_ in enumerate(top_words)]
print("indices=",indices)
print()

#Bar Graph

print("""Problem 8: Repace the [] in the next line so the bar heights will be 
the frequencies.""")  
graph1=plt.bar(indices, [],.9)
plt.xticks(indices, top_words)
plt.ylabel("Frequency")
plt.title("Top ten words in the Gettysburg Address")
print("Answer 8:")
plt.show(graph1)

print()

#Historgram

print("""Problem 9: Replace the 0 and [] in the next line with appropriate code
so that world_lengths will be a list of the lengths of the words in the Address.""")
word_lengths=[0 for word in []]

print("Answer 9:", word_lengths[:10], "etc.")
print()

#the next two functions can be used to create a historgram
def bucketize(point, bucket_size):
    """floor the point to the next lower multiple of bucket_size"""
    return bucket_size * math.floor(point / bucket_size)
def make_histogram(points, bucket_size):
    """buckets the points and counts how many in each bucket"""
    return Counter(bucketize(point, bucket_size) for point in points)
 
length_count= make_histogram(word_lengths, 3)
print("""Problem 10: Replace the [] in the next line with appropriate code to 
create a histogram of the word lengths.""") 
graph2=plt.bar(length_count.keys(), [], 2.9, align='edge')

print("Answer 10:")
plt.xticks(list(length_count.keys()))
plt.xlabel('Word length (with bucketsize 3)')
plt.ylabel('Frequency')
plt.title("Histogram of word lengths")
#plt.show(graph2)
Posted
Updated 8-Mar-22 20:07pm
Comments
Richard MacCutchan 9-Mar-22 4:11am    
The answer to problem 1 is wrong.

1 solution

This is the same thing you asked yesterday: How do I solve these questions[^]
And I see no difference in "What I have tried" - so the answer is still the same.

Where is problem 1 solution?
What testing did you do to check your results so far?

Testing and debugging your code is part of the test: they are parts of the process of development that somebody is trying to get you to show you have learned. And so far, your test regime appears to be "ask someone else if it works" so I assume your debugging abilities are "ask someone else to fix it".

That's not enough. Run your code. See what it does, and compare that to what the problem requires of you. If it matches, it passes. If it doesn't ... then you need to fix it!

But we aren't here to "pre-mark" your test - that's all part of your task!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900