DEV Community

Cover image for tips for python short code part-1
ademdj19
ademdj19

Posted on • Updated on

tips for python short code part-1

1- appending an element to a list:

k+=[1] #same as k.append(1)
Enter fullscreen mode Exit fullscreen mode

2- get multiple lines of from stdin:

instead of

k=[input() for i in range(number_of_lines)]
Enter fullscreen mode Exit fullscreen mode

do

k=[i.strip() for i in open(0)]
Enter fullscreen mode Exit fullscreen mode

3- making a class:
there is multiple modules that have ready porpused classes and types to inherit from or use

usual class

class paper:
    def __init__(self,nl,*lines_):
       self.numberOf_lines = nl
       self.lines = lines_
Enter fullscreen mode Exit fullscreen mode

dataclass

from dataclasses import dataclass
@dataclass
class paper:
    lines: list
    numberOf_lines: int
Enter fullscreen mode Exit fullscreen mode

. . .
this libraries will help u make a readable classes with less characters and awesome features(compareablity , readable representaiton ...)
4- string manipulation:

k = "abcdef-ABCDEF-123456"
print(k[1:])  #  bcdef-ABCDEF-123456
print(k[:-1]) # abcdef-ABCDEF-12345
print(k[2:-2])#   cdef-ABCDEF-1234
print(''.join(filter(str.isupper   , k))) # ABCDEF
print(''.join(filter(str.islower   , k))) # abcdef
print(''.join(filter(str.isnumeric , k))) # 123456
print(*map("".join,zip(*k.split("-")))) # aA1 bB2 cC3 dD4 eE5 fF6
print(*[k[:i] for i in range(len(k))]) # all substrings "a ab abc abcd abcde abcdef ..." 
Enter fullscreen mode Exit fullscreen mode

5- code golfs:

Bi-Output:

lets asume you have to write "odd" if an input is odd and "even" if not
the first thing that come to mind is:

n = int(input())
if n%2==1:print("odd")
else:print("even")
Enter fullscreen mode Exit fullscreen mode

this code is 58 cahracter long
with a bit of python wizardry

print("odd"if int(input())%2else"even")
Enter fullscreen mode Exit fullscreen mode

from 58 char to 39
but we can do more

print("eovdedn"[int(input())%2::2])
Enter fullscreen mode Exit fullscreen mode

from 58 to 35 char

function name is repeated a lot

x,y = map(int,input().split())
names = input().split()
fathers = input().split()
mothers = input().split()
age,shoe_size = map(int,input().split())
weight,height,arm_length = map(float,input().split())
Enter fullscreen mode Exit fullscreen mode

228 char long
we notice that "input().split()" is repeated to many times
solution:

k=lambda:input().split()
x,y = map(int,k())
names = k()
fathers = k()
mothers = k()
age,shoe_size = map(int,k())
weight,height,arm_length = map(float,k())
Enter fullscreen mode Exit fullscreen mode

just like that we saved 47 characters, this example is made for explaining purposes , you can apply it to any repeating funtion or statment with long enough characters. but what i recommend in cases like this is to use stdin file(you can access it with 'open(0)' statment) and dicts to store input

Top comments (5)

Collapse
 
xtofl profile image
xtofl

Also, when you'd need to append 'a lot' to the same list, you could shortcut k+=[1] to a=k.append; now you can a(1). (save 2 chars per append; becomes profitable when you need N appends where N*len('k+=[]')>len('a=k.append')+N*len('a()') <=> N>5)

k+=[1]
k+=[2]
k+=[3]
k+=[4]
k+=[5]
Enter fullscreen mode Exit fullscreen mode

vs

a=k.append
a(1)
a(2)
a(3)
a(4)
a(5)
Enter fullscreen mode Exit fullscreen mode

Now I'm having fun :)

Collapse
 
marcinpohl profile image
Marcin Pohl

dis('k+=[1]')
1 0 LOAD_NAME 0 (k)
2 LOAD_CONST 0 (1)
4 BUILD_LIST 1
6 INPLACE_ADD
8 STORE_NAME 0 (k)
10 LOAD_CONST 1 (None)
12 RETURN_VALUE
dis('k.append(1)')
1 0 LOAD_NAME 0 (k)
2 LOAD_METHOD 1 (append)
4 LOAD_CONST 0 (1)
6 CALL_METHOD 1
8 RETURN_VALUE

append is faster, because you do not need to create a single element list

Collapse
 
ademdj19 profile image
ademdj19

is it shortest tho

Collapse
 
xtofl profile image
xtofl

Does that code run? map takes a function and an iterable; did you mean map(int, input().split())?

Collapse
 
ademdj19 profile image
ademdj19

thanks