HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Improving many for loops, any more efficient alternative?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
alternativeanyloopsmoreefficientformanyimproving

Problem

I'm working through an introduction to computer science book, this is not homework for me but me trying to learn in my spare time, I'm not asking for homework help!

The output is below, and this is all ok, but I'm just certain there is a more efficient way of doing this. I have been trying for many hours now and this is still the best solution I can come up with, if anyone can improve upon this and possibly explain how, I would highly appreciate it.

The code:

naught = 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0

for i in range (0, 10):
    print("")
    for i in range (0,1):
        print(naught, end = " ")
    for i in range (0,1):
        print(one, end = " ")
        one += 1
    for i in range (0,1):
        print(two, end = " ")
        two += 2
    for i in range (0,1):
        print(three, end = " ")
        three += 3
    for i in range (0,1):
        print(four, end = " ")
        four += 4
    for i in range (0,1):
        print(five, end = " ")
        five += 5
    for i in range (0,1):
        print(six, end = " ")
        six += 6
    for i in range (0,1):
        print(seven, end = " ")
        seven += 7
    for i in range (0,1):
        print(eight, end = " ")
        eight += 8
    for i in range (0,1):
        print(nine, end = " ")
        nine += 9


The output is below and that is all correct, that's no problem.

0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
0 5 10 15 20 25 30 35 40 45
0 6 12 18 24 30 36 42 48 54
0 7 14 21 28 35 42 49 56 63
0 8 16 24 32 40 48 56 64 72
0 9 18 27 36 45 54 63 72 81


As I said I'm getting the right answer, just I'm not satisfied that it's in the best way.
Many thanks,
Matt.

Solution

If you are just looking to generate that same output, simplify your problem a little:

for x in range(10):
  temp = ''

  for y in range(10):
    temp += str(x * y) + ' '

  print temp


Or if you want to get fancy:

for x in range(10):
  print ' '.join(str(x * y) for y in range(10))

Code Snippets

for x in range(10):
  temp = ''

  for y in range(10):
    temp += str(x * y) + ' '

  print temp
for x in range(10):
  print ' '.join(str(x * y) for y in range(10))

Context

StackExchange Code Review Q#7068, answer score: 4

Revisions (0)

No revisions yet.