2025-08-18_simple-python-tricks-17.html


001| #:name::Simple Python Tricks #17
002| #:link::https://thehardcorecoder.com/2025/08/18/simple-python-tricks-17/
003| #:date::2025-08-18
004| #:code::
005| def fizz_buzz_1 ():
006|     """Fizz-Buzz Quiz, basic approach."""
007| 
008|     for n in range(1,101):
009|         if n%3 == 0:
010|             if n%5 == 0:
011|                 print(f'{n:3d}: "FizzBuzz"')
012|                 continue
013| 
014|             print(f'{n:3d}: "Fizz"')
015|             continue
016| 
017|         if n%5 == 0:
018|             print(f'{n:3d}: "Buzz"')
019|             continue
020| 
021|         print(f'{n:3d}: "{n}"')
022|     print()
023| 
024| if __name__ == '__main__':
025|     print()
026|     fizz_buzz_1()
027|     print('Done.')
028| 
029| #:code::
030| def fizz_buzz_2 ():
031|     """Fizz-Buzz Quiz, Python approach."""
032| 
033|     threes = ["Fizz" if n%3 == 0 else "" for n in range(1,101)]
034|     fives  = ["Buzz" if n%5 == 0 else "" for n in range(1,101)]
035|     flags  = [len(x3)+len(x5) for x3,x5 in zip(threes,fives)]
036| 
037|     for n,flg,x3,x5 in zip(range(1,101), flags, threes, fives):
038|         output = f'{x3}{x5}' if flg else str(n)
039|         print(f'{n:3d}: "{output}"')
040|     print()
041| 
042| if __name__ == '__main__':
043|     print()
044|     fizz_buzz_2()
045|     print('Done.')
046| 
047| #:code::
048| def python_quiz_1 (num=5):
049| 
050|     def memo_func (n, memo={}):
051|         if n in memo: return memo[n]
052|         if n <= 2: return 1
053|         memo[n] = memo_func(n-1,memo) + memo_func(n-2,memo)
054|         return memo[n]
055| 
056|     print(f'{num} => {memo_func(num)}')
057| 
058| if __name__ == '__main__':
059|     print()
060|     python_quiz_1(7)
061|     print('Done.')
062| 
063| #:code::
064| def python_quiz_2 (num=5):
065| 
066|     def memo_fib (n, memo={}):
067|         print(f'memo_fib({n}, {len(memo)})')
068| 
069|         if n in memo:
070|             print(f'memo[{n}] => {memo[n]}')
071|             return memo[n]
072|         if n <= 2:
073|             print('return 1')
074|             return 1
075| 
076|         memo[n] = memo_fib(n-1,memo) + memo_fib(n-2,memo)
077|         print(f'{n} => {memo[n]}')
078|         return memo[n]
079| 
080|     print('#1')
081|     print(f'fib({num}) => {memo_fib(num)}\n')
082|     print('#2')
083|     print(f'fib({num+1}) => {memo_fib(num+1)}\n')
084|     print('#3')
085|     print(f'fib({num+2}) => {memo_fib(num+2)}\n')
086|     print()
087|     print('#4')
088|     print(f'fib({num+3}) => {memo_fib(num+3, {})}\n')
089|     print('#5')
090|     print(f'fib({num+4}) => {memo_fib(num+4)}\n')
091|     return ()
092| 
093| if __name__ == '__main__':
094|     print()
095|     python_quiz_2(7)
096|     print('Done.')
097| 
098| #:code::
099| def python_gotcha ():
100| 
101|     def add_item_to_list (my_item, my_list=[]):
102|         my_list.append(my_item)
103|         return my_list
104| 
105|     grocery_list = add_item_to_list('bread')
106|     grocery_list = add_item_to_list('cheese', grocery_list)
107|     grocery_list = add_item_to_list('beans', grocery_list)
108| 
109|     todo_list = add_item_to_list('dust')
110|     todo_list = add_item_to_list('vacuum', todo_list)
111| 
112|     print(f'Shopping: {grocery_list}')
113|     print()
114|     print(f'Chores: {todo_list}')
115|     print()
116| 
117| if __name__ == '__main__':
118|     print()
119|     python_gotcha()
120|     print('Done.')
121| 
122| #:code::
123| def python_gotcha_solved ():
124| 
125|     def add_item_to_list (my_item, my_list=None):
126|         if my_list is None:
127|             my_list = []
128|         my_list.append(my_item)
129|         return my_list
130| 
131|     grocery_list = add_item_to_list('bread')
132|     grocery_list = add_item_to_list('cheese', grocery_list)
133|     grocery_list = add_item_to_list('beans', grocery_list)
134| 
135|     todo_list = add_item_to_list('dust')
136|     todo_list = add_item_to_list('vacuum', todo_list)
137| 
138|     print(f'Shopping: {grocery_list}')
139|     print()
140|     print(f'Chores: {todo_list}')
141|     print()
142| 
143| if __name__ == '__main__':
144|     print()
145|     python_gotcha_solved()
146|     print('Done.')
147| 
148| #:code::
149| def python_gotcha_solved_pedantic_version ():
150| 
151|     def add_item_to_list (my_item, my_list=None):
152|         the_list = [] if my_list is None else my_list
153|         the_list.append(my_item)
154|         return the_list
155| 
156|     grocery_list = add_item_to_list('bread')
157|     grocery_list = add_item_to_list('cheese', grocery_list)
158|     grocery_list = add_item_to_list('beans', grocery_list)
159| 
160|     todo_list = add_item_to_list('dust')
161|     todo_list = add_item_to_list('vacuum', todo_list)
162| 
163|     print(f'Shopping: {grocery_list}')
164|     print()
165|     print(f'Chores: {todo_list}')
166|     print()
167| 
168| if __name__ == '__main__':
169|     print()
170|     python_gotcha_solved_pedantic_version()
171|     print('Done.')
172| 
173| #:code::
174| def sierpinski_triangle (level=6, char='*', space=' '):
175|     """Draw a left-aligned Sierpinski Triangle."""
176| 
177|     # We need N to be a power of two...
178|     n = pow(2, level)
179| 
180|     result = []
181|     for y in range(n):
182|         buf = []
183| 
184|         for x in range(n):
185|             buf.append(space if x & y else char)
186| 
187|         result.append(buf)
188| 
189|     for row in result:
190|         print(''.join(row))
191| 
192|     return result
193| 
194| if __name__ == '__main__':
195|     print()
196|     sierpinski_triangle(5)
197|     print('Done.')
198| 
199| #:code::
200| def square_grid (n):
201|     """Given some number, returns two integer sides for a square that can hold at least n units."""
202|     print(f'square({n:d})')
203| 
204|     root = pow(n, 1/2) # square root
205|     x = int(root)
206|     # If the square root isn't integer, round up...
207|     if root != x:
208|         x += 1
209| 
210|     print(f'square: ({x},{x}); {pow(x,2)}')
211|     print()
212|     return (x, x)
213| 
214| if __name__ == '__main__':
215|     print()
216|     ns = list(range(9))
217|     for n in range(3,13):
218|         n2 = pow(n, 2)
219|         ns.append(n2-1)
220|         ns.append(n2)
221|         ns.append(n2+1)
222| 
223|     print('Fit Square')
224|     for n in ns:
225|         square_grid(n)
226|     print()
227|     print('Done.')
228| 
229| #:code::
230| def cubic_grid (n):
231|     """Given some number, returns three integer sides for a cube that can hold at least n units."""
232|     print(f'cubic({n:d})')
233| 
234|     root = pow(n, 1/3) # cube root
235|     x = int(root)
236|     # If the cube root isn't integer, round up...
237|     if root != x:
238|         x += 1
239| 
240|     print(f'cubic: ({x},{x},{x}); {pow(x,3)}')
241|     print()
242|     return (x, x, x)
243| 
244| if __name__ == '__main__':
245|     print()
246| 
247|     ns = list(range(10))
248|     for n in range(3,13):
249|         n3 = pow(n, 3)
250|         ns.append(n3-1)
251|         ns.append(n3)
252|         ns.append(n3+1)
253| 
254|     print('Fit Cube')
255|     for n in ns:
256|         cubic_grid(n)
257|     print()
258|     print('Done.')
259| 
260| #:code::
261| from itertools import zip_longest
262| 
263| def generate_list_of_pairs (data, fillvalue='@'):
264|     """Split data into a list of pairs."""
265|     print(data)
266|     print()
267| 
268|     even  = [d for ix,d in enumerate(data) if (ix%2)==0]
269|     odd   = [d for ix,d in enumerate(data) if (ix%2)==1]
270|     print(even)
271|     print(odd)
272|     print()
273| 
274|     pairs = zip_longest(even,odd, fillvalue=fillvalue)
275|     for a,b in pairs:
276|         print(f'{a}.{b}')
277|     print()
278| 
279|     return pairs
280| 
281| if __name__ == '__main__':
282|     print()
283|     data = [chr(ord('A')+ix) for ix in range(25)]
284| 
285|     pairs = generate_list_of_pairs(data, '*')
286|     print('Done.')
287| 
288| #:code::
289| from os import path
290| import zipfile as zf
291| 
292| FMT = '{ix:2d}: {sfs:>10s} {scs:>10} {pct:6.3f}% [{sct}] {fname}'
293| 
294| def zip_compression_type (n:int) -> str:
295|     if n == zf.ZIP_STORED: return 'Stor'
296|     if n == zf.ZIP_DEFLATED: return 'Defl'
297|     if n == zf.ZIP_BZIP2: return 'BZip'
298|     if n == zf.ZIP_LZMA: return 'LZMA'
299|     raise ValueError(f'Unknown compression type: {n}')
300| 
301| def ziplist (zname, zpath=r'C:\demo\hcc\python'):
302|     '''List contents of a ZIP file.'''
303|     zipname = path.join(zpath, zname) if zpath else zname
304| 
305|     zipfile = zf.ZipFile(zipname)
306|     print(f'opened: {zipname}')
307|     print()
308| 
309|     # List the filenames...
310|     for ix,name in enumerate(zipfile.namelist(), start=1):
311|         print(f'{ix:2d}: {name}')
312|     print()
313| 
314|     # List the details...
315|     for ix,zi in enumerate(zipfile.infolist(), start=1):
316|         args = dict(
317|             ix  = ix,
318|             sfs = f'{zi.file_size:,}',
319|             scs = f'{zi.compress_size:,}',
320|             pct = 100.0 * (zi.compress_size / zi.file_size),
321|             sct = zip_compression_type(zi.compress_type),
322|             fname = zi.filename
323|         )
324|         print(FMT.format(**args))
325|     print()
326| 
327| if __name__ == '__main__':
328|     print()
329|     ziplist('archive.zip')
330|     print('Done.')
331| 
332| #:code::
333| from os import path, listdir
334| import zipfile as zf
335| 
336| def zipper (fpath, zname='archive.zip'):
337|     '''Put all the files in a given directory into a ZIP file.'''
338| 
339|     # Get a list of files...
340|     fnames = listdir(fpath)
341| 
342|     # Set ZIP parameters and filename...
343|     props = dict(
344|         mode='w',
345|         compression=zf.ZIP_DEFLATED,
346|         compresslevel=9
347|     )
348|     zipname = path.join(fpath, zname)
349| 
350|     # Create (or overwrite!) a ZIP file...
351|     with zf.ZipFile(zipname, **props) as archive:
352| 
353|         # Iterate over the list of files...
354|         for fname in fnames:
355|             # Ignore our own name in case old version exists...
356|             if  fname == zname:
357|                 continue
358| 
359|             # Need the full file path and name...
360|             filename = path.join(fpath,fname)
361| 
362|             # Only store files; subdirectory recursion is extra...
363|             if path.isfile(filename):
364|                 # Add file to archive...
365|                 archive.write(filename, fname)
366| 
367|     print(f'created: {zipname}')
368|     print()
369| 
370| if __name__ == '__main__':
371|     print()
372|     zipper(r'C:\demo\hcc\python')
373|     print('Done.')
374| 
375| #:end:code::
376|