fork(9) download
  1. #http://p...content-available-to-author-only...e.com/q/268022/51441
  2.  
  3.  
  4. # s:
  5. # input digit string that should be checked
  6. # L:
  7. # the start of the substring that should be investigated
  8. # L:
  9. # the end of the substring that should be investigated
  10. # cnt:
  11. # number of 3divisble substrings found so far
  12. # ss0:
  13. # number of substrings that end at the current position
  14. # and are divisible by 3
  15. # ss1:
  16. # number of substrings that end at the current position
  17. # and have the remainder 1 when divided by 3
  18. # ss2:
  19. # number of substrings that end at the current position
  20. # and have the remainder 2 when divided by 3
  21.  
  22.  
  23. def ss(s,L,R):
  24. cnt=0
  25. (ss0,ss1,ss2)=(0,0,0)
  26. for i in range(L,R+1):
  27. r=int(s[i])%3
  28. if r==0:
  29. ss0+=1
  30. elif r==1:
  31. (ss0,ss1,ss2)=(ss2,ss0,ss1)
  32. ss1+=1
  33. elif r==2:
  34. (ss0,ss1,ss2)=(ss1,ss2,ss0)
  35. ss2+=1
  36. cnt+=ss0
  37. return(cnt)
  38.  
  39. print(ss('392301',0,len('392301')-1))
  40. print(ss('2035498',2,5))
  41.  
Success #stdin #stdout 0.01s 7736KB
stdin
Standard input is empty
stdout
9
6