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

dn PythonList at DancesWithMice.info
Sat Feb 20 17:51:32 EST 2021


On 21/02/2021 06.02, jak wrote:
> Il 20/02/2021 15:40, C W ha scritto:
>> 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?
>>
>> Thanks so much!
>>
>> Mike
>>
> 
>>>> num='0123456789'
>>>> n=8475
>>>> sn = ''
>>>> for x in str(n):
>     sn += num[(int(x) - 3) % 10]
> 
>     
>>>> int(sn)
> 5142
>>>>


This code doesn't *look* correct (in the original post, via email
reflector) because the loop is not indented


Per previous respondents identifying it as likely to be an 'homework
assignment', does it help the student if you/me/we "give" the answer?
How has the student proven that (s)he has learned the material?
(apologies for criticism: I readily assume your motivation was to be
helpful)


The problem is a Caesar Cipher - disguised, because most examples/usage
of such is for alphanumeric messages. This topic is often used for ComSc
examples to demonstrate modulo arithmetic and/or circular data
structures, eg a bounded-queue (per other's responses).
-- 
Regards,
=dn


More information about the Python-list mailing list