r/badcode • u/Jeremy_Thursday • Oct 19 '20
python The rest of the codebase is equally fucking depressing and buggy, part of an AI speech to text backend I contracted a team to build :(
73
u/DrDelbertBlair Oct 19 '20
What would be a better solution to this? Just like a for loop that iterates the replace function through a list of the characters or is there something that works better than that?
161
u/Jeremy_Thursday Oct 19 '20
User input is really dirty here and anything that isn’t alphanumeric or an apostrophe is going to fuck shit up. So in this case we need to take a whitelist approach instead of a blacklist approach.
Regex is a tool which is great for purging text of characters you don’t want (aka characters not on your whitelist). It’s typically the tool used for stuff like this if you’re replacing more than like one type of character/text-pattern.
26
28
10
5
u/DreadCoder Oct 19 '20
A regex that converts anything that's not 'a-z, A-Z, 0-9' into ''
ONE line would have done it
4
8
Oct 19 '20 edited Oct 19 '20
Assuming this is python:
DisallowedCharacters = [{characters you wanna remove}] for i in str: if i in DissalowedCaracters: str.replace(i, " ")18
u/igoromg Oct 19 '20
Quadratic complexity right here. A linear solution exists which is also much more gc friendly:
translation_table = { chars you want to keep, also upper to lowercase } res = [] for ch in string: res.append(translation_table.get(ch, ' ')) ''.join(res)1
u/omg_drd4_bbq Oct 19 '20
You should also look into str.maketrans and str.translate. It is probably faster (depends on use case) and more idiomatic.
1
u/0x564A00 Oct 19 '20
That's the actual bad code. I now have to insert 143840 different characters into a hash table just because I care about the remaining 19! ComLarsic's code was fine - much clearer even - apart from missing lower(). In languages other than Python (which is horrible inefficient), a array of characters of small (19 in this case) length can be more efficient even.
3
u/igoromg Oct 19 '20
Bruh, if you want to keep all but some chars just insert the (char, ' ') pair into the table and pass the char you want to keep as the default param to dict.get
0
Oct 19 '20
[deleted]
4
u/igoromg Oct 19 '20
Now that I gave it a second thought I've misunderstood your comment. the complexity of my comment is linear if translation_table is a hash table with constant time access. The comment I replied to is quadratic since if every character in the string is in DisallowedCharacters, replace will be called for every character of the string and each invocation will traverse the entire string thus quadratic.
0
Oct 19 '20
[deleted]
1
u/igoromg Oct 19 '20
Yes and then if that character is in the list it calls the replace() method which in itself is a linear traversal of the string so its actually n*(k+n)
0
u/sebamestre Oct 19 '20
Yes, but the replace method will only be called k times, because it (presumably) replaces every instance of
ifrom the string.Thus, it is O(N*k)
1
u/igoromg Oct 19 '20 edited Oct 19 '20
first of all changing a collection you're iterating over is the epitome of bad code and many languages will throw an error over this. second that's not how it'll work at all, since strings are immutable and replace actually creates and returns a new string. so in this regard the code in question will not function at all on top of being n*(n+k) worst case complexity.
Here's an example where n = 46, k = 2
https://www.online-python.com/yrhVDLsbAz1
u/sebamestre Oct 20 '20
I didn't know it didn't modify the string in place. I don't use python.
Well, if it did modify in place, it would work and run in O(nk). Do you at least agree with that?
I mean, I can tell you understood what I meant. You're just being pedantic, all the while moving the goalposts.
→ More replies (0)
34
22
Oct 19 '20
What a terrible day to have eyes.
10
5
Oct 19 '20
Well, do you want a text to speech browser reading you all of this instead? I would rather have eyes.
44
u/LSatyreD Oct 19 '20 edited Oct 19 '20
I see nothing wrong with this.
edit: Oh wait, I see the problem now. They forgot to put an if statement to check if the replacement character is present or not before each replace.
Here I wrote an improved / updated version for you that should be safer (note: I only wrote the first four replaces, the rest is left as an excercise for the reader):
#Method to clear text
def clear_text(text=str(None)):
"""
Replaces bad characters in text with clear text.
Takes text as input and returns clear text.
Text should be a string.
"""
if text is not None:
return_text = text
try:
#Replace ,
for split_text in text.split():
try:
for split_character in split_text:
if split_character == ','
return_text = return_text.replace(',', ' ')
else:
pass
except:
print("ERROR replacing string of ,")
pass
finally:
return_text = return_text
pass
#Replace !
for split_text in text.split():
try:
for split_character in split_text:
if split_character == '!'
return_text = return_text.replace('!', ' ')
else:
pass
except:
print("ERROR replacing string of !")
pass
finally:
return_text = return_text
pass
#Replace ?
for split_text in text.split():
try:
for split_character in split_text:
if split_character == '?'
return_text = return_text.replace('?', ' ')
else:
pass
except:
print("ERROR replacing string of ?")
pass
finally:
return_text = return_text
pass
#Replace :
for split_text in text.split():
try:
for split_character in split_text:
if split_character == ':'
return_text = return_text.replace(':', ' ')
else:
pass
except:
print("ERROR replacing string of :")
pass
finally:
return_text = return_text
pass
except:
print("ERROR unknown error in clear_text")
pass
finally:
return return_text42
u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20
KAPPA AF someone get this man the “bad coder” flair
14
u/LSatyreD Oct 19 '20
I edited in some good code for you, feel free to use it (:
15
u/Jeremy_Thursday Oct 19 '20
Haha it’s pretty gorgeous ❤️ I think I’ll just stick with this and add more characters to blacklist the entire unused Unicode space I don’t want.
20
u/mind_overflow Oct 19 '20
i hope you're sarcastic because if you are, then what you said is hilarious, and if you aren't, it's still hilarious.
8
u/LSatyreD Oct 19 '20
The world may never know. I added some revisions to OP's original code to my previous comment, in case anyone needs a better way to do it.
9
u/taptrappapalapa Oct 19 '20
Oh my god. I think that’s somehow even worse than OPs code, as you literally no regard for it exponentially increasing runtime as I think that’s a O(4n2 ) runtime right there bud. It would be way faster just to use regex
Edit: didn’t notice the .replace methods when calculating runtime, holy shit that’s a lot of array computations.
6
2
u/LSatyreD Oct 19 '20
And don't forget there's a double nested for loop before the actual check if the character is even present. Assuming it needs to replace any non A-z 0-9 character across the unicode space, with any reasonable length message, and who knows how many messages there are.... yeah.
I mean I'm sure I could "improve" it further. But ya have to work out all these improvements before the first release that way you can later remove them, one at a time, to make users happy about "performance improvents" and "reduced processing time".
6
u/taptrappapalapa Oct 19 '20
Just imagine the runtime of iterating over strings that much for each input.
5
9
44
u/EyeInDaSky_ Bad coder Oct 19 '20
return ''.join ([' ' if i in ',!?:;)(".\r\n&\u2028_*' else i for i in ' '.join ([i for i in text.split (' ') if i != ''])])I am pretty sure this would work fine
10
u/Jeremy_Thursday Oct 19 '20
Thank you haha
0
u/EyeInDaSky_ Bad coder Oct 19 '20
If you need some help I think I could do some optimization, I like that and I think I could do a lot for free.
17
u/Jeremy_Thursday Oct 19 '20
I need a whitelist regex approach here instead of this blacklist BS. The regex pattern should get rid of anything that isn’t alphanumeric or an apostrophe [ ‘ ]. Thanks so much for offering to help, that’s really nice of you! ❤️
11
u/Darudekappastorm12 Oct 19 '20
alphanumeric_string = filter(str.isalnum, a_string)
4
u/Jeremy_Thursday Oct 19 '20
Thanks! I also need apostrophes. Probably will just muddle my way through regex.
0
Oct 19 '20
[deleted]
6
u/AutoModerator Oct 19 '20
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/DankTrain, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
You can find some examples in the reddit help documentation.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
3
7
-2
u/notger Oct 19 '20
Don't offer to fix work for free, that the people that effed it up were paid for.
Your tag instills confidence. I like the contrast, because you actually seem to know what you are doing, unlike the guys from above.
68
u/8asdqw731 Oct 19 '20
not as readable as text above, just because something is split on several lines doesn't mean it's bad code
24
u/TheOnlyTrueEnte Oct 19 '20
It's also way slower in this case because it has to iterate over the text and create a new string of equal length about 20 times.
3
u/8asdqw731 Oct 19 '20
that could be an issue, if it's called often,
if it's not then I'd probably still go with the more readable variant
3
5
u/Taburn Oct 19 '20
Did you pay them for their buggy code?
21
u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20
Of course! We’re not assholes. We did also drop them when they “fixed bugs” but actually didn’t fix the bugs or bother testing to see their “fix” didn’t work.
Their bug fixes were truly retarded, didn’t work and then they wanted more money to do work they’d already been paid to do.
We got burned but not too bad. I have heard some real horror stories, don’t hire developers if you don’t know how to code and don’t hire teams that make you go through an intermediary person to talk with the developers. Just my 2 cents.
1
u/Taburn Oct 20 '20
That's very kind. I was thinking that if what they gave you didn't meet the performance specification then they shouldn't get any money for it.
2
u/Tm1lly Oct 19 '20
You need to contact a priest to cleanse this... only god can save this code base.
2
2
u/honkinggr8namespaces Oct 19 '20
i hate how your editor font is in 2 different sizes at the same time
1
u/Jeremy_Thursday Oct 20 '20
Heh, you caught me! I kinda like it but yea it can occasionally be awkward to not have that perfect mono space
2
u/asaf92 Oct 20 '20
2028? What about 2027? Is that ok?
1
u/Jeremy_Thursday Oct 20 '20
No, they literally just coded checks for everything that was in an example. This will be replaced with a whitelist instead of a blacklist
77
Oct 19 '20
I'm shocked they did text.lower() instead of just doing a text.replace("A", 'a')
49
u/AlbusSeverus14 Oct 19 '20 edited Oct 19 '20
So I can write "Contributed to AI speech to text backend open source project" on my resumé:
text = text.replace('A', 'a') text = text.replace('B', 'b') text = text.replace('C', 'c') text = text.replace('D', 'd') text = text.replace('E', 'e') text = text.replace('F', 'f') text = text.replace('G', 'g') text = text.replace('H', 'h') text = text.replace('I', 'i') text = text.replace('J', 'j') text = text.replace('K', 'k') text = text.replace('L', 'l') text = text.replace('M', 'm') text = text.replace('N', 'n') text = text.replace('O', 'o') text = text.replace('P', 'p') text = text.replace('Q', 'q') text = text.replace('R', 'r') text = text.replace('S', 's') text = text.replace('T', 't') text = text.replace('U', 'u') text = text.replace('V', 'v') text = text.replace('W', 'w') text = text.replace('X', 'x') text = text.replace('Y', 'y') text = text.replace('Z', 'z')26
Oct 19 '20
I need you to implement multi-language by next week. I'm counting on you.
7
u/mfb- Oct 19 '20
text = re.sub('[^a-zA-Z0-9]','',text)
Fixed the issue with the strange outputs, boss.
Edit: Wait, this seems to be nearly what OP wants.
3
u/LonelyContext Oct 21 '20
Might want to throw an \s in there sothatitdoesntallruntogetherlikethis
3
18
15
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Oct 19 '20
Image Transcription: Code
def clear_text(text):
text = text.replace(',', ' ')
text = text.replace('!', ' ')
text = text.replace('?', ' ')
text = text.replace(':', ' ')
text = text.replace(';', ' ')
text = text.replace(')', ' ')
text = text.replace('(', ' ')
text = text.replace('"', ' ')
text = text.replace('.', ' ')
text = text.replace('\r', ' ')
text = text.replace('\n', ' ')
text = text.replace("&", ' ')
text = text.replace("\u2028", ' ')
text = text.replace("”", ' ')
text = text.replace("“", ' ')
text = text.replace("-", " ")
text = text.replace("*", " ")
text = text.replace(" ", ' ')
text = text.replace(" ", ' ')
text - text.lower()
return textI'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
4
u/lachyBalboa Oct 19 '20
I like the mixed use of double- and single-quotes. Along with all the other bullshit, that isn't even consistent
1
3
u/antonivs Oct 20 '20
Pull requests and code review catches this kind of thing early. You control the repo, they use it. For bonus points set up a static code analysis tool that runs whenever code is pushed to the repo.
2
2
2
1
1
1
1
1
u/Poddster Oct 19 '20
Contractors are notorious bad-coders. The reason is obvious: they never have to deal with their crap code.
1
1
Oct 19 '20
I wonder, is there a python standard library function that takes a str and a dictionary and replaces all instances of keys with values in the str?
-10
u/doggyStile Oct 19 '20
Still better than using regex!!
10
u/Jeremy_Thursday Oct 19 '20
Honestly I absolutely hate regex and I'd take something like this for readability in different circumstances. The problem is user input is super dirty here and we really need a whitelist approach as opposed to a blacklist approach.
2
2
0
Oct 19 '20
[deleted]
6
u/Jeremy_Thursday Oct 19 '20
Lmfao I love this comment! Made me laugh super hard. Any chance you could give me the pattern to purge anything that’s not alphanumeric or an apostrophe. I don’t need to replace them with a space or anything, just yeet them into the void.
2
u/the-nick-of-time Oct 19 '20
In python,
re.sub(r"[^a-zA-Z0-9']", "", text)will work assuming you need only ASCII characters; it means "replace every character that is not a-z or 0-9 with nothing". You could instead dore.sub(r"[^\w']", "", text)where \w is a character class that encompasses basically any word-like character in unicode, which encompasses letters, numbers, and the underscore.1
Oct 19 '20
[removed] — view removed comment
1
u/Jeremy_Thursday Oct 19 '20
Yea it’s an ass backwards blacklist when a whitelist is what’s called for.
2
u/RFC793 Oct 19 '20
translatewould be better IMHO. But, really, this should be whitelisting instead of blacklisting.7
u/Jeremy_Thursday Oct 19 '20 edited Oct 19 '20
Yea whitelisting 100% needed here. was my first instinct as well.
3
u/ywBBxNqW Oct 19 '20
translate would be better IMHO.
Why?
1
u/RFC793 Oct 20 '20
Readability wise, it expresses “replace all this stuff with space” more clearly. No need to switch gears and mind-parse a regex. No need to think about what needs to be escaped etc. just: here’s a list of characters.
Computationally, it’s all you need. Better than creating N intermediate strings with a chain of
replace. But not overkill like a regex, which despite their name, are not regular.1
u/Exnixon Oct 19 '20
You probably don't need the double space anyway. The original code looks like they're making a buggy attempt to collapse all whitespace down to a single space. You'd want to do
s/ */ /gafter you do all the single character substitutions.
2
Oct 19 '20
Or rather,
s/ \+/ /g. The asterisk applies even to zero spaces, and ends up inserting a space between every character.1
0
Oct 20 '20
[deleted]
1
Oct 29 '20
Yes that would work but makes for a unorganized line imo.
I would use an array/list of banned chars and just use
for i in banned_chars: string.replace(i, ' ')The second line is indented but was made on mobile and doesn't work apparently
432
u/grrangry Oct 19 '20
The real wtf being a neon color theme and an editor with a transparent background.