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

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Sat Feb 20 09:59:08 EST 2021


On 2021-02-20 at 09:40:48 -0500,
C W <tmrsg11 at gmail.com> wrote:

> Hello everyone,
> 
> I'm curious if there is a way take number and back each digit by 3 ?
> 
> 2342 becomes 9019
> 8475 becomes 5142
> 5873 becomes 2540
> 
> The tricky part is that 2 becomes 9, not -1.
> 
> Here's my toy example and what I attempted,
> > test_series = pd.Series(list(['2342', '8475', '5873']))
> > test_series
> 0    2342
> 1    8475
> 2    5873
> dtype: object
> 
> > test_series.str.split('')
> [, 2, 3, 4, 2, ]
> [, 8, 4, 7, 5, ]
> [, 5, 8, 7, 3, ]
> dtype: object
> 
> What a good approach to this? Is there a method or function that should be
> handling this?

I'm assuming that this is homework or some other academic exercise, so
I'm being deliberately vague on some of the details.  That said:

Break it down.

(1) Write a function that takes a number and returns the result of
subtracting three from it.  This function should also handle the
"special" cases of 0, 1, and 2.  Look up the modulo operator for a
better way than actually special-casing them.

(2) Python has several ways of building a list by transforming the
elements of a list one at a time and building a new list from the
results.  Consider a simple iterative approach, but also look up the
builtin "map" function and "list comprehensions."

One interesting decision is where to convert the individual digits of
the original numbers from strings to integers.  There are arguments for
doing it in either of the parts I've just outlined, as well as making it
a sort of Part 1a and applying both Part 1 and Part 1a to each digit.

> Thanks so much!

HTH,
Dan


More information about the Python-list mailing list