Chr() arg not in range python -
i have been creating program, , part of involves modifying list of characters @ random:
while rel>0: pos = random.randint(0,len(out)-1) change = random.randint(-1*rel,rel) if (change+ord(out[pos]))>=255: change = 255-ord(out[pos]) elif ((ord(out[pos]))-change)<=0: change = -1*(ord(out[pos])) out[pos] = chr(ord(out[pos])+change) rel -= abs(change) here, rel 'currency' program using modify list of characters out. first chooses random position in list, , random amount of change position between -rel , +rel, changes value of character using chr(ord(out[pos])+change). giving me error new modified value character out of range(256), added 2 if statements executed before changing character, still returns error, large values of rel. how can stop this?
the problem in choice of translation checks.
elif ((ord(out[pos]))-change)<=0: why difference meaningful? of other operations on sum of char , change. error when change < -ord(out[pos]): neither if nor elif condition true, wind taking chr of negative number.
change minus plus, , should fine, until values of rel beyond 512. if possible, please consider using modulus (%) instead of simple subtraction.
it took me couple of minutes trace this. cleaned program , added pair of tracing prints find out what's going on.
import random out = list("now time parties") rel = 500 while rel > 0: pos = random.randint(0, len(out)-1) chord = ord(out[pos]) change = random.randint(-rel, rel) print "a", chord, change if change + chord >= 255: change = 255 - chord elif chord + change <= 0: change = -chord print "b", chord, change out[pos] = chr(chord + change) rel -= abs(change) print ''.join(out)
Comments
Post a Comment