tips for python short code part-1

1- appending an element to a list:

k+=[1] #same as k.append(1)

2- get multiple lines of from stdin:

instead of

k=[input() for i in range(number_of_lines)]

do

k=[i.strip() for i in open(0)]

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_

dataclass

from dataclasses import dataclass
@dataclass
class paper:
    lines: list
    numberOf_lines: int

. . .
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 ..."

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")

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

print("odd"if int(input())%2else"even")

from 58 char to 39
but we can do more

print("eovdedn"[int(input())%2::2])

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())

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())

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

25

This website collects cookies to deliver better user experience