DDC-4: Bar plot of word lengths
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
Create a string variable for the sentence “This is a sentence that should say something witty but instead is just meta.”
Split the sentence into words, count the number of characters in each word, and show the results in a bar graph as below.
.
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
Keep scrolling!
.
.
.
.
import matplotlib.pyplot as plt
import matplotlib as mpl
# text and split
sentence = 'This is a sentence that should say something witty but instead is just meta.'
words = sentence.split()
n_words = len(words)
# count word lengths
wordlens = [ len(w) for w in words ]
# draw the plot and color the bars
plt.figure(figsize=(8,3))
bars = plt.bar(range(n_words),wordlens)
for i in range(n_words):
bars[i].set_color(mpl.cm.plasma((1+i)/n_words))
# beautify the axis
plt.gca().set(ylabel='character count',xticks=range(n_words),xticklabels=words)
plt.xticks(rotation=45)
plt.show()
Fellow math nerd problem for you…I am a five digit number. My square root is a three digit number. All our digits are prime. No computers..No calculators….Just use pure mathematical Logic and Reasoning to find us. Let me know your reasoning and how you arrived at the two numbers. This will be one of the problems in my upcoming book.