I will update the techniques I learned in show coding recently started on the site codefights from time to time.
Short coding consideration
The comparison operator <= can basically be omitted and can be reduced by ** 1 character **
# long
a <= 3
# short (When a is an integer)
a < 4
Corresponds to -1 and +1 respectively However, since it has a higher priority than the multiplication operator, it can be reduced by ** 2 characters ** by omitting the parentheses.
# long
b * (a - 1) * 5
# short
b * ~-a * 5
: (Colon) and the left side of the assignment can be omitted
# long
if a < b:
c = 4
else:
c = 2
# short
c = 4 if a < b else 2
(Python2 only)
Use \ \
to convert to string
# long
str(1600)
# short
`1600`
If you want to return a logical value exactly, use a logical operation without using True or False.
# long
b = False
# short
b = 0 > 1
# long
return True
# short
return 1 > 0
import as Also shorten the module to import
# long
import math
math.sqrt(10)
# short
import math as m
m.sqrt(10)
Connect multiple string comparisons and perform at once
#Both the first and last characters match
# long
a[0] == b[0] and a[-1] == b[-1]
# short
a[0] + a[-1] == b[0] + b[-1]
#a and b,c and d have the same length(Or unique even when combined)If
# long
a == b and c == d
# short
a + c == b + d
If it is a challenge of codefights, the answer in the form of a function will be tested.
lambda If possible, you can reduce ** 4 characters ** by converting the function to a lambda expression.
# long
def Hoge(n):
return n * 2
# short
Hoge = lambda n: n * 2
Argument names can be one character because there are many cases where they are not explicitly called.
# long
def Hoge(arg):
return arg ** arg
# short
def Hoge(a):
return a ** a
Assign to a one-character variable when using recursion
# long
def LongLongHoge(a):
if a < 3:
return a
return LongLongHoge(a - 2) * LongLongHoge(a - 1)
# short
def LongLongHoge(a):
if a < 3:
return a
return t(a - 2) * t(a - 1)
t = LongLongHoge
Even shorter with lambda and simultaneous assignment
# short
LongLongHoge = t = lambda a: a if a < 3 else t(a - 2) * t(a - 1)
# long
t = a % 3
if t == 0:
a = a * 2
elif t == 1:
a = 0
elif t == 2:
a = t * 2
# short
a = [a * 2, 0, (a % 3) * 2][a % 3]
# short
t = a % 3
a = [a * 2, 0, t * 2][t]
(a <b) returns True and False, but can be used for operations as 1, 0, respectively. There are many patterns that can be omitted by using it
# long
c = 4 if a < b else 2
# short
c = 2 + 2 * (a < b)
# long
myhex = lambda n: '%X' % n
# short
myhex = '{:X}'.format
myhex = '%X'.__mod__
Recommended Posts