1. 程式人生 > >python學習例項(2)

python學習例項(2)

#===================================
#2.2 不同進位制間的轉換
#===================================


#+++++++++++++++++++++++++++++++++++
#2.2.1.	二進位制數轉換為十進位制數
#+++++++++++++++++++++++++++++++++++

#<程式:2-to-10進位制轉換>
b=input("Please enter a binary number:")
d=0; 
for i in range(0,len(b)):
    if b[i] == '1':
        weight = 2**(len(b)-i-1)
        d = d+weight;
print(d)



#<程式:改進後的2-to-10進位制轉換>
b=input("Please enter a binary number:")
d=0; weight=2**(len(b)-1);
for i in range(0,len(b)):
    if b[i] == '1':
        d = d+weight;
    weight=weight//2;       #‘//’是整數除法
print(d)




#+++++++++++++++++++++++++++++++++++
#2.2.2. 十進位制數轉換為二進位制數
#+++++++++++++++++++++++++++++++++++

#<程式:整數的10-to-2進位制轉換>
x= int(input("Please enter a decimal number:"))
r = 0;
Rs = [];
while(x != 0):
    r = x% 2
    x = x//2
    Rs = [r]+Rs
for i in range(0,len(Rs)):   
#從最高位到最低位依次輸出;Rs[0]存的是最高位, Rs[len(Rs)-1]存的是最低位。
    print(Rs[i],end='')



#<程式:整數的10-to-2進位制轉換-遞迴>
def convert(x):		 #把10進位制數x轉換為2進位制數,並返回結果列表。
    if x<2: return([x])     #x=0 或 1,所以返回x
    r= x%2; 			#r 是2除x的餘數
    return(convert(x//2)+[r])   # 結果=[x//2的二進位制,r]

num = int(input("Please enter a decimal number:"))
Rs= convert(num)
for i in range(0, len(Rs)):
    print (Rs[i],end='')


#=====================================================================================
    


#===================================
#2.4. 一切都是邏輯(Logic)
#===================================

#+++++++++++++++++++++++++++++++++++
#2.4.3. 用邏輯做加法
#+++++++++++++++++++++++++++++++++++


#<程式: 全加器>
def FA(a,b,c):  # Full adder
     Carry = (a and b) or (b and c) or (a and c)
     Sum = (a and b and c) or (a and (not b) and (not c)) \
           or ((not a) and b and (not c)) or ((not a) and (not b) and c)
     return Carry, Sum



#<程式:完整的加法器 Carry Ripple adder>
def  add(x,y): # x, y are lists of True or False, c is True or False
                # return carry and a list of x+y
    while len(x) < len(y): x = [False]+x    #前面補0
    while len(y) < len(x): y = [False]+y	#前面補0
    L=[];Carry=False
    for i in range(len(x)-1,-1,-1):  #從最後一位一個個往前加
        Carry,Sum=FA(x[i],y[i],Carry)
        L=L+[Sum]
    return (Carry, L)



#<程式:乘法器>
def multiplier(x,y):    # 求x*y
     S=[];
     for i in range(len(y)-1,-1,-1):
         if y[i] == True:     	#y[i]是 1,要將x加進到S
             C, S=add(S,x)
             if C==True: S=[C]+S
         x=x+[False]			#每一次x都要向左移一位,後面補0
     return(S)