Hey guys,

In prepping for a job interview, I'm trying to eliminate some bad habits and this trivial problem has me realizing how hard that is :'(.

The problem:

Print a 12 x 12 multiplication table. This is easy....

outstring=''
for i in range(1,13):
	for j in range(1,13):
		outstring +='\t'+str(i*j)  #+= is add new value
	print '\n', outstring
	outstring=''

Resulting in
1 2 3 4 5 6 7 8...
2 4 6 8 10 12 14 16... etc

Ok no biggy, but what I want to do now is to get rid of my sloppy outstring method and use .join(). I also would like to do the iterator in one go. Here's the closet I can get.

outlist=[str(i*j) for i in range(1,13) for j in range(1,13)]
s="".join(outlist)
print s

This works sort of, but now I don't know how to get the nice tab-delimited output. Any ideas of how to modify this so it uses these premises but outputs data like the original method?

Thanks.

Our friend Gribouillis has a masterful solution. Let's just hope nobody at the job interview asks you to explain how it works.

.join() is more efficient than string concatenation, so I would expect to see at least one join(). Also, don't use "i", "l", or "O" in an interview.

for outer in range(1,13):
    print '\t'.join(str(outer*inner) for inner in range(1, 13))

Edited 4 Years Ago by woooee: n/a

Thanks for both of these good solutions guys.

Also, woooee, why is using "i", 'I' and "O" bad?

Thanks for both of these good solutions guys.

Also, woooee, why is using "i", 'I' and "O" bad?

They can look like numbers and you are interviewing, usually, with someone who is interested in code that can be easily maintained, so they don;t want anything that can be confusing. In fact single letter variables are not a good idea at any time. You should use something more descriptive, outer and inner, or row and col, etc.

You can also use Python's built-in % format specifiers:

for outer in range(1,13):
    print '\t'.join("%5d"%(outer*inner) for inner in range(1, 13))
This question has already been answered. Start a new discussion instead.