2013-11-23 70 views
0
陣列

剛剛在任何類型的編程和Python的起步是我入類是教學語言。麻煩與串聯的4個二進制整數

我的老師中有一個遊戲,她扮演稱爲二進制骰子,它只是4模具(代表一個半字節),每個模具有3個邊(0)和3個邊(1),你應該安排模具以便獲得最大可能值,然後將該值轉換爲十六進制數字。

那麼我試圖寫入到py程序,所以它產生4個二進制數字,用戶排序,檢查它,然後有用戶輸入十六進制值,檢查它對自己的二進制到十六進制翻譯,使用連接的半字節作爲一個4位數值。

繼承人什麼我走到這一步......排序數字數組

在級聯例如後(同樣,只被編程的幾個星期)

#Binary Dice Program 

#individual integers generated randomly 
print ("This Game Simulates Binary Dice,") 
print ("Your objective is to sort the 4 given") 
print ("binary numbers so they make the highest") 
print ("possible hexadecimal value...") 
auth = input("When you are ready, hit Enter to continue...") 
print (" ") 

#generation and display of given ints 
import random 
die0 = random.randint (0, 1) 
die1 = random.randint (0, 1) 
die2 = random.randint (0, 1) 
die3 = random.randint (0, 1) 
dieArray=[die0, die1, die2, die3] 
print ("Your die are showing as ") 
print (dieArray) 

#sort array from highest to lowest 
def get_data(): 
     return dieArray 
nib=get_data() 
nib.sort(reverse=True) 

for num in nib: 
    print .join((str(num))) #I think Im doing this completely wrong 

#Once we get a concatenated 4 digit binary nibble, 
#I want to be able to translate that nibble into a hex value 
#that is used to check against the user's input 

,如果我得到一個[0,1,1,0]的數組我希望它排序並連接以顯示爲一個新值,「1100」

+0

得到十六進制值:'hex(int(「1100」,2))' – jfs

+0

@ J.F.Sebastian,只需將它替換爲'hex(int([name],2))''? – user3025862

回答

0

行例如,如果我得到的[0,1,1,0]我希望它進行排序和concatentate以展會爲新值的數組,「1100」

L = [0,1,1,0] 
print("1"*L.count(1) + "0"*L.count(0)) # O(n) 

或者

L = [0,1,1,0] 
print("".join(map(str, sorted(L, reverse=True)))) # O(n*log n) 

您可以同時滾動所有二進制骰子:

roll_n_dices = lambda n: random.getrandbits(n) 
r = roll_n_dices(4) 
binstr = bin(r)[2:].zfill(4) 
sorted_binstr = "1"*binstr.count("1") + "0"*binstr.count("0") 
hex_value = hex(int(sorted_binstr, 2)) 
2

您正在嘗試排序並加入列表。我會用代碼

''.join(map(str, sorted(nib, reverse = True)))