1-liners Python + Ruby


  • 2

    Ruby:

    def find_the_difference(s, t)
      (s + t).bytes.reduce(:^).chr
    end
    

    (previously I had unpack("c*") instead of bytes, thanks @hbin)

    Python:

    def findTheDifference(self, s, t):
        return chr(sum(map(ord, t)) - sum(map(ord, s)))
    
    def findTheDifference(self, s, t):
        return chr(reduce(int.__xor__, map(ord, s+t)))

  • 1
    H

    For the ruby version, (s + t).bytes.reduce(&:^).chr may be more clear and easier to understand.


  • 0

    @hbin Ah, yes, bytes is much nicer but I didn't know it (I'm really a Ruby noob). Thanks. Why did you add the &, though?


  • 1
    H

    @StefanPochmann Good question! This SO question gave a more precise answer: http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby

    And I also took a benchmark between with or without the & sign:

    require 'benchmark/ips'
    
    STR1 = 'aabbccddeeffgg'.freeze
    STR2 = 'aabbccddeeffggh'.freeze
    
    Benchmark.ips do |x|
      x.report 'reduce(&:^)' do
        (STR1 + STR2).bytes.reduce(&:^)
      end
    
      x.report 'reduce(:^)' do
        (STR1 + STR2).bytes.reduce(:^)
      end
    
      x.compare!
    end
    

    Here is the result

    Warming up --------------------------------------
    reduce(&:^) 18.746k i/100ms
    reduce(:^) 21.560k i/100ms
    Calculating -------------------------------------
    reduce(&:^) 217.850k (± 5.6%) i/s - 1.087M in 5.006533s
    reduce(:^) 257.857k (± 7.0%) i/s - 1.294M in 5.043450s

    Comparison:
    reduce(:^): 257857.1 i/s
    reduce(&:^): 217849.8 i/s - 1.18x slower


  • 0

    @hbin I ran your benchmark a few times as well and got similar results, factor about 1.20. When precomputing S = (STR1 + STR2).bytes to focus on the reduce, the factor became about 1.28.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.