I saw this problem posted as an interview question asked at Bloomberg:
Given an integer N, print numbers from 1 to N in lexicographic order. Restriction. One cannot use strings or characters.
Below is my solution to this problem. Can the algorithm be improved?
#!/usr/bin/env python
import sys
import traceback
def printlexnum(i, tens, number):
lexnum = i*tens
for j in range(lexnum,min(number+1,lexnum+tens)):
print j
if number>=lexnum:
printlexnum(i, tens*10, number)
return
try:
if len(sys.argv) < 2:
number = 0
while number < 0:
number = int(raw_input('please enter number >0: '))
if number == 0:
sys.exit(1)
else:
number = int(sys.argv[1])
if number <= 0:
print "Bad argument." + number + " must be greater than zero."
sys.exit(1)
for i in range(1,min(10,number+1)):
print i
printlexnum(i,10, number)
except ValueError, e:
traceback.print_exc()
print sys.argv[1], " Input not an integer"
except Exception, e:
traceback.print_exc()
print sys.argv[1], " Exception thrown"
finally:
a = 1 # dummy line