码迷,mamicode.com
首页 > 其他好文 > 详细

菜鸡日记6

时间:2017-08-01 21:45:01      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:guess   ret   穷举   not   between   sam   ring   statement   程序   

好久都没有写过了。。。

1.二分查找法的强大,不用多说。比穷举法不知道高到哪里去了!以下是一个二分法求平方根的例子

x=int(input(‘Enter a number which you like:‘))
precision=0.01
numguess=0
low=0
high=x
ans=(low+high)/2
while abs(ans**2-x)>=precision:
  print(‘low=‘+str(low)+‘,‘+‘high=‘+str(high)+‘,‘+‘ans=‘+str(ans))
  numguess+=1
  if (ans**2)>x:
    high=ans
    ans=(low+high)/2
  else:
    low=ans
    ans=(low+high)/2
print(‘ans=‘+str(ans))
print(‘numguess=‘+str(numguess))

 

2.

# Notice how if we have two print statements                
print "Hi"
print "there"

# The output will have each string on a separate line:                
Hi
there
                
# Now try ading a comma after the print statement:
print "Hi",
print "there"
                
# The output will place the subsequent string on the same line:
Hi there
           
3.猜数字游戏,使用者输入一个0到100间的整数,程序使用二分法进行猜测(我写的有点low,好在实现了。。。。)

x=int(input(‘Enter a number between 0 and 100:‘))
low=0
high=100
guess=(low+high)/2
numguess=0
print(‘Is your secret number ‘+str(guess)+‘?‘)
judge=str(input(‘Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.‘))
while judge!=‘c‘:
  numguess+=1
  if judge==‘l‘:
    low=guess
    guess=int((low+high)/2)
    print(‘Is your secret number ‘+str(guess)+‘?‘)
    judge=str(input(‘Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.‘))
  else:
    high=guess
    guess=int((low+high)/2)
    print(‘Is your secret number ‘+str(guess)+‘?‘)
    judge=str(input(‘Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly.‘))
print(‘numguess=‘+str(numguess))
print(‘Game over. Your secret number was: ‘+str(guess))

菜鸡日记6

标签:guess   ret   穷举   not   between   sam   ring   statement   程序   

原文地址:http://www.cnblogs.com/zeke-lizhe/p/7270682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!