写穿墙缝隙,穿墙最少时遇到的array与list的转化问题

题目为:

解题思想:

   就是组成新数组:新数组每一列都是原数组对应列及其前面列之和.[1,2,3]--->[1,3,6]

   每一列就是墙缝,每一列重复的数字越多,穿的墙数越少!

代码:

import numpy as np
b = np.zeros(shape= (1,5),dtype = int)
np = np.random.randint(1,10,size=(5,5))
for i in np.T:
    b +=i
    m = len(set(list(b.reshape(-1))))-1  ##在这里出现了问题,因为b是array,必须reshape(-1)一下才可以,原因看下面的代码!
    print(m)
#输入:
import numpy as np
x= np.random.randint(1,5,size= (1,5),dtype = int)
x


#输出:
array([[1, 3, 1, 3, 1]])
#输入:
list(x)

#输出:

[array([1, 3, 1, 3, 1])]


#输入:

x.reshape(-1)

#输出:

array([1, 3, 1, 3, 1])

#输入:
list(x.reshape(-1)) ##单行数组必须reshape一下,才可以list(),得到常规列表!

#输出:

[1, 3, 1, 3, 1]

#因此才能有应集合去重:
#输入:
set(list(x.reshape(-1)))

#输出:{1, 3}

 题目的算法:感觉很low

lst = [[1,2,2,1],[3,1,2],[1,3,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
m = len(lst)
lt = []
for i in lst:
    n=0
    for j in i[:-1]:
       n+=j
       lt.append(n)
lt1=[]
for i in lt:
   lt1.append(lt.count(i))
y=m-max(lt1)
print(y)
    
原文地址:https://www.cnblogs.com/kevin-red-heart/p/11311617.html