我正在开发一个用python对输入字符串进行哈希处理的程序,但我无法运行它。当我尝试将字符串的两个部分相加时,我的记忆会出现错误
File "C:/Users/jacke/PycharmProjects/Hashbrown/Hashbrown.py", line 43, in <module>
print(hashout(input("Hash input: ")))
File "C:/Users/jacke/PycharmProjects/Hashbrown/Hashbrown.py", line 8, in hashout
out = out + hash(x,0)
File "C:/Users/jacke/PycharmProjects/Hashbrown/Hashbrown.py", line 38, in hash
jumbled = second_half+first_half
MemoryError
这是我的代码,我试图通过各种转换对输入字符串进行编码,并输出散列字符串:
import math
import binstr
def hashout(input):
inputmod = input.replace(" ","spc").replace("y","55ut")
listofchars=[char for char in inputmod]
out =""
for x in listofchars:
out = out + hash(x,0)
return(out)
def hash(input,len_out):
inputlength = 1
n1 = int(input,32)
n2 = round(n1*inputlength)**math.sqrt(((inputlength*n1)**math.pi)*1537437/10000000000000000000000)
n3 = n2-inputlength
n4 = n3+inputlength + n1
s1 =str(n4)
s2 =s1[::-1]
s3 = s2.replace("e","")
s3 = s3.replace("+","").replace(".","")
l1=list(s3)
n5 = int(l1[0])
n6 = n5*int(s3)/10000
n7=(round(n6))
s99999=str(n7)
n=2
line=s99999
fakeascii=[line[i:i + n] for i in range(0, len(line), n)]
res = ""
for val in fakeascii:
res = res + chr(int(val))
asciiout=str(res)
test_str = asciiout.replace(" ","sp")
bindat=''.join(format(ord(i), 'b') for i in test_str)
s=(str(bindat*100000000))[::-1]
first_half = s[0:len(s) // 2]
second_half = s[len(s) // 2 if len(s) % 2 == 0 else ((len(s) // 2) + 1):]
jumbled = second_half+first_half
#out=binstr.bintostr(jumbled)
out=jumbled
return(out)
while True :
print(hashout(input("Hash input: ")))
这是binstr图书馆:
def BinaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while (binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return (decimal)
def bintostr(bin_data):
str_data = ' '
for i in range(0, len(bin_data), 7):
temp_data = int(bin_data[i:i + 7])
decimal_data = BinaryToDecimal(temp_data)
str_data = str_data + chr(decimal_data)
return(str_data)
代码编写得非常糟糕,但主要问题在于:
将bindat设置为字符串,然后尝试将其作为整数进行乘法,简单的替代是:
因此,您不会在任何地方使用binstr库,其中有一行注释,但根本没有使用。代码本身非常不理想,您经常将可以在一行中完成的事情拆分为多行,例如:
可以简化为:
也许你也可以把这些数字作为变量来添加,以使代码更清晰
您也可以经常执行一些步骤,比如分配一个变量,但没有原因或使用,比如
binary1=binary
在bintostr
中binary1=binary
,而不进一步使用变量binary1
或out = jumbled
,然后只返回这个变量。您应该避免使用此类代码,以提高可读性和性能。出于这个原因,我建议您签出this guide。它可能会帮助您编写更好的代码:)相关问题 更多 >
编程相关推荐