Python is the fastest way to randomly randomize strings

I want to randomize a string case, here is what I have:

word="This is a MixeD cAse stRing" word_cap='' for x in word: if random.randint(0,1): word_cap += x.upper() else: word_cap += x.lower() word = word_cap print word 

I am wondering if you can use list comprehension to make it faster. I could not use the lower () and upper () functions in randomchoice, I tried to do something like

 ''.join(randomchoice(x.upper(),x.lower()) for x in word) 

but I think this is wrong. Is something like this possible?

+6
source share
2 answers
 import random s = 'this is a lower case string' ''.join(random.choice((str.upper,str.lower))(x) for x in s) 

random.choice randomly selects one of two functions str.upper , str.lower .

This function is then applied to x for each letter in the input string s .

If the source string has all lowercase letters, I would use this code:

 ''.join(x.upper() if random.randint(0,1) else x for x in s) 

because the source code used a half-letter redundant str.lowercase in the case of a lowercase starting line.

By the way, look at another answer by Michael J. Barber. Python has high costs of function calls. In his code, he calls str.upper only once. In my str.upper code, approximately half the characters of the original string are called. Thus, a temporary line with an upper edge is created in the memory; the time efficiency of its code can be much greater.


Lo and here:

Code Sync Time Comparison: https://ideone.com/eLygn

+8
source

Try the following:

 word="this is a lower case string" caps = word.upper() ''.join(x[random.randint(0,1)] for x in zip(word, caps)) 

This should outperform your version because it raises far fewer upper calls and because, more importantly, it avoids the sequential O (N ^ 2) additions that you used in the loop version.

With the change of the question, you will need to create both lowercase and uppercase versions:

 word="This is a MixeD cAse stRing" caps = word.upper() lowers = word.lower() ''.join(random.choice(x) for x in zip(caps, lowers)) 

As suggested by Tim Pitzker in the comments, I used random.choice to select the letters from the tuples created by the zip call.

Since the question has been modified to focus more on speed, the fastest approach would probably be to use Numpy:

 ''.join(numpy.where(numpy.random.randint(2, size=len(caps)), list(caps), list(lowers))) 
+4
source

Source: https://habr.com/ru/post/902854/


All Articles