Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Modulus Giving String Formatting Errors

Tags:

python

modulus

I'm trying to perform the modulus of a value in python, but I'm getting errors as it's interpretting the modulus as a string formatting constant, from my knowledge. My initial guess would be to type cast this, but then it hangs.

    val = pow(a,n,p)
    val = y1*val
    val = val % p

Are the two lines of code corresponding to this question. Right now, when I run this, I get: TypeError: not all arguments converted during string formatting At the second line.

If I wrap val into an integer and type cast it...it takes extremely long to calculate.

I'm not too skilled with python, my guess is I'm missing something simple, but what?

like image 402
r36363 Avatar asked Mar 20 '12 18:03

r36363


2 Answers

If yu are getting this error, y1 itself is a string. You can't perform numeric calculations with strings - when you do "int(y1) " - it is not casting, it is converting the number represented by characters inside the string o an actual numeric value - and that is the only way you can perform numeric operations on it.

If it is takin thta log, it is probable because you are trying convert "y1 * val" to int - which is wrong already - if y1 is a string, "y1 * val" gives you y1 concatenated to itself "val" times - so it would be a really huge number. You need to have the value i n "y1" as a number before multiplying - as in:

val  = int(y1) * val
like image 61
jsbueno Avatar answered Oct 26 '22 22:10

jsbueno


As you can see from this code, the % operator has different meanings with strings than with numbers.

>>> 1 % 2
1
>>> '1' % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

My guess is that y1 is actually a string. Here's the difference the type of y1 makes:

>>> val = 10
>>> y1 = '2'
>>> val * y1
'2222222222'
>>> y1 = 2
>>> val * y1
20
like image 45
Steven Rumbalski Avatar answered Oct 26 '22 22:10

Steven Rumbalski