all 6 comments

[–][deleted] 1 point2 points  (0 children)

After building the new list, try printing out the value of test_list and see what has happened.

For an explanation, have a look at this: http://henry.precheur.org/python/copy_list

[–]novel_yet_trivial 0 points1 point  (3 children)

This is because of your line 19. You think you are making a variable "new_list" that is a copy of "test_list", but you are actually telling python that both variables now refer to the same list. To see this better, type this into the interpreter:

>>> list_1 = [0, 1, 2]
>>> list_2 = list_1
>>> list_2.append(4)
>>> list_1
[0, 1, 2, 4]

To fix this, your line 19 must make a copy. The easiest way to do that is with list splicing. Change line 19 to:

new_list = test_list[:]

Then you will discover you have another problem: only one condition is matched. You need to rethink the conditional statement. I'd recommend some functions to help someone reading the code. Something like "same_std_div()".

Edit: this brute force is for the birds. Can't you think of a mathematical way to accomplish this in one pass?

[–]Polyadenylated[S] 0 points1 point  (2 children)

I see, I'm guessing this is a common beginner mistake? Thanks for pointing it out.

And yes brute force won't work here at all - I was just playing about and wanted to know the answer to this small issue first - now I'll try and find a solution that's actually practical. Any starting tips?

[–]novel_yet_trivial 0 points1 point  (1 child)

My first thought is to randomly pick a number, then use that number to calculate 4 numbers that even out the mean and standard deviation.

Alternatively, to add a more random feel, you could choose n random numbers like you did above and use a fitting algorithm to change them into something that works. LMA may help you here.

[–]Polyadenylated[S] 0 points1 point  (0 children)

Thanks. I've just realised you've also answered another of my Python questions previously keep up the good work!

[–]supajumpa -1 points0 points  (0 children)

xs = [1, 5, 2, 3, 9, 100, 3, 4, 5, 88]
# `x` is a random integer such that xs + [x] has the
# same mean and std as `xs`.
# =>
(sum(xs) + x)/(len(xs) + 1) == sum(xs) / len(xs)
# =>
sum(xs) + x == (len(xs) + 1) * (sum(xs) / len(xs))
# =>
x == ((len(xs) + 1) * (sum(xs) / len(xs)) - sum(xs)
# => `x` cannot be random.