要求: 将给定的二进制转换为十进制
Input: data = [0, 0, 1, 1]
Output: 3
Clever:
def binary_array_to_number(arr):
return int("".join(map(str,arr)),2)
# map(str ,arr) 把数组中的元素全部转化为str类型
-
Some pionts:
-
map()函数
map() 会根据提供的函数对指定序列做映射。
map(lambda x,y:x+y,[1,3,5,7,9],[2,4,6,8,10]) #返回为 新的list
-
int(x,[base])
将x转换为整数。如果x是字符串,则要base指定基数。
-
join连接字符串数组
-
def binary_array_to_number(arr):
s = 0
for digit in arr:
s = s * 2 + digit
return s
Let’s say we have some input “so far” such as [a2, a1, a0]. We’ve calculated N2 = a2 * 2^2 + a1 * 2^1 + a0 * 2^0. Now we add another digit (let’s call it b) to the right side of the array. Now we need N3 = a2 * 2^3 + a1 * 2^2 + a0 * 2^1 + b * 2^0. In other words, when we had a2 before, we thought it was the 3rd place, but it turns out it’s the 4th place. a3 before was the 2nd place but it turns out it’s the 3rd. Does that mean we have to recalculate everything with new place values? Well, no. If we look at the relationship between N2 and N3, we see that every “digit” in N2 got multiplied by 2 (and then we added b). In other words N3 = N2 * 2 + b.