79
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 21 '20
Image Transcription: Code
for words in user_file:
get_word = words.replace("-", " ").lower().split()
for word in get_word:
user_words.add(word.replace('.', '').replace(',', '').replace('!', '').replace('?', '').replace(':', '')
.replace(';', '').replace('\"', '').replace('-', '').replace('[', '').replace(']', ''))I'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!
50
17
u/_Kiiler_UwU Sep 21 '20 edited Sep 21 '20
badTokens = ["!","$"...]
newStr = "''.join(c for c in myString if not c in badTokens)
fuck Regex, all my homies use competitive knowledge8
u/Jonno_FTW shameless Sep 21 '20
List lookups are slow, use a set, or better yet, use translate. https://docs.python.org/3/library/stdtypes.html#str.translate
3
u/CodenameLambda shameless Sep 21 '20
In my experience (though I might just not remember some variables to it) sets are slower when you're only dealing with a few elements.I'm apparently misremembering (or something has changed):
Some quick tests gave me these timings for three characters to delete (via
python3 -m timeit -s "setup code" -n 1000000 -r 5 "test expression):
.translate: 626 nsec.replace: 208 nsecre.sub: 1.59 usec.subwith a compiled regex: 1.13 usec
predefined list (like in _Kiiler_UwU's comment): 4.08 usec
inline list: 3.9 usec, weirdly enough
predefined set: 2.52 usec
inline set: 2.43 usec (I think Python might be optimizing behind the scenes to some degree or something)
predefined string: 2.46 usec
inline string: 2.41 usecHonestly those findings kind of make sense too - the iterator solutions all have the iteration in Python, while regex,
.translateand.replaceare probably implemented in C; where.translatehas to deal with many different types plus the overhead of a hashmap while.replaceonly deals with single strings; while the regex solution has to deal with all the stuff regex entails. Though this is of course just wild speculation on my part, and my tests might already be faulty.3
u/AutoModerator Sep 21 '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/_Kiiler_UwU, 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.
48
u/moekakiryu Sep 21 '20 edited Sep 21 '20
In case anyone's wondering, here's the timeit results of regex vs replace (tl;dr string.replace is WAY faster)
Function Definitions: (imports implied)
def stringReplace(s,old,new):
for c in old:
s=s.replace(c,new)
return s
def reReplace(s,old,new):
return re.sub("["+old+"]",new,s)Each function was called 500,000 times using timeit.repeat, with s being a random 100 letter string, old being a random 5 letter string, and new being an empty string.
EDIT 3: As pointed out in another comment, this is not a fair test since the old string is regenerated every time, but is constant in the original post. This test is a more realistic solution to the problem
Results:
| stringReplace: | reReplace: | |
|---|---|---|
| Mean: | 9.48s | 16.29s |
| Best: | 9.44s | 16.21s |
| Worst: | 9.55s | 16.34s |
(5x100,000 iterations per test, all times are per 100,000 iterations)
EDIT: all da formatting
EDIT 2: fixed table alignment
24
u/Nall-ohki Sep 21 '20
This test is different than the given problem.
In the original, the replacements are static, and could benefit from re.compile() on a static var
14
u/moekakiryu Sep 21 '20 edited Sep 21 '20
perfect timing! You are absolutely correct! I was just writing the results of the additional test using
re.compile. With a more fair test, they ended up being comparable but see my note at the bottom.Function Definitions:
(
stringReplaceis same as above)def compiledReplace(s,oldPattern,new): return re.sub(oldPattern,new,s) randomChars = ''.join(random.choice(string.ascii_letters) for i in range(5)) randomPattern = re.compile("["+randomChars+"]")I ran the test again with the same parameters as before, but using
randomCharsforstringReplaceandrandomPatternforcompiledReplaceResults:
stringReplace: compiledReplace: Mean: 14.38s 14.44s Best: 13.07s 12.99s Worst: 16.07s 16.50s (5x100,000 iterations per test, all times are per 100,000 iterations)
I did have another program running in the background which resulted in slightly slower operating times overall, but the conditions did not change between the two tests.
So yeah, under perfectly optimal conditions for regex it breaks even with
string.replacebut it does suffer from readability concerns from needing to escape special characters and is slower if the search pattern changes on each iteration (which was rightly pointed out is not the case in the original post).edit: typo
10
u/Nall-ohki Sep 21 '20 edited Sep 24 '20
That's to be expected - replace is a single purpose algorithm that's optimized for its case whereas regex is generally a compiled nondeterministic finite automaton (fast) or a tree parsed by a recursive descent parser (slow), though other approaches are possible.
The fact that it's that close in speed for being its own general sub language is pretty damn impressive as a technology.
I've written a niche special-purpose parsing system inspired by regex design during my first Masters, and it's amazing how useful having a less powerful language embedded gives you the ability to structure problems well while still being efficient.
Honestly, I think we'd benefit from language-level encoding of regex as opposed to string encoding in a lot of cases for readability.
1
2
u/RFC793 Sep 22 '20 edited Sep 22 '20
I wanted to test 2 other implementations, and I was concerned how much the random number generation is affecting the measurements. This code generates 100,000 random strings prior to testing. This list is cycled through for each iteration of each implementation. I had to do over 1 million iterations to get usable durations.
Code:
#!/usr/bin/env python3 import itertools import random import re import string import timeit bad_chars = '.,!?:;\-[]' bad_char_set = set(bad_chars) bad_re = re.compile(r'[.,!?:;\\\-\[\]]') bad_trans = str.maketrans('', '', bad_chars) iters = 5 * (10**6) repeat = 5 def str_replace(): s = next(inputs) for c in bad_chars: s = s.replace(c, '') return s def re_sub(): return bad_re.sub('', next(inputs)) def str_translate(): return next(inputs).translate(bad_trans) def join_generator(): return ''.join(c for c in next(inputs) if c not in bad_char_set) def random_str(length): return ''.join(random.choices(string.printable, k=length)) print("Generating inputs...") random_strs = [random_str(50) for x in range(100000)] inputs = itertools.cycle(random_strs) for fun in str_replace, re_sub, str_translate, join_generator: print(f"{fun.__name__:16s}", end='', flush=True) results = timeit.repeat(stmt=fun, number=iters, repeat=repeat) print(f"min: {min(results):.4f}, max: {max(results):.4f}, avg: {sum(results)/len(results):.4f}")Output:
str_replace min: 8.9091, max: 9.0107, avg: 8.9448 re_sub min: 7.5655, max: 7.6123, avg: 7.5922 str_translate min: 12.6937, max: 13.2049, avg: 12.8160 join_generator min: 20.8355, max: 21.3530, avg: 21.0275I surely thought str.translate would be the fastest. It is purpose-built, and not as computationally complex as regular expressions. Boy was I wrong.
1
u/AutoModerator Sep 22 '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/RFC793, 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.
10
8
u/Jonno_FTW shameless Sep 21 '20
Try
string.translate, it avoids the overhead of a loop:t = str.maketrans({c:"" for c in ".,!?:;\"-[]"}) def replace(s): return s.translate(t)10
u/moekakiryu Sep 21 '20
Your wish is my command:
stringReplace: translateReplace: Mean: 9.69s 9.56s Best: 9.62s 9.46s Worst: 9.78s 9.64s (5x100,000 iterations per test, all times are per 100,000 iterations)
This definitely looks faster. Since this test is relatively small, its possible
string.translatecould be faster for larger problems, but tbh I'm all tested out and don't really feel like looking into it. Nice solution all the same!! I'll have to remember this one4
u/Jonno_FTW shameless Sep 21 '20
If you ever do codewars most of the solutions will use it as part of one liners (where required).
3
u/anamorphism Sep 21 '20
assuming all punctuation is to be replaced:
s.translate(None, string.punctuation)1
u/CodenameLambda shameless Sep 21 '20
Why the
None,?EDIT: Nvm, it appears to be a python2 thing, where the second argument is the list of characters to remove, if I'm not mistaken
1
u/RFC793 Sep 22 '20 edited Sep 22 '20
I thought the same and tested it. Interestingly, it is quite slow: https://reddit.com/r/badcode/comments/iwxm89/_/g66s11g/?context=1
2
u/Mr2-1782Man Sep 21 '20
Should point out that this is valid for only very simple constant to constant string replacements. Any variability will give regex the edge.
11
u/QFTornotQFT Sep 21 '20
11
u/xjcl Sep 21 '20
Oh, this one is very bad. The top 3 answers are using Python 2 syntax that won't work in Python 3.
4
u/Cometguy7 Sep 21 '20
For the first time, python (ok, python 2) has a feature of which I am jealous.
5
u/Chunderscore Sep 21 '20
Out of interest, what do you usually use?
1
u/Cometguy7 Sep 21 '20
Mainly C#. And if anyone's about to start bashing on C#, I don't really care, as it's an enterprise decision, not mine. Python has plenty of interesting things about it, this is simply the first I've seen where I said, man, I wish I had that.
3
u/TinyBreadBigMouth Sep 21 '20
str.translateis still available in Python 3, the interface just changed a little.translation_table = str.maketrans('', '', '.,!?:;"-[]') print(text.translate(translation_table))https://docs.python.org/3/library/stdtypes.html#str.translate
29
u/KookyWrangler Sep 21 '20
Honestly might be more maintainable.
15
u/sendvo Sep 21 '20
how is this mess more maintainable than a single regex replace call?
11
u/xjcl Sep 21 '20
Regexes are too powerful and can introduce subtle bugs. Java has this problem with their
String#splitmethod which takes a regex String. So while in Python'8.8..'.split('.') == ['8', '8', '', ''], in Java you have to doubly escape the dot using"8.8..".split("\\."), EXCEPT that will result in a String[] of length 2 rather than 4, so you ACTUALLY have to do"8.8..".split("\\.", -1).Another example:
>>> import re >>> re.findall('\(.*\)', 'whitespace bad (haha) (not really)') ['(haha) (not really)']It is not obvious how to fix this:
>>> re.findall("\(.*?\)", 'whitespace bad (haha) (not really)') ['(haha)', '(not really)']1
u/Mr2-1782Man Sep 21 '20
That's just an example of not understanding what you really want. Both results are valid, if you want to match everything but a specific character it would be more obvious to actually write that.
>>> re.findall("\([^()]+\)", 'whitespace bad (haha) (not really)') ['(haha)', '(not really)']36
u/KookyWrangler Sep 21 '20
It's perfectly obvious what every step does and it's easily scalable. Poorly written regex would be worse.
17
u/chunes Sep 21 '20
I'm curious what you mean by scalable.
Doesn't each additional replace() call iterate over the entire string?
10
u/Ahajha1177 Sep 21 '20
He never said it was fast, just that it's very obvious what's going on.
6
u/moekakiryu Sep 21 '20
fwiw, string.replace is faster than re.sub (I commented the test results lower in this thread)
3
u/KookyWrangler Sep 21 '20
If you need something else, you can just add another replace().
5
u/Not_Sugden Sep 21 '20
i mean a regex is easy too, infact easier no? just add the character you want to the regex, 1 (maybe 2 if it needs escaping) key press, vs typing out
.replace("...", "");4
u/Qesa Sep 21 '20 edited Sep 21 '20
yes,
word.replace('/[.,!?:;\"-\[\]]/g','')is a true mystery that nobody can discernEDIT: Or since it's python and re.escape exists,
word.replace('/[' + re.escape('.,!?:;"-[]') + ']/g','')8
u/KookyWrangler Sep 21 '20
That's not how replace() works.
9
u/Qesa Sep 21 '20
Ah damnit that's the javascript usage. My python's rusty.
2
u/KookyWrangler Sep 21 '20
It's also better to use f-strings instead of re.escape.
2
u/the-nick-of-time Sep 22 '20
[r-strings] (https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals), not f-strings for this case.
2
u/Jonno_FTW shameless Sep 21 '20
Python has
re.suband therstring, so the call would bere.sub(r'[.,!?:;"-\[\]]', '', word)1
u/Qesa Sep 21 '20
Yeah I am actually aware of that, just haven't used python in a couple of years but have been doing a decent bit of web work recently, so with all the
replaces in the OP my brain entered js mode.2
4
24
u/wampastompah Sep 21 '20
Honestly? I've done this before. It's certainly less efficient than regex, no one will deny that. But it's a hell of a lot more readable and maintainable, and it's less error prone. You'd be amazed how many people are out there who don't know or are uncomfortable using regex. If you have those people in your code base, something like this can prevent hours of headaches in the future.
6
u/FistThePooper6969 Sep 21 '20
Regex is less code, but way less efficient than string operations in terms of performance
5
u/wampastompah Sep 21 '20
Less code != More readable and maintainable. We're past the days when you had to limit the length of your code and variables, and usually things that are too short can be harder to read. Look at most Code Golf examples.
And performance depends on the situation. In Python, Regexes need to be created and compiled, which adds some overhead, but you only have to loop through the string once. In the case where there's only one word ten million characters long, a regex is way more efficient than looping through looking for each character one at a time. But in a realistic scenario with a couple hundred average english words, it really doesn't matter much.
2
u/Ultraflame4 Sep 21 '20
what is regex. I also thought it had something todo with registeries. It sounds complicated. plz teach
5
u/MysticTheMeeM Sep 21 '20
You might be thinking of RegEd a common abbreviation for Windows registry editor.
3
Sep 21 '20
Kids these days.... Real men parse html with regex 😉😉
4
u/gregrainman314 Sep 21 '20
HTML and regex go together like love, marriage, and ritual infanticide.
4
4
u/Needleroozer Sep 21 '20
Programmer: I have a problem.
Co-worker: Use RegEx.
Programmer: Now I have five problems.
2
2
1
1
u/omegasome Sep 22 '20
At the very fucking least just put your replacements in a list and use a FOR loop:
for c in bad_characters:
word = word.replace(c, '')
user_words.add(word)-1
u/Th3T3chn0R3dd1t Sep 21 '20
Dont see how regex would help - granted this is needlessly long but regex replacement would be even longer
164
u/gnutrino Sep 21 '20
I know people with an irrational fear of regex who will go to great lengths to avoid using it.