Use string substitution and evalexec to deal with long keywordkeywords like lambdas:lambda that are repeated often in your code.
c="`x:`ya=lambda b:x"
execlambda c:lambda d:lambda e:lambda f:0 # 48 bytes (plain)
exec"a=`b:`c:`d:`e:`f:0".replace('`', 'lambda ') # 47 bytes (replace)
Can save strokes for a long run.
Alternatively, for a low number of things to replace, use string formatting:
compare:
exec"%sxexec"a=%sb:%sy%sc:x"%%sd:%se:%sf:0"%(('lambda ',)*2*5)
and
exec"`x:`y:x".replace('`','lambda ' # 46 bytes (%)
String formatting takes two chars per thing to replace inThe target string is very often 'lambda ', sowhich is 7 bytes long. Suppose your code snippet contains replacen wins if you need to replace a very large numberoccurences of strings'lambda ', and is s bytes long. Then:
- The
plain option is s bytes long.
- The
replace option is s - 6n + 29 bytes long.
- The
% option is s - 5n + 22 + len(str(n)) bytes long.
ProblemFrom a plot of bytes saved over plain for these three options, sequence point?we can see that:
- For n < 5 lambdas, you're better off not doing anything fancy at all.
- For n = 5, writing
exec"..."%(('lambda ',)*5) saves 2 bytes, and is your best option.
- For n > 5, writing
exec"...".replace('`','lambda ') is your best option.
For other cases, you can index the table below:
[ doThis(), doThat( 1), getValue 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 (occurences)
][2] +---------------------------------------------------------
3 | - - - - - - - - - - - - - - r r r r r
4 | - - - - - - - - - r r r r r r r r r r
5 | - - - - - - - r r r r r r r r r r r r
6 | - - - - - r r r r r r r r r r r r r r
7 | - - - - % r r r r r r r r r r r r r r
8 | - - - % % r r r r r r r r r r r r r r
9 | - - - % % r r r r r r r r r r r r r r
10 | - - % % % r r r r r r r r r r r r r r
11 | - - % % % r r r r r r r r r r r r r r
12 | - - % % % r r r r r r r r r r r r r r r = replace
13 | - - % % % r r r r r r r r r r r r r r % = string %
14 | - % % % % r r r r r r r r r r r r r r - = do nothing
15 | - % % % % r r r r r r r r r r r r r r
(length)
For example, if the string lambda x,y: (length 11) occurs 3 times in your code, you're better off writing exec"..."%(('lambda x,y:',)*3).