Is there a way to subtract 3 from every digit of a number?

Dan Stromberg drsalists at gmail.com
Sat Feb 20 23:49:15 EST 2021


On Sat, Feb 20, 2021 at 7:13 PM Ming <ming at 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


More information about the Python-list mailing list