Zack Gao
Zack Gao

Reputation: 568

Differences between the following python and ruby code

I was trying to solve the following problem: https://www.codeeval.com/open_challenges/23/

This was my solution in Python, which didn't pass:

for x in range(1,13):
    string = ''
    for y in range(1,13):
        string += ' '*(4-len(str(x*y))) + str(x*y)
    print string.strip()

This was my friend's solution in Ruby, which did pass:

for i in 1..12
  line = ""
  for j in 1..12
    line += " " * (4 - (j * i).to_s.length) + "#{j * i}"
  end
  puts line.strip
end

To me, the two snippets look like they do the same thing and they output the same thing based on my testing. Do you think there is a reason my solution isn't being accepted other than issues with the evaluation system?

Upvotes: 0

Views: 63

Answers (2)

tadman
tadman

Reputation: 211710

Answer in Ruby for comparison:

(1..12).each do |i|
  puts((1..12).collect do |j|
    '%4d' % (i * j)
  end.join(' '))
end

The '%4d' makes use of sprintf-style formatting to properly pad without needing to test lengths.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124548

I'd use:

for x in range(1, 13):
    print ''.join([format(x * y, '2d' if y == 1 else '4d') 
                   for y in range(1, 13)])

This formats the left-most column to hold at most 2 characters (1 through to 12), 4 characters otherwise, right-aligned.

Your version removes too much whitespace from the start of the lines; the last 3 lines need space for 2 digits in the left-most column.

Upvotes: 2

Related Questions