The key observation for this problem is that any number is divisible by 8 if its last three digits are divisible by 8. Once you convince yourself of this, the problem boils down to looping through all the three-digit permutations of the (substrings of the) number.
itertools is a handy library for efficient iterator-based tools which can help you avoid having to write out the permutation loops yourself.
If you haven’t already, make yourself aware of the other functions in itertools: combinations()
, combinations_with_replacement()
, product()
, as well as cycle()
, izip()
, etc.
Here is the reference solution:
import itertools
def solve(string):
for c in itertools.permutations(string, min(len(string), 3)):
if int(''.join(c)) % 8 == 0:
return 'YES'
return 'NO'
Note that wrapping permutations
inside of a list constructor entirely defeats the purpose of the itertools
library and is unnecessary! Don’t do that!