solve p7.py(this algorithm is not efficient)