Use sortedset.range(), remove at()
Replace manually counts with sum()