2013-11-23 71 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)))