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.

Recommended Answers

Hm, try this

outstr = "\n".join("\t".join(str(i*j) for j in range(1, 13)) for i in range(1, 13))
print outstr
Jump to Post

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

Jump to Post

.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))
Jump to Post

All 9 Replies

Hm, try this

outstr = "\n".join("\t".join(str(i*j) for j in range(1, 13)) for i in range(1, 13))
print outstr
commented: wow +15

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

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.

Alright I'll keep that in mind, thx

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

Sneekula, I don't really follow what the "5d" means. I think I understand it otherwise...

Actually I'm an idiot, I see what you're getting at Sneekula.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.