0

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?

5
  • don't call a string string and use string formatting to align stuff Commented Feb 24, 2014 at 16:52
  • The output is exactly the same.. Commented Feb 24, 2014 at 16:53
  • I don't know Ruby, but may be because better way of writing code in Python is something like that @Martijn's answered Commented Feb 24, 2014 at 16:57
  • 1
    for i in 1..12 is almost always better written as 12.times do |i| or (1..12).each do |i| as it's extremely unusual to see for used in Ruby code. Commented Feb 24, 2014 at 16:57
  • Btw, Who submitted first? you or your friend? Commented Feb 24, 2014 at 16:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But so does the ruby version, which was apparently accepted.
@wim: I don't know enough Ruby to judge that, but it could be that there is a bug in the challenge checker for Ruby.
@wim: another option is that the friend is pulling OPs leg and hasn't yet passed the challenge.
No I tried to submit the Ruby solution and it did pass. Thank you for the suggested approach though. It worked.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.