Nick Coghlan wrote:

> Huh - you remind me that I forgot to put the "show_base" Bengt and I came
> up with into the ASPN cookbook. . .
> 
> Py> def show_base(val, base, min_digits=1, complement=False,
> ...���������������digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
> ...���if�base�>�len(digits):�raise�ValueError("Not�enough�digits�for
> base") ...���negative�=�val�<�0
> ...���val�=�abs(val)
> ...���if�complement:
> ...�����sign�=�""
> ...�����max�=�base**min_digits
> ...�����if�(val�>=�max)�or�(not�negative�and�val�==�max):
> ...�������raise�ValueError("Value�out�of�range�for�complemented�format")
> ...�����if�negative:
> ...�������val�=�(max�-�val)
> ...���else:
> ...�����sign�=�"-"�*�negative
> ...���val_digits�=�[]
> ...���while�val:
> ...�����val,�digit�=�divmod(val,�base)
> ...�����val_digits.append(digits[digit])
> ...���result�=�"".join(reversed(val_digits))
> ...���return�sign�+�("0"�*�(min_digits�-�len(result)))�+�result
> ...
> 

Yes, that is a bit more general. For the cookbook you might consider
factoring out the "".join() operation, thus entirely removing the upper
limit for the base (the output of the first step would be a tuple of
integers).

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to