TheFoxx TheFoxx - 20 days ago 5
Python Question

syntax-error: can't assign to operator

def RandomString (length,distribution):
string = ""
for t in distribution:
((t[1])/length) * t[1] += string
return shuffle (string)


This returns a syntax error as described in the title. In this example,
distribution
is a list of tuples, with each tuple containing a letter, and its distribution, with all the distributions from the list adding up to 100, for example:

[("a",50),("b",20),("c",30)]


And
length
is the length of the string that you want.

Answer

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)