I was using a function to calculate the standard deviation of some hashing methods and I can’t seem to read the words from a list which in turn loads it from a file by indexing to first letter of the strings Here is the entire code:
import numpy as np
listhash1=[]
listhash2=[]
listhash3=[]
templist=[]
dictlist=[]
def hash1(list:list,list1):
for i in range(len(list)):
list1.append(ord((list[i][0]).upper())+len(list[i])-ord('A'))
return list1
def hash2(list:list,list2):
for i in range(len(list)):
list2(((ord((list[i][0]).upper())-ord('A'))*len(list[i]))%100)
def hash3(list:list,list3):
for i in range(len(list)):
list3((ord((list[i][0]).upper())-ord('A'))%len(list[i]))
def variance(list):
sum=0
deviations=0
for i in range(len(list)):
sum=sum+list[i]
sum=sum/len(list)
for j in range(len(list)):
deviations=deviations+np.pow((list[j]-sum),2)
deviations=deviations/len(list)
deviations=np.pow(deviations,0.5)
return deviations
q=0
with open("dict.txt","r") as dictionary:
for line in dictionary:
dictlist.append(dictionary.readline())
listhash1=hash1(dictlist,templist)
listhash2=hash2(dictlist,templist)
listhash3=hash3(dictlist,templist)
print(variance(listhash1),"n",variance(listhash2),"n",variance(listhash3),"n")
Sorry for any lack of specificty, this is my first question on this site
Edit: To expand further, when I try to run it, I get an error saying invalid string index on line 9(ord(list[i][0]), I tried running it with index 1 for the string instead of 0 since it wouldn’t really impact the hash function but it still didn’t change the error
Edit 2: the issue was fixed after I tried all suggestions in the comments. If for reference purposes anybody wants the results of the program, here they are:
7.631627233244063,
28.864721512130362,
2.8228899955211144
3
It seems that you’re not actually deserializing the dict
object but just reading it (line by line) as a file:
with open("dict.txt","r") as dictionary:
for line in dictionary:
dictlist.append(dictionary.readline())
You could try something like:
import ast
with open("dict.txt","r") as dictionary:
dictlist = ast.literal_eval(dictionary.read())
This is an educated guess of what you’re looking to do. But somehow you need to get the file object (or text) into the python object (dict).
1