Your function is a version of bijective numeration. In particular, your $f(n)$ is the ($n+1$)th word in the shortlex ordering of all words on the given alphabet. (The $n+1$ is due to your omission of the empty word.) Here's an implementation (in Sage), which is essentially the algorithm given on the page at the first link above, adapted to use an arbitrary $k$-character alphabet rather than the usual digits {1, 2, ..., $k$}:
def number_to_word(n, alphabet): """ return the nth word (n >= 0) in the shortlex ordering of words on the given alphabet string """ k = len(alphabet) word = '' while n != 0: q = ceil(n/k) - 1 a = n - q*k word = alphabet[a-1] + word n = q return word
Here's an implementation of the inverse of that function:
def word_to_number(w, alphabet): """ return the number n such that w is the nth word in the shortlex ordering of words on the given alphabet string """ k = len(alphabet) n = q = 0 for c in w[::-1]: p = alphabet.index(c) + 1 n = n + p*(k^q) q = q + 1 return n
For example
for n in [0..15]: s = number_to_word(n+1,'abc') t = word_to_number(s,'abc')-1 print '%d --> %s --> %d'%(n,s,t)
produces
0 --> a --> 0 1 --> b --> 1 2 --> c --> 2 3 --> aa --> 3 4 --> ab --> 4 5 --> ac --> 5 6 --> ba --> 6 7 --> bb --> 7 8 --> bc --> 8 9 --> ca --> 9 10 --> cb --> 10 11 --> cc --> 11 12 --> aaa --> 12 13 --> aab --> 13 14 --> aac --> 14 15 --> aba --> 15