Scene: Host to a commodity, the price in 99999, you say a price, support people will be compared to the actual price, to tell you is high, or low, how to use the least number of times to guess the price of the commodity.
Idea: Two-point search method
On the code:
#-*-coding:utf-8-*-#guess commodity price game-using dichotomy fastest premise: price within 999 yuan#actual price of goodsOldprice=0#user-guessed priceCaiprice=0#interval Lowest price--for calculating the best guess priceZuidi=0#Maximum price rangezuigao=99999Oldprice=int (Input ("Please enter the actual price of the product:")) Caiprice=int (Input ("Please enter the price you guessed:")) whileoldprice!=Caiprice:ifCaiprice>Oldprice:Print("High.") Print("based on your guess price, the best price strategy is:") Zuigao=CaipricePrint((Zuidi+zuigao)/2) Caiprice=int (Input ("Please enter the price you guessed:")) elifcaiprice<Oldprice:Print("it's low.") Print("based on your guess price, the best price strategy is:") Zuidi=CaipricePrint((Zuidi+zuigao)/2) Caiprice=int (Input ("Please enter the price you guessed:"))ifoldprice==Caiprice:Print("Congratulations, you guessed it.")
Actual results: The higher the actual price of the commodity, the more times it needs
Please enter the product actual price: 800 Please enter the price you guessed: 500 lower according to your guess price, the best price strategy is: 749.5 Please enter the price you guessed: 750 low based on your guess price, the best price strategy is: 874.5 Please enter your guess price: 874 high up according to your guess Price, The best price strategy is: 812.0 Please enter the price you guessed: 812 high up according to your guess price, the best price strategy is: 781.0 Please enter the price you guessed: 781 low based on your guess price, the best price strategy is: 796.5 Please enter the price you guessed: 796 lower based on your guess Price, The best price strategy is: 804.0 Please enter your guess price: 804 high up according to your guess price, the best price strategy is: 800.0 Please enter the price you guessed: 800 Congratulations, you guessed it.
Algorithm--guessing the price of a commodity