Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Shorten ugly code?

I have a ridiculous code segment in one of my programs right now:

str(len(str(len(var_text)**255)))

Is there an easy way to shorten that? 'Cause, frankly, that's ridiculous.

A option to convert a number >500 digits to scientific notation would also be helpful (that's what I'm trying to do)

Full code:

print("Useless code rating:" , str(len(var_text)**255)[1] + "e" + str(len(str(len(var_text)**255))))
like image 249
Violet Avatar asked Nov 19 '25 21:11

Violet


1 Answers

TL;DR: y = 2.408 * len(var_text)

Lets assume that your passkey is a string of characters with 256 characters available (0-255). Then just as a 16bit number holds 65536 numbers (2**16) the permutations of a string of equal length would be

n_perms = 256**len(passkey)

If you want the number of (decimal) digits in n_perms, consider the logarithm:

>>> from math import log10
>>> log10(1000)
3.0
>>> log10(9999)
3.9999565683801923
>>> 

So we have length = floor(log10(n_perms)) + 1. In python, int rounds down anyway, so I'd say you want

n_perms = 256**len(var_text)
length = int(log10(n_perms)) + 1

I'd argue that 'shortening' ugly code isn't always the best way - you want it to be clear what you're doing.

Edit: On further consideration I realised that choosing base-10 to find the length of your permutations is really arbitrary anyway - so why not choose base-256!

length = log256(256**len(var_text)
length = len(var_text) # the log and exp cancel!

You are effectively just finding the length of your passkey in a different base...

Edit 2: Stand back, I'm going to attempt Mathematics!

if x = len(var_text), we want y such that
y = log10(256**x)
10**y = 256**x
10**y = (10**log10(256))**x
10**y = (10**(log10(256)x))
y = log10(256) * x

So, how's this for short:

length = log10(256) * len(var_text)     # or about (2.408 * x)
like image 66
Peter Gibson Avatar answered Nov 22 '25 10:11

Peter Gibson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!