Difference between revisions of "One-line Python programs"

From MathMoth
Jump to: navigation, search
(using pre tags instead to dodge wiki markup)
 
Line 7: Line 7:
  
 
A factorial can be coded as  
 
A 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())))
+
<pre>print((lambda foo, i: foo(foo, i))(lambda f, n: 1 if n == 0 else f(f, n-1)*n, int(input())))</pre>
  
 
Printing the odd elements of a list.
 
Printing the odd elements of a list.
  print(*map(lambda a:a[1], filter(lambda x: x[0]%2==0, enumerate(input().split()))))
+
<pre>print(*map(lambda a:a[1], filter(lambda x: x[0]%2==0, enumerate(input().split()))))</pre>
 
or
 
or
  print(*input().split()[0::2])
+
<pre>print(*input().split()[0::2])</pre>
  
 
The maximum element of the list and its index.
 
The maximum element of the list and its index.
  print(*reversed(max(enumerate(map(int,input().split())),key=lambda a:a[1])))
+
<pre>print(*reversed(max(enumerate(map(int,input().split())),key=lambda a:a[1])))</pre>
  
 
Inserting a character between every pair of characters in a given string.  
 
Inserting a character between every pair of characters in a given string.  
  print(input().replace('','*')[1 : -1])
+
<pre>print(input().replace('','*')[1 : -1])</pre>
 
or
 
or
  print("*".join(tuple(input())))
+
<pre>print("*".join(tuple(input())))</pre>

Latest revision as of 20:35, 3 August 2017

English Russian

One-line Python programs

Sometimes, Python exercises require solving the problem in one line of code. Even if this is not required, one-line solutions are fun to write. Besides, a short program doesn't leave too much space for bugs.

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

Printing the odd elements of a list.

print(*map(lambda a:a[1], filter(lambda x: x[0]%2==0, enumerate(input().split()))))

or

print(*input().split()[0::2])

The maximum element of the list and its index.

print(*reversed(max(enumerate(map(int,input().split())),key=lambda a:a[1])))

Inserting a character between every pair of characters in a given string.

print(input().replace('','*')[1 : -1])

or

print("*".join(tuple(input())))