How to randomly select elements from an array in python? - python-3.x

I need to randomly select elements from a list. Currently, I will sometimes select too many copies of an element from the original list eg:
Original List: [0, 1, 2, 3, 4]
3 Randomly Selected Elements: [4, 4, 4]
I do not want multiple 4s selected if there was only 1 in the original list.
What should I do to not take more copies of a value than exists in the first array?

A solution is to remove the elements from the original list when you select them.
import random
original_list = [1, 2, 2, 3, 3, 3]
number_of_random_selections = 4
random_selections = []
for i in range(0, len(original_list)):
random_index = random.randint(0, number_of_random_selections)
random_selection = original_list[random_index]
random_selections.append(random_selection)
original_list.remove(random_selection)
print(random_selections)

Related

I'm trying to add lists in lists by column. Is there a way to sum them with missing variables in a list?

I had followed the book and can sum lists in lists by column but one of the test cases is missing variables in the list and I'm unable to move forward because I keep getting an index error.
The first initial_list works as it should giving [3,6,9]
The second one though should apparently give me [3,4,9,4]
list_initial = [[1, 2, 3], [1, 2, 3],[1, 2, 3 ]]
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
def column_sums(list_initial):
column = 0
list_new = []
while column < len(list_initial):
total = sum(row[column] for row in list_initial )
list_new.append(total)
column = column + 1
print(list_new)
column_sums(list_initial)
You can effectively "transpose" your data so that rows become columns, and then use itertools.zip_longest with a fillvalue of 0, to sum across them, eg:
from itertools import zip_longest
list_initial = [[1, 2, 3], [1], [1, 2, 3, 4]]
summed = [sum(col) for col in zip_longest(*list_initial, fillvalue=0)]
# [3, 4, 6, 4]

How would I iterate through a list and replace objects that are repeated?

I am trying to go through a list and have each object in that list compared with the others, and all repetitions of it replaced with something else.
>>> t = [1, 2, 1, 1, 2, 2, 4, 4]
>>> for i in range(len(t)):
num = t[i]
if num in t[i+1:]:
num = 'cherry'
This is not turning the repeated ints into 'cherry'. I know that I am referring to them correctly as I put print(num) in place of num = cherry and it is printing what I want. It will not reassign them, though. What am I doing wrong?
You should make the list a set because sets are unordered collections of unique elements and are great for removing duplicates from a sequence
To make a set use either the set() function like in the code below or use curly braces {} like the output
t = [1, 2, 1, 1, 2, 2, 4, 4]
x = set(t)
print(x)
#Output
{1, 2, 4}

Can you use count() for an entire list instead of one variable?

Is there a way to use count() for an entire list rather than have to use it on each variable seperately? If this is possible it would save me alot of typing.
var1 = random.randint(u,v)
var2 = random.randint(w,x)
var3 = random.randint(y,z)
listName = [var1,var2,var3]
listName.count(x)
listName.count(y) #can you get the count for an entire list instead of having to do them
listName.count(z) #all seperately? It would be much more efficient.
Here's an example of creating a list with random contents and then showing the length and sum.
import random
my_list = [
random.randint(1, 10),
random.randint(1, 10),
random.randint(1, 10)
]
print("The value of my_list is {0}".format(my_list))
print("The length of my_list is {0}".format(len(my_list)))
print("The sum of my_list is {0}".format(sum(my_list)))
Sample Output:
The value of my_list is [4, 8, 4]
The length of my_list is 3
The sum of my_list is 16
Is this what you were looking for?
list.count(item) returns the number of times item appears in a list.
If you want to know how many times each item appears in the list, if it appears in the list, you can do this:
original_list = [1, 1, 2, 3, 4, 4, 4]
uniques = list(set(original_list))
counts = {}
for unique in uniques:
counts[unique] = original_list.count(unique)
print(counts)
which should print something like
{
1: 2,
2: 1,
3: 1,
4: 3
}
Here's more info on the set data type:
https://docs.python.org/3/tutorial/datastructures.html#sets
While we're at it, you can also use collections.Counter:
from collections import Counter
counts = Counter([1, 1, 2, 3, 4, 4, 4])
print(dict(counts))
and this should print the same dictionary as above.

For Loop only printing of 1? Python

I was trying to print a list in backwards order using a for loop, however my code only prints of a 1, any ideas why?
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(len(sorted_list)-2,-3,-1):
des_list.append(sorted_list[i-2])
des_list.append(sorted_list[i - 1])
des_list.append(sorted_list[i])
des_list.append(sorted_list[i+1])
print(des_list)
It would probably be easier to store the chunks of data into objects. That way, you can just call reversed() on the list of objects and handle the data that way.
If you want to keep the list in the format you have, you can loop through the list in "chunks", like this: for i in range(0, len(sorted_list), 4):.
So, for every 4 elements in the list, grab the chunk of of data using list slicing notation: sorted_list[i:i+4] and insert it to the front of the destination list.
Putting that together, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
des_list.insert(0, sorted_list[i:i+4])
print(des_list)
That will output this: [['sod', 3, 1, 0], ['tim', 5, 3, 1], ['bob', 0, 0, 10], ['jill', 4, 1, 0], ['jack', 4, 3, 1]].
Keep in mind that that code will give you a list of lists, because sorted_list[i:i+4] returns a list, which is why it might be easier to use objects instead.
If you don't want to have a list of lists, you can reverse the sliced list, loop through each element in the reversed sliced list, and insert it one at a time to the destination list.
Doing that, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
for j in reversed(sorted_list[i:i+4]):
des_list.insert(0, j)
print(des_list)
Which outputs this: ['sod', 3, 1, 0, 'tim', 5, 3, 1, 'bob', 0, 0, 10, 'jill', 4, 1, 0, 'jack', 4, 3, 1]

How to find all numbers in a list that are not part of a pair - using python 3

I am trying to write a python 3 function that finds all numbers in a list (unspecified length) that are not part of a pair.
For example, given the list [1, 2, 1, 3, 2], the function will return 3; and given the list [0, 1, 1, 7, 8, 3, 9, 3, 9], the function will return 0, 7, and 8.
Thanks for your help!
You can use the following function :
>>> def find(l):
... return (i for i in l if l.count(i)==1)
>>> l= [0, 1, 1, 7, 8, 3, 9, 3, 9]
>>> list(find(l))
[0, 7, 8]
This function will return a generator that is contain the elements in list which those count is equal to 1.
I can tell you how I would do it. What does it mean a "pair"?
You should say, find all the numbers repeated oddly in the array.
First plan: (more efficient!)
Sort the list and then a single loop through your list should be enough to find how many numbers of each there are inside and you can generate awhile another list that you will return.
Second plan (nicer in python, but also more expensive because of the number of evaluations though the hole list):
Try the solution of Kasra. 'count' function from 'list' type helps our code but not our efficiency. It counts the number of times that appears the value 'i' on the list 'l', obviously.
If the pair need to be "closed pair" I mean, if you have three 1 (ones), do you have one pair and one single 1? or do you have all the 1 paired? If the second one, the solution of Kasra is Ok. Else you should compare:
if l.count(i) % 2 == 1
This can be easily and efficiently done in 3 lines with collections.Counter.
from collections import Counter
def unpaired(numbers):
for key, count in Counter(numbers).items():
if count % 2:
yield key
print(list(unpaired([1, 2, 1, 3, 2])))
# [3]
print(list(unpaired([0, 1, 1, 7, 8, 3, 9, 3, 9])))
# [0, 7, 8]
My answer comport if you have three equals numbers or if you have one pair and one single number without pair.
def name(array):
o = sorted(array)
c = []
d = []
for i in o:
if o.count(i) % 2 == 1:
c.append(i)
for j in c:
if j not in d:
d.append(j)
return d
or do not use for j in c and use directly:
return list(set(c))
for example:
array = [0, 1, 1, 7, 8, 3, 9, 3, 9, 9]
output: [0, 7, 8, 9]

Resources