On Sat, Feb 20, 2021 at 7:13 PM Ming <m...@pgp.cool> wrote:

> I just wrote a very short code can fulfill your needs:
>
> a = 2342
> b = int("".join(map(lambda x: str((int(x)-3)%10) ,list(str(a)))))
>
I tend to favor plenty of temporary variables with descriptive names, but
this is indeed short.

Apart from that, you may find that using a generator expression is shorter
and clearer than map+lambda.  It should allow to additionally eliminate the
list conversion.

So in the terse form you've got there, it'd be more like:
b =  int(''.join(str((int(x) - 3) % 10) for x in str(a))

But in real life, I'd try to use descriptive variable names for some of the
subexpressions in that.  This makes reading and debugging simpler, which is
important because the maintenance phase of software is almost always much
longer and costly than the development phase.  And although you could do a
generator expression for each of the different parts of (int(x) - 3) % 10,
I kinda like having a named function for just that piece.

So maybe:
  def rot_3(character):
      """Convert to int, subtract 3 and mod 10."""
      digit = int(character)
      assert 0 <= digit <= 9
      return (digit - 3) % 10


  def descriptive_minus_three_caesar(input_number):
      """Convert to a -3 caesar cypher on an integer."""
      string_number = str(input_number)
      rotated_digits = (rot_3(character) for character in string_number)
      output_string = ''.join(str(digit) for digit in rotated_digits)
      output_number = int(output_string)
      return output_number
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to