Skip to main content
5 of 13
added 2098 characters in body
xnor
  • 146.6k
  • 3
  • 93
  • 131

Python

Submissions are either programs or functions. They should print or return the output. These examples compute the factorial of a positive integer.

General I/O

# Program that prints
n=input();p=1
for i in range(1,n+1):p*=i
print p

# Defined function that outputs or prints
def f(n):
 p=1
 for i in range(1,n+1):p*=i
 print p

# Lambda function, no name needed
lambda n:reduce(int.__mul__,range(1,n+1))

# Lambda function, named to use recursive call
f=lambda n:1 if n==0 else n*f(n-1)

Your may not expect input in a pre-assigned variable.

# Invalid, expects input in n
p=1
for i in range(1,n+1):p*=i
print p

Nor may you output just by saving the result to a variable.

# Invalid, saves result to p
n=input();p=1
for i in range(1,n+1):p*=i

Nor can the result just be the value of an expression like in the interactive shell.

Inputs

We're pretty free about input formats. For example, if a challenge says to take a list of numbers, you can assume it will be in a Python list like l=[1,2,3], not like "1 2 3". So, a Python 2 program can do

l=input()

rather than

l=map(int,raw_input().split())

Likewise, when a program takes string input, you can assume it's given in quotes and use input() for Python 2 rather than raw_input().

Version

Use Python 2 or Python 3 as you prefer. If the version matters, say it in the header.

Libaries

You may import standard libraries. Just include the import statement in the code. You may also import non-standard ones like scipy, but then call the language "Python with scipy" in the header.

Truthy/Falsey

Some challenges ask for a Truthy or Falsey output. In Python, Truthy values are those where bool(x)==True. That is, everything but False, 0, None, and empty collections, which are all Falsey.

More on functions

A function submission may have additional helper code outside the function definition, for example

import re;r=range
lambda l: ...

Functions may use extra optional arguments. For example, this factorial function expects a single number, but uses the optional input i to help recurse:

f=lambda n,i=1:1 if i>n else i*f(n,i+1)

You may not however expect the user to call the function with a specific additional argument, i.e. like

# You may not say "call this with 2nd argument 1" 
f=lambda n,i:1 if i>n else i*f(n,i+1)
xnor
  • 146.6k
  • 3
  • 93
  • 131