Is my code for the censor exercise too "rough"?


#1

Hey guys!

I just completed the "Censor" exercise in the "Practice makes Perfect", and it works perfectly!

Then you're probably wondering "What is the problem?". Well, it's just that i feel like the bit of code i wrote was too unoptimized, too "rough" for an exercise like that.

I'm not saying it was easy, quite the opposite in fact. It took me a good portion of my day to figure it out, but with everything I've been reading about the importance of being "quick and optimized" for a programmer, i wasn't as satisfied as i thought i'd be when i solved the problem.

def censor (text, word):
    x = 0
    censored_sentence = ''
    while x < len(text):
        word_to_compare = ''
        for x in range(x, len(text)):
            if text[x] != ' ':
                word_to_compare += text[x]
            else:
                index = x
                break
        print word_to_compare
        if word_to_compare == word:
            for i in word_to_compare:
                censored_sentence += '*'
        else:
            for i in word_to_compare:
                censored_sentence += i
        if x != len(text) - 1:
            censored_sentence += ' '
        x += 1
    return censored_sentence

I forgot about the split function and didn't want to check the hints, so i had to make do with something else.

Tell what you think of my code guys. I'm 16 and I've been through some programming languages, but i always end up quitting because of a reason or another. But this time, I found the process of learning Python really fun (probably because of this site) and decided to stick with it until the end, so i'd really like to know if i'm on the right path.


#2

well, you don't use any built in functions, that will make your code longer.

quit impressive that you managed to solve this problem without any built in function, optimization will come later

one you thing you should worry about is strings vs list

strings are not mutable. Each character takes 1 byte in memory.

so, if have 'ab' + 'bc' a new string with combined result needs to be created

on the other hand, list are mutable so that will take less memory


#3

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