python 3.7 搓螺旋丸

 

'''
搓螺旋丸,先从最外围填数,一圈隔一圈往内填
假设左基准点位置,r_base,c_base   row col
'''
import numpy as np

def spiralize(number):
    
    cur_len = number
    r_base = 0
    c_base = 0
    map_arr = np.full((number,number),0)
    
    times = number//2
    print(times)
      
    try:    
        while times:
            
            #先赋值最外围的3边
            for i in range(3):
                temp_arr = map_arr[r_base : r_base+cur_len, c_base : c_base+cur_len]
                
                if number%2 == 0 and cur_len <= 3 and r_base+cur_len < number and c_base+cur_len < number :
                    if temp_arr[cur_len-1,cur_len-1] == 1:
                        #temp_arr[cur_len-1,cur_len-1] = 3
                        map_arr = np.rot90(map_arr,-i)
                        return print('====\n',map_arr)
                if(number == 2 and i == 2):
                    map_arr = np.rot90(map_arr,-i)
                    return print('====\n',map_arr)
                
                temp_arr[0] = [1 for i in range(len(temp_arr[0]))]
                map_arr = np.rot90(map_arr)
                
            temp_arr = map_arr[r_base : r_base+1 , c_base : c_base + cur_len - 2]
            temp_arr[0] = [1 for i in range(len(temp_arr[0]))]

            map_arr = np.rot90(map_arr,-3)
            r_base += 2
            c_base += 2
            cur_len -= 4
            if r_base+1 <number and map_arr[r_base+1,c_base-1] != 1:
                map_arr[r_base,c_base-1] = '1'
            times -= 1
    except IndexError:
        return print('最终 map_arr = \n',map_arr)
    
spiralize(20)

相关文章: