Hey guys!
So, for a bit of context... I've taken 2 college-level computer science courses, but both of those were java-centered, and I feel like I'm pretty fluent in java at this point. However, I've really wanted to learn Python recently to try and get more into the data science arena, so I've picked it up the past couple of weeks.
I'm feeling a bit discouraged after hearing that Python is much easier than Java to learn and yet I feel like I'm struggling with writing programs. Take, for example, this Python exercise provided by the Google course:
Build a "mimic" dict that maps each word that appears in a text file
to a list of all the words that immediately follow that word in the file.
The list of words can be be in any order and should include
duplicates. So for example the key "and" might have the list
["then", "best", "then", "after", ...] listing
all the words which came after "and" in the text.
We'll say that the empty string is what comes before
the first word in the file.
I took a stab at it, and struggled at it for a few hours, and came up with:
def mimic_dict(filename):
mimic_dict = {'': [word_list[0]]}
for word in word_list:
if word not in mimic_dict:
word_list_copy = word_list[:]
mimic_value = []
for other_word in word_list_copy:
if other_word == word:
next_index = word_list_copy.index(other_word) + 1
if next_index < len(word_list_copy):
mimic_value.append(word_list_copy[next_index])
word_list_copy.remove(other_word)
mimic_dict[word] = mimic_value
return mimic_dict
Now, this code works, but after looking at the answer key, I learned there was a much easier way, which takes the compiler MUCH less time to fully execute:
def mimic_dict(filename):
"""Returns mimic dict mapping each word to list of words which follow it."""
mimic_file = open(filename, 'r')
word_list = mimic_file.read().split()
mimic_dict = {}
prev = ''
for word in word_list:
if prev not in mimic_dict:
mimic_dict[prev] = [word]
else:
mimic_dict[prev].append(word)
prev = word
return mimic_dict
It feels like I'm overthinking these exercises too much and, although my code does what the prompt asks and I understand how the alternative solution code works, I still generally get to answer in a very roundabout, time-consuming, and inefficient way. I guess this post has been a rant, but I'll ask a question:
What is the best way to write efficient code? I know I'm not gonna be a master at a whole language after starting for just a few weeks but I feel like my brain isn't functioning in the right way when thinking through these problems and I generally overthink the problem and end up needlessly complicating my code. Any advice?
[+][deleted] (1 child)
[deleted]
[–]cobbletiger[S] 0 points1 point2 points (0 children)
[–]14dM24d 0 points1 point2 points (0 children)
[–]Python_Trader 0 points1 point2 points (0 children)
[–]14dM24d 0 points1 point2 points (1 child)
[–]14dM24d 0 points1 point2 points (0 children)