【筆試題】:0.“沒事兒走兩步”問題
阿新 • • 發佈:2018-12-02
問題:
小明在單位為1的尺子上向目標點走,每次只能向前或向後走,第一次走1步,第二次走2步,第n次走n步,請問小明走到正前方x步最短需要走幾次?
輸入:x
1
2
3
4
輸出:n
1
3
2
4
答案:
1.程式碼:
https://github.com/JackKuo666/csdn/blob/master/Algorithm_written_test/zoubuti.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ def is_x(x): n = 0 i = 0 while n < x: i += 1 n = n + i if n == x: print ('need zhe me duo ci:'+str(i)) for j in range(i): print ('+' + str(j+1),end='') print ('=' + str(x)) elif (n - x) % 2 ==0: print ('need zhe me duo ci:'+str(i)) for j in range(i): if (n-x) / 2 == j+1: print ('-' ,end ='') else: print ('+',end ='') print (str(j+1),end ='') print ('=' + str(x)) elif (i + 1) % 2 == 0: print ('need zhe me duo ci:'+str(i+2)) for j in range(i+2): if (n-x - 1) / 2 == j+1: print ('-',end ='') elif j+1 == i+1: print ('+',end ='') elif j+1 == i+2: print ('-',end ='') else: print ('+',end ='') print (str(j+1),end ='') print ('=' + str(x)) elif (i + 1) % 2 != 0: print ('need zhe me duo ci:'+str(i+1)) for j in range(i+1): if (n-x + i+1 ) / 2 == j+1: print ('-',end ='') else: print ('+',end ='') print (str(j+1),end ='') print ('=' + str(x)) x = 7 x_in = input('please enter your x: ') print ('your x is :',x_in) x = int(x_in) while x_in != 'q': is_x(x) x_in = input('please enter your x: ') print ('your x is :',x_in) x = int(x_in)
2.解析:
設小明向前走x步時最少走m次,則m為:
設小明向前走到第i次時
且
其實上邊的公式時秦老師結出來,讓我們通過一些例子理解一下公式:
我們以表格的形式寫出來:(第一列是x,表示小明離目標多少步,第二列m,表示小明需要走多少次,每次前邊“±”號表示向前或向後)
x | 第一步:確定i | 第二步:(1+…+i)-x 奇/偶 | i+1 奇/偶 | 第三步:操作 | 展開 | m |
---|---|---|---|---|---|---|
1 | 1 | (+1)-1=0 偶 | - | 0/2=0,符號不變,加到i | +1 | 1 |
2 | 2 | (+1+2)-2=1 奇 | 3 奇 | (1+3)/2=2,2前邊添“-”;且加到i+1 | +1-2+3 | 3 |
3 | 2 | (+1+2)-3=0 偶 | - | 0/2=0,符號不變,加到i | +1+2 | 2 |
4 | 3 | (+1+2+3)-4=2 偶 | - | 2/2=1,1前邊添“-”,加到i | -1+2+3 | 3 |
5 | 3 | (+1+2+3)-5=1 奇 | 4 偶 | (1+4+5)/2=5,5前邊添“-”;且加到i+2 | +1+2+3+4-5 | 5 |
6 | 3 | (+1+2+3)-6=0 偶 | - | 0/2=0,符號不變,加到i | +1+2+3 | 3 |
7 | 4 | (+1+2+3+4)-7=3 奇 | 5 奇 | (3+5)/2=4,4前邊添“-”;且加到i+1 | +1+2+3-4+5 | 5 |
8 | 4 | (+1+2+3+4)-8=2 偶 | - | 2/2=1,1前邊添“-”,加到i | -1+2+3+4 | 4 |
9 | 4 | (+1+2+3+4)-9=1 奇 | 5 奇 | (1+5)/2=3,3前邊添“-”;且加到i+1 | +1+2-3+4+5 | 5 |
10 | 4 | (+1+2+3+4)-10=0 偶 | - | 0/2=0,符號不變,加到i | +1+2+3+4 | 4 |
11 | 5 | (+1+2+3+4+5)-11=4 偶 | - | 4/2=2,2前邊添“-”,加到i | +1-2+3+4+5 | 5 |
注:吳老師提供題目,秦老師提供解題思路,小郭敲程式碼,一次愉快的合作。