This article mainly describes the Python implementation of reading string by column allocation after the output, involving Python for string traversal, judgment, operation and other related operations skills, the need for friends can refer to the next
The example in this article describes the Python implementation of reading a string by column distribution after the output is done. Share to everyone for your reference, as follows:
Problem:
Enter a string and a number, the number is divided into several lines, you need to follow the given column storage method is stored and then read by the line splicing, such as:
Input: tngdwxazqscvbk,3
Output: Twqbndxzsvkgac
This pattern is formed when the intermediate conversion occurs:
T W Q K
N D X Z S V B
G A C
The matrix may look clearer:
T 0 W 0 Q 0 B
N D X Z S V K
G 0 A 0 C 0 0
0 is filled in as blank, the following see the specific implementation:
#!usr/bin/env python#encoding:utf-8 "" __author__: Yishui Cold City Features: Zigzag_patternt W Q KN D X Z S V BG A cconvert ("TNGDWXAZQSC VBK ", 3) should return" TWQBNDXZSVKGAC ". def convert_test (one_str,num): "" "Mod=len (ONE_STR)% (num+1) if mod==0:cols= (Len (ONE_STR)/(NUM+1)) * * Else: Cols= (len (ONE_STR)/(num+1)) *2+1 rows=num #print ' rows, cols ', rows, cols matrix=[] for I in range (rows): MATRIX.A Ppend ([0]*cols) one_str_list=list (ONE_STR) for J in Range (cols): If J%2==0:for I in range (rows): If Len ( One_str_list): Matrix[i][j]=one_str_list.pop (0) else:matrix[1][j]=one_str_list.pop (0) #print Matrix # For one in The matrix: # ONE_LIST=[STR (Onec) for Onec in one] # print ". Join (One_list) res= ' for one_list in matrix : One_list=[str (one) for one in One_list] res+= ". Join (One_list) return '. Join (Res.split (' 0 ')) if __name__ = = ' __ma In__ ': Print convert_test ("TNGDWXAZQSCVBK", 3) Print convert_test ("paypalishiring", 2) Print convert_test ("Paypalishiring", 4)
The results are as follows:
Twqbndxzsvkgac
Ppiinayalshrig
Plraaiiiysnphg
[Finished in 0.3s]