Practice Makes Perfect 9/15 What solution is better?


#1

I solved this one, but when I look at the Codecademy solution its a bit different, so I wonder, whos code is “better”

My code:

def scrabble_score(word):
totalscore = 0
for letter in word:
for key in score:
if letter.lower() == key:
totalscore += score[key]

return totalscore
print scrabble_score(“Helix”)

Codecademy code:

def scrabble_score(word):
word = word.lower()
total = 0
for letter in word:
for leter in score:
if letter == leter:
total = total + score[leter]
return total

I feel like the word = word.lower() in the Codecademy code is unnecessary, why not just put .lower() next to letter in the if statement like I did?


#2

‘Better’; or, more suitable?


#3

Considering both of the codes are almost identical, the word suitable is probably the right word to use here :wink:


#4

And now I solved the next part (10/15) and here I feel that my code is more understandable than the Codecademy code…

My code:

def censor(text, word):
text = text.split()
newtext = []
for i in text:
if i != word:
newtext.append(i)
else:
if i == word:
newtext.append("*" * len(i))

return " ".join(newtext)
print censor(“this hack is wack hack”, “hack”)

Codecademy code:

def censor(text, word):
words = text.split()
result = ‘’
stars = ‘*’ * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =’ '.join(words)

return result

And the reason Im asking is because I want to learn to write better code, so if the Codecademy code is a better way to solve the problem, then I want to strive to write code that looks more like the Codecademy code instead of continuing to write code the way I do…


#5

One of these tests is redundant. Pick one, and don’t check in the else clause.

if on then something else something else (it must be off)

as in,

if i == word: x.append('*' * len(word))
else x.append(i)

To re-iterate, think in terms of better understanding, not better code. One is a worthwhile goal, the other is subjective desire with lack of understanding. Set subjectivity aside and learn objective reasoning through study of as many various methods as you can drum up.

def censor(text, word):
    return text.replace(word, '*' * len(word))

is that better? No. It’s different. That is all. But what does it teach us? Very little. It takes all the fun out of writing algorithms.


#6

Thats a great point!! I just re-wrote the code in my notebook :wink: But you see what I mean, If I didn’t ask I would’ve probably continued writing similar code, but now I’ll have this as an example in the back of my head next time I try to solve a similar problem.

I see what you mean, but you know, several times I’ve heard people online comenting some kind of code and saying that they would never hire somebody because their code is ugly etc. So Im scared, for a lack of a better word, of learning to write code in a way that might be considered ugly/bad…


#7

When hiring, one would hope they are looking for someone who is a good team player, positive minded and mentally strong, patient and persistent, determined and able to learn new things. They hire for what you can become, not what you are. It takes time to fit into an organization, and no matter how much one knows, there will be much yet to learn. I would rather look for someone who is open-minded, willing to try new things and not so arrogant they cannot admit their own mistakes or weaknesses. If someone hires you at the top of your game, what is in it for them? Watching you go down hill? They want you to grow, not stagnate.

Creative people start with nothing, build on their ideas, review and revise until they are satisfied, then they tear it apart and do it again, learning as they go. It takes at least four drafts to write a decent essay. Programming is much the same thing. Focus on what you are learning, not whether you are writing pretty code or not. How much do you understand? That is more important, to my mind, than how cool your code is.


#8

Extra Study

What if we do not have a split() method or a list() function? How will we detect each word?

If we do it like split(), we target space characters.

text = "the rain in Spain falls mainly in the plains"
temp = ''
while len(text) > 0:
    temp += text[:text.index(' ') + 1]
    text = text[text.index(' ') + 1:]
    if text.isalpha():
        temp += text
        text = ''
print (temp)

the rain in Spain falls mainly in the plains

That’s proof we can replicate the string word (and space) by word. This will need some refinement, but it’s a first step. Remember, we start from nothing, and create.

What if we don’t have an index() method?

for i, v in enumerate(text):
    print (i, v)

What if we don’t have an enumerate() function?


#9

Im not sure, maybe there is some other function…or I would at least think there is another function we can use…


#10

I’m hinting at the core use of algorithms. Working with what we have to achieve an end. Draw upon the strength of the algorithm without reaching for built in functions or methods. The more we develop that skill, the better programmers we will be. It’s about developing one’s thought processes into step by step procedures and the use of logic. Learners bent on rote learning of built in features of the language will find themselves at a wall with each new language they approach. Learners with sound thinking, good algo skills and a firm grasp of logic can feel at home with any language.


#11

Down to basics…

no_split_censor.py
text = "the rain in Spain falls mainly in the plains the"
word = "the"
temp = pend = ""
for i in range(len(text)):
    x = text[i]
    if x == " ":
        if temp != word:
            pend += x + temp
        else:
            pend += x + "*" * len(word)
        temp = ""
    else:
        temp += x

# append the last word (no space after it)
if temp != word:
    pend += " " + temp
else:
    pend += " " + "*" * len(word)

# trim leading spaces
while pend[0] == " ":
    pend = pend[1:]

print (pend)
============ RESTART: D:\cc\discuss\users\mtf\no_split_censor.py ============
*** rain in Spain falls mainly in *** plains ***
>>> 

That’s almost brutal in its ugliness and repetition, but still fun to build. We don’t build from perfection, but toward it. Skeleton first, body second, skin last *.

*
This includes leveraging built-ins and available libraries. Obviously we are not writing production code. But this could well be production if it is on a spacecraft with limited memory and storage. Overhead is the biggest concern. Garbage collection needs to be adamant. That’s where functions come into play. When we leave them, all the data in their scope is garbage collected and memory freed up for the next operation.

It is vitally important that one spend a good deal of time working with scant resources in terms of keywords and memory. Learn what can be done with the least. That will be time well spent. The leveraging can come when the demand is there.


#12

It was kind of challenging to read hehe

I see what you mean. Hopefully I can get good at it after a while. I’ll try to practice as much as I can…Im actually thinking of signing up at codesignal(I think it used to be called codefights) to practice (after I finish the Python course here of course)


#13

I was just looking through the Codecademy code and I stumbled on something that got me wondering…

def censor(text, word):
words = text.split()
result = ‘’
stars = ‘*’ * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =’ '.join(words)

return result

We know that stars is already equal to four ‘’*’’…
But what is going on here…?

if i == word:
words[count] = stars

I see that the count number is used as index that represents each part of the string, BUT…and when there is a match, the four * come in to play, and everything going through the for loop and the if statement and going out afterwards is stored back in the variable words…am I correct? Because nothing is stored inside result’’ until the end when we join all parts of the string that is stored inside the variable words…

In my function I created a new list that I returned later:

text = text.split()
newtext = []

But they skipped that part and stored everything back in the same varibale…

words = text.split()


#14

count is actually an index. As each word is iterated, count is increased by one. If that word is to be censored, then the element at index[count] is swapped out.


#15

Yes that part is fine, Im just wondering if everything is stored back in the variable words after it goes through the loop


#16

Yes. The above is an in-place change.


#17

Oh great, then I’ll put it in my notes. Its a good thing to know that I actually I could’ve done it this way istead of creating a list etc


#18

The more ways you try, the more new things you learn. Don’t settle on any one solution as being better than another. We’re learning, so just keep adding to the pile.


#19

Exactly, thats why Im going through my notes now and look at the Codecademy solutions that differ from mine, and try to understand how they did it…that way I’ll learn more ways to solve similar problems in the future :wink:


#20

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.