Rachit Ajitsaria - 1 year ago 52

Python Question

I am converting letters in a string to their corresponding numbers and printing YES if the result is divisible by 6 or NO. For eg, ab is 12 and will give YES. The program is working fine for small strings but gives wrong answer for very long inputs. I tried to change the datatype for integers to long but nothing changed.

The test case for which it did not work: here#1 here#2

Edit: Input restrictions allow only lowercase characters 'a' to 'i'

`str = raw_input()`

n = len(str)

value = 0L

str = str[::-1]

for i in arange(n):

value = value*1L + (10L**i)*(ord(str[i])-96)

if value%6 == 0:

print "YES"

else:

print "NO"

Answer Source

The problem with the code appeared to be that the long int is possibly not long enough to hold the integer value of the string, decoded as given.

So, the problem can be simplified by applying the mathematical rules of divisibility.

Check if the corresponding digit for the last letter of the string is even. If not print 'NO' and exit.

Then check for the divisibility by 3, using the sum divisibility property.

Here's the code.

```
#Title: String decoding and divisibility by 6
#Author: Rtg
#Date: 29-05-16
str = raw_input()
n = len(str)
if (ord(str[n-1])-96)%2:
print "NO"
raise SystemExit
value = 0
for i in xrange(n):
value = value + ord(str[i])-96
if value%3 == 0:
print "YES"
else:
print "NO"
```