One-line Python programs
From MathMoth
Revision as of 14:11, 11 May 2013 by Peterche (Talk) (Created page with "{{langs|en=One-line Python programs|ru=Однострочные программы на Питоне}} ==One-line Python programs== Sometimes, Python exercises require to sol...")
English Russian
One-line Python programs
Sometimes, Python exercises require to solve the problem in one line of code. Even if this is not required, one-line solution is fun to write. Besides, a short program doesn't leave too much space for bugs.
Factorial can be coded as
print((lambda foo, i: foo(foo, i))(lambda f, n: 1 if n == 0 else f(f, n-1)*n, int(input())))
Writing odd elements of the list.
print(*map(lambda a:a[1], filter(lambda x: x[0]%2==0, enumerate(input().split()))))
or
print(*input().split()[0::2])
Max element of the list and its index.
print(*reversed(max(enumerate(map(int,input().split())),key=lambda a:a[1])))
Insert a character between every pair of characters of a given string.
print(input().replace(,'*')[1 : -1])
or
print("*".join(tuple(input())))