better solution to problem7