Better way of doing problem 6