0

I have the following problem

import random
a_list = range(0,64)
a = random.sample(a_list,16)
print(a)

So I get 16 random numbers.

Now what I want further is to add every two numbers in the random set of 16 elements even with each number to be added with itself.

2 Answers 2

1

If you want to use just pure python lists, the solution can be a one-liner list comprehension.

sums_list = [n+m for n in a for m in a]

With Numpy you can use broadcasting.

import numpy as np
arr = np.array(a)
sums = arr[:, np.newaxis] + arr[np.newaxis, :]
sums_list = sums.flatten().tolist()
4
  • Can you also tell that after getting the list of these sums how can I tell python to give me the missing numbers from our original list ( 0 --63) anf there are no missing numbers return Commented Jul 15, 2021 at 9:56
  • You can use set difference: set(a_list) - set(sums_list). Commented Jul 15, 2021 at 11:15
  • Please accept the answer if it is satisfactory. Commented Jul 15, 2021 at 11:16
  • Yes all worked thank you. Appreciate your effort. Commented Jul 15, 2021 at 13:06
0

Can you please write down an example of what you are trying to achieve?

1
  • I want a list of 0 --63 numbers then i want to select any 16 numbers randomly and then i want the list of all sums of two numbers in the random list of 16 numbers and want to check if the sums will give me the original list ( 0 ---63) by usin only the random 16 numbers Commented Jul 15, 2021 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.