Python's idea of using iterators to print helical matrices and code examples _python

Source: Internet
Author: User

Ideas

A helical matrix is a spiral matrix whose number starts with the first line to the right, and the downward becomes larger,
The left is bigger, the upward is bigger, and so the loop goes.
The helical matrices are represented by two-dimensional arrays, coordinates (X,Y), i.e. (x-axis, y-coordinate).
The clockwise spiral direction is-> right, down, left, on, with a numerical value that is x plus 1 lattice (1,0), Y plus 1 lattice (0,1), X minus 1 lattice ( -1,0), y minus 1 lattice (0,-1).
The coordinates start at (0,0) and switch directions when out of range or when obstacles are encountered.
The printing of the spiral matrix first assigns a value to the N*n array, according to the law can be seen, each layer is in accordance with the right-> under the-> left-> on the order to increase, so as long as the first number of each layer can be found, the first number is the first digit of the previous layer +4*n-4, Cycle time n minus 2 per time.

Code
through the above analysis, the idea is very clear, thousand words than a yard:

Import Itertools 
def Spiral (n,m): 
  _status = itertools.cycle ([' Right ', ' down ', ' left ', ' up ']) #用于状态周期性的切换 
  _ Movemap = { 
    ' right ':(1,0), 
    ' down ':(0,1], 
    ' left ':( -1,0), 
    ' up ':(0,-1), 
  } 
  pos2no = Dict.fromkeys ([(X,y) for x in range (n) to Y in range (m)]) 
  _pos = (0,0) 
  _st = Next (_status) for 
  I in range ( 1,n*m+1): 
    _oldpos = _pos 
    _pos = tuple (Map (Sum,zip (_pos,_movemap[_st))) #根据状态进行移动 
    if (_pos not in pos2no ) or (Pos2no[_pos]): #当超出范围或遇到障碍时切换方向 
      _st = Next (_status) 
      _pos = tuple (Map (Sum,zip (_oldpos,_movemap[_st))) 
    Pos2no[_oldpos] = i return 
  pos2no 
 
def display_spiral (n,m): 
  pos2no = Spiral (n,m) for 
  i in Range (m): 
    for J in Range (n): 
      print pos2no[(j,i)], ' \ t ', 
    print ' \ n ' 
  print '-' *30 
 
Display_ Spiral (4,4) 
display_spiral (5,4) 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.