2023-11-18_simple-python-tricks-1.html


001| #:name::Simple Python Tricks #1
002| #:link::https://thehardcorecoder.com/2023/11/18/simple-python-tricks-1/
003| #:date::2023-11-18
004| #:code::
005| def chunker (seq, size):
006|     '''Return seq elements in chunks.'''
007|     for ix in range(0, len(seq), size):
008|         yield seq[ix:ix+size]
009| 
010| example_text = '''\
010| While I love coding, it turns out I don't enjoy blogging \
010| about it quite as much as I thought I would. I'm not \
010| ready to toss in the towel yet, and to help develop more \
010| of a habit of posting here, I thought I'd try posting \
010| some really simple things.'''

011| 
012| for c in chunker(example_text, 24):
013|     print(c)
014| print()
015| 
016| #:code::
017| def commas (number):
018|     '''Insert commas every three digits.'''
019|     s0 = str(number)
020|     s1 = chunker(list(reversed(s0)),3)
021|     s2 = [''.join(ch) for ch in s1]
022|     s3 = ','.join(s2)
023|     s4 = reversed(s3)
024|     return ''.join(s4)
025| 
026| print(commas(1))
027| print(commas(12))
028| print(commas(123))
029| print(commas(1230))
030| print(commas(12300))
031| print(commas(123000))
032| print(commas(1230000))
033| print(commas(12300000))
034| print(commas(123000000))
035| 
036| #:code::
037| seq = bytes(range(256))
038| 
039| for group in chunker(seq, 16):
040|     s = ['%02x' % c for c in group]
041|     print(' '.join(s))
042| print()
043| 
044| #:code::
045| seq = bytes(range(256))
046| 
047| def blocks (seq, rowsize, width):
048|     for rx in range(0, len(seq), rowsize):
049|         row = seq[rx:rx+rowsize]
050|         bs = [row[cx:cx+width] for cx in range(0, len(row), width)]
051|         yield bs
052| 
053| def demo_blocks (rowsize, width):
054|     for row in blocks(seq, rowsize, width):
055|         line = []
056|         for datum in row:
057|             s =  ['%02x' % b for b in datum]
058|             line.append(''.join(s))
059|         print(' '.join(line))
060|     print()
061| 
062| demo_blocks(16, 1)
063| demo_blocks(16, 2)
064| demo_blocks(16, 4)
065| 
066| #:code::
067| seq = bytes(range(256))
068| 
069| def get_row (seq, rowsize=16, width=1, endian='BE'):
070|     '''Given a sequence of bytes, return BYTES, WORDS or DWORDS.'''
071|     _endian = endian.upper()
072|     assert _endian in ['LE','BE'], ValueError('Endian must be LE or BE')
073| 
074|     # Generate the byte indexes
075|     bixs = list(reversed(range(width)) if _endian=='BE' else range(width))
076| 
077|     # For each row of data...
078|     for rx in range(0, len(seq), rowsize):
079|         row = []
080| 
081|         # For each group of bytes...
082|         for gx in range(0, rowsize, width):
083|             if len(seq) <= (rx+gx):
084|                 break
085|             accum = 0
086| 
087|             # For each byte in the group...
088|             for ix,bix in enumerate(bixs):
089|                 if (rx+gx+bix) < len(seq):
090|                     # Get byte (or zero if beyond row)...
091|                     value = seq[rx+gx+bix] if (gx+bix)<rowsize else 0
092|                     # Shift value into the accumulator...
093|                     accum += (value << (8 * ix))
094| 
095|             # Add the value to the row...
096|             row.append(accum)
097| 
098|         # Yield the row...
099|         yield (rx, row)
100| 
101| 
102| def demo_get_row (rowsize=16, width=1, endian='le'):
103|     for rx,row in get_row(seq, rowsize=rowsize, width=width, endian=endian):
104|         buf = ['%0*x' % (2*width,g) for g in row]
105|         print('%04x: %s' % (rx,' '.join(buf)))
106|     print()
107| 
108| demo_get_row(rowsize=16, width=1)
109| 
110| demo_get_row(rowsize=16, width=2, endian='le')
111| demo_get_row(rowsize=16, width=2, endian='be')
112| 
113| demo_get_row(rowsize=16, width=4, endian='le')
114| demo_get_row(rowsize=16, width=4, endian='be')
115| 
116| demo_get_row(rowsize=17, width=5, endian='le')
117| demo_get_row(rowsize=17, width=5, endian='be')
118| 
119| #:code::
120| def hex_dump (data, rowsize=16, width=1, endian='le'):
121|     '''Configurable Hex Dump function.'''
122| 
123|     def char (cx):
124|         '''Convert character index to a character.'''
125|         if 0x110000 <= cx:
126|             # Return non-unicode code point...
127|             return '?'
128|         # Convert index to a character...
129|         ch = chr(cx)
130|         if chr(cx).isprintable():
131|             # Return printable character...
132|             return ch
133|         # Return non-printable character...
134|         return '.'
135| 
136|     # Determine the number of number groups per row...
137|     rowcount,rem = divmod(rowsize, width)
138|     if rem:
139|         rowcount += 1
140| 
141|     # Iterate over the rows of data...
142|     for rx,row in get_row(data, rowsize=rowsize, width=width, endian=endian):
143| 
144|         # Generate hex values from row data...
145|         xvals = ['%0*x' % (2*width,g) for g in row]
146|         # Check for dangling (last) row...
147|         while len(xvals) < rowcount:
148|             # Fill out the row...
149|             xvals.append('%*s' % (2*width,''))
150| 
151|         # Generate character values from row data...
152|         svals = [char(g) for g in row]
153| 
154|         # Print the row...
155|         print('%04x| %s | %s' % (rx,' '.join(xvals), ''.join(svals)))
156| 
157|     # End with a nice blank line...
158|     print()
159| 
160| #:code::
161| seq = bytes(range(256))
162| 
163| class feeder (object):
164|     '''Given a sequence of bytes, return then in groups.'''
165| 
166|     def __init__ (self, seq, width=1, endian='LE'):
167|         '''New feeder instance.'''
168|         self.seq = seq
169|         self.wid = width
170|         self.end = endian.upper()
171|         self.bixs = list(range(width))
172|         assert self.end in ['LE','BE'], ValueError('Endian not LE or BE.')
173|         # Generate the byte indexes
174|         if self.end=='BE':
175|             self.bixs = list(reversed(range(width)))
176|         # Set data index to beginning of sequence...
177|         self.dix = 0
178| 
179|     def __next__ (self):
180|         '''Next data value.'''
181|         if len(self.seq) <= self.dix:
182|             raise StopIteration()
183| 
184|         # Generate next data value...
185|         value = 0
186|         for ix,bix in enumerate(self.bixs):
187|             curr = 0
188|             if (self.dix+bix) < len(self.seq):
189|                 curr = self.seq[self.dix + bix]
190|             value += (curr << (8 * ix))
191| 
192|         # Advance the data index...
193|         self.dix += self.wid
194|         # Return the value...
195|         return value
196| 
197|     def __iter__ (self):
198|         '''Get a new iterator.'''
199|         return feeder(self.seq, width=self.wid, endian=self.end)
200| 
201| 
202| def demo_feeder (width=1, endian='LE'):
203|     # Iterate over data values...
204|     for ix,datum in enumerate(feeder(seq, width=width, endian=endian)):
205|         print('%04x: %0*x' % (ix*width, 2*width, datum))
206|     print()
207| 
208| demo_feeder(12)
209| demo_feeder(16, 'be')
210| 
211| #:end:code::
212|