hash function for a string python syntax error - python

I am trying to compute the hash function for a string and I am receiving a syntax error about how to convert a character at position x to an integer value. Anyone know how to correctly do this?
def hashFunction(inputString, r, m):
for x in range(0,len(inputString)-1):
hashValue = (hashValue*r+(ord)inputString[x])% m
return hashValue

I see two issues, first of all, you're not calling ord on an argument. You probably want this:
hashValue = (hashValue*r+ord(inputString[x]))% m
Notice how I wrapped the argument in parentheses instead of around the function name.
The second thing is that you're using the value of hashValue when it hasn't been assigned to yet. This will give you an error when you call the function.

Related

How can we understand if the value inside a String is an int or not in Python?

I am writing a code where I am facing the problem and need a solution if it exists.
Suppose we have a following String type variable in Python which contains an integer value.
Eg:x='123'
I know that we can easily convert this by type conversion to int.
However, suppose we have the following list.
x=['123','Spain']
Is there any method in Python by which I can know which element of the list x is Integer contained inside a string and which is purely an Object?
I would recommend this method:
x = "123"
if x.isdigit():
# int
elif x.replace(".","",1).isdigit():
# float
else:
# str
I assume you have similar question with this post.
But, from my perspective, for more general solution (language agnostic), you should learn more about Regular Expression, here also the same question

Hexdigest from passing parameter

I wanted to create a function that could hash a string using sha.
Here's my code:
def hashNow(number,string):
for i in range (number):
hashH = int(hashlib.sha1(string.hexdigest(),16)
print hashH #debug purpose
indexing = hashH % len(arrays)
arrays[indexing] = 1
When I compile this code, it prints SyntaxError: invalid syntax pointing at the print hashH. Based on my experience, invalid syntax error usually is an error carrier from the previous line.
My question: am I implementing the hexdigest incorrectly? Why string.hexdigest() cause a syntax error?
One syntax error is that there is missing a closing bracket of the int()-call. Another error is, that sha1() returns an object what can't be converted to int (I'm trying it in python 2.7). By the way, sha-1 isn't really safe, sha-2 and sha-3 are better.

Iterable error with int when using for / argument ()error while using map. Where am i going worng

I tried bith ways using map nad using for loop but its not working i know for for loop it has to list,tuples or string. So how do i make this work
1
def narcissistic(value):
x = ((value)== sum((c)**len(value) for c in list(value)))
return x
2
def narcissistic(value):
x=(value== (map(lambda c :sum(c**len(value)),value)))
return x
Your issue comes down to confusion about the type of your different objects. Python is a strongly typed language, so each object has a clear type at any given moment and the language generally won't convert anything to another type automatically for you.
Based on the error you're getting, you're calling your function with an int argument. This causes you trouble when you try to call len or iterate on your value. Python ints don't have a length, nor are they iterable, so it's quite understandable that these fail under the circumstances.
What you want to do is create a string representation of your value number. Then you can loop over the characters of the string, and take its len freely.
There's another issue though. You're also trying to do an exponential operation on the c variable in the generator expression. That won't work because c is a string, not a number. It's a one-digit string, but still a str instance! To do math with it, you need to convert it back to a number with int.
Here's a fixed version of your function:
def narcissistic(number):
num_str = str(number)
return sum(int(c)**len(num_str) for c in num_str) == number
I've renamed the very generic value name with number, which should hopefully make it more clear what type each thing is.

String format argument for traits.Any

I'm using enthought canopy's traits to wrap a code for Nipype. I know format argument is %d for integer variables. However, Multiplication variable below should be also a file.
multiplication = traits.Int(argstr='-mul %d', desc='multiplication', position=2)
So, I want to use Any instead of Int but I don't know what the corresponding format argument is for Any. How can I replace %? below?
multiplication = traits.Any(argstr='-mul %?', desc='multiplication', position=2)
I've got the answer multiplication = traits.Any(argstr='-mul %s', desc='multiplication', position=2) It works for both integer and file

Converting a string-like object into a string in python

I am using python and XMLBuilder, a module I downloaded off the internet (pypi). It returns an object, that works like a string (I can do print(x)) but when I use file.write(x) it crashes and throws an error in the XMLBuilder module.
I am just wondering how I can convert the object it returns into a string?
I have confirmed that I am writing to the file correctly.
I have already tried for example x = y although, as I thought, it just creates a pointer, and also x=x+" " put I still get an error. It also returns an string like object with "\n".
Any help on the matter would be greatly appreciated.
file.write(str(x))
will likely work for you.
Background information: Most types have a function __str__ or __repr__ (or both) defined. If you pass an object of such a type to print, it'll recognize that you did not pass a str and try to call one of these functions in order to convert the object to a string.
However, not all functions are as smart as print and will fail if you pass them something that is not a string. Also string concatenation does not work with mixed types. To work with these functions you'll have to convert the non-string-type objects manually, by wrapping them with str(). So for example:
x = str(x)+" "
This will create a new string and assign it to the variable x, which held the object before (you lose that object now!).
The Library has __str__ defined:
def __str__(self):
return tostring(~self, self.__document()['encoding'])
So you just need to use str(x):
file.write(str(x))
I'm not quite sure what your question is, but print automatically calls str on all of it's arguments ... So if you want the same output as print to be put into your file, then myfile.write(str(whatever)) will put the same text in myfile that print (x) would have put into the file (minus a trailing newline that print puts in there).
When you write:
print myObject
The __repr__ method is actually called.
So for example you could do: x += myXMLObject.__repr__() if you want to append the string representation of that object to your x variable.

Categories