Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a list L and want to return a list of n items from it, at random.
Right now I am relying on itertools.combinations and then picking one at random, but I have to wait a while until the list looks like something that isn't stuck with a lot of items near the start of the list, so it's not really "random."
use random.sample to sample K items from a list of population n.
>>> import random
>>> random.sample(range(100), 5)
[56, 1, 0, 60, 61]
from random import randint
L=[1,2,3,4,5,6]
a=len(L)
n=5
K=[ L[randint(0,a-1)%a] for x in xrange(0,n)]
print K
Sample output
[6, 4, 3, 2, 5]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
For a homework assignment I am given this task:
Read a list of numbers and generate a new list which squares the members of the original list.
generate a third list of ints that ranks the second list of ints.
What does it mean to "rank the list"? What is this asking me to do?
I am NOT asking for a solution to the programming assignment, please do not provide one.
To create a list of integers between 0 and N, a solution is to use the range(N) function.
Then you can use the append() method which adds an item to the end of the list while getting the square of each element.
Finally use the sort() method which sorts the list ascending by default. You can also make a function to decide the sorting criteria(s)
def printSortedList():
l = list()
for i in range(1,21):
l.append(i**2)
l.sort()
print(l)
printSortedList()
Ranking means to number the items in a list from lowest to highest, or vice-versa.
So, for example, “ranking” the list [639, 810, 150, 162, 461, 853, 648] produces the list [4, 6, 1, 2, 3, 7, 5], where 1 corresponds to the lowest value (150), 2 to the next-lowest value (162).
Or maybe you're supposed to rank them the other way, giving [4, 2, 7, 6, 5, 1, 3].
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have 5 arrays with 6 questions in each one.
I need the script to pick 2 questions from each array and create an input() function. The part I can't seem to think of is how to make an output for a correct answer for the questions. I understand how a specified input would work but what about randomized.
I think you're looking for something like this:
randomNumber1=***some generated number (0 thru 6)
randomNumber2=***some generated number (0 thru 6)
array1=['what is the meaning of life', 'how far away is the sun',...]
array2=['what did is your favorite color', 'how many pennies are in 1 dollar'...]
q1=array1[randomNumber1]
q2=array2[randomNumber2]
input1=input(q1)
input2=input(q2)
#stores answers in a dictionary
answers={q1:input1, q2:input2}
I do not think the random module has the function that you want.
But it is easy to build one if you like. Python is easy.
Does this work?
import random
from typing import Iterable
def get_sub_random_list(sub_length: int, iterable: Iterable) -> list:
iterable_copy = list(iterable)
result = []
for __ in range(sub_length):
length = len(iterable_copy)
if length == 0:
raise ValueError(f"the iterable should longer than {sub_length}")
index = random.choice(range(length))
result.append(iterable_copy[index])
del iterable_copy[index]
return result
example:
>>> get_sub_random_list(1, [1, 2, 3, 4, 5, 6])
[5]
>>> get_sub_random_list(6, [1, 2, 3, 4, 5, 6])
[4, 1, 5, 2, 6, 3]
The complexity is O(n+m): n is the length of iterable, and the m is the the times of the loop.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am going through the exercises here: https://www.machinelearningplus.com/python/101-pandas-exercises-python/
Problem #16 has a solution (#1) using np.where() that I am having trouble understanding.
import pandas as pd
import numpy as np
print('pandas: {}'.format(pd.__version__))
print('NumPy: {}'.format(np.__version__))
print('-----')
ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])
ser2 = pd.Series([1, 3, 10, 13])
# Get the positions of items of 'ser2' in 'ser1' as a list.
# Solution 1
list1 = [np.where(i == ser1)[0].tolist()[0] for i in ser2]
print(list1)
print()
# Solution 2
list2 = [pd.Index(ser1).get_loc(i) for i in ser2]
print(list2)
I have looked up np.where() here:
# https://stackoverflow.com/questions/34667282/numpy-where-detailed-step-by-step-explanation-examples
# https://thispointer.com/numpy-where-tutorial-examples-python/
# https://www.geeksforgeeks.org/numpy-where-in-python/
To be precise, I am not understanding the function and placement of both
bracketed zero's ( [0] ).
np.where outputs a tuple (output of numpy.where(condition) is not an array, but a tuple of arrays: why?), so you'd have to index it (hence the first [0]), then, the output is a numpy array of elements. There is only one in this case, so the second [0] works. the tolist() is completely redundant though
It'd be better to extend list1 with the found indexes, because this code fails when an element occurs more than once:
list1 = []
[list1.extend(np.where(i == ser1)[0]) for i in ser2]
print(list1)
print()
Not the best code imo.
tip, just check the output of stuff yourself, and you would have figured this out. just run np.where(i==ser1) and you'd have seen it returns a tuple, and you need to index it. etc.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Say I've a list with a fixed size and elements.
I wish to create set of all possible combinations of the elements inside the array. How do I achieve this?
In python I've tried to use itertools like this:
import itertools
a = [4, 7]
for L in range(0, len(a)+1):
for subset in itertools.combinations(a, L):
print(subset)
Howsoever, this gives me an output(),(4),(7),(4,7) as in tuples. I want 4,7,47,74 as my desired output in a list or array(C++) and not to print them after each loop iteration.
I don't know if that's permutation or combination. So kindly bear with me and help.
From your sample output (which by the way is not in agreement with your input), it is clear that you don't need combinations but permutations from itertools. You can use join to merge your two numbers for printing purpose.
Most importantly, you should start your loop over L from 1 because you need at least length of 1 to generate the permutations other wise you will get empty lists (tuples) as you mentioned in your question.
import itertools
a = [4, 7]
lst = []
for L in range(1, len(a)+1):
for subset in itertools.permutations(a, L):
lst.append(''.join(str(x) for x in subset))
for l in lst:
print (l)
Output
4
7
47
74
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I am trying to remove duplicate values from a list.
This is what i have so far:
list1=[1,2,3,4,3,2,1]
list2=[]
l=len(list1)
for i in range(l):
if list1[i] not in list2:
list2.append(list1[i])
print(list2)
# [1, 2, 3, 4]
And it works just fine.
However, i am wondering if you can get the same result under the following conditions:
Conditions:
Should not use any predefined functions to remove item
Can use loops but, only once
And should not use any other 2nd list
I tried but I didn't make any progress. Is it possible..?
Just use a set. A set is technically a type. Technically correct is the best kind of correct.
>>> type(set)
<class 'type'>
>>> set([1,1,1,1,1,1,2])
{1, 2}
Does this follow the sadistic rules?
alist = [1,2,3,4,1,1,6,7,2,2,8,10]
i = 0
while i < len(alist):
if alist[i] in alist[i+1:]:
del alist[i]
i -= 1
i += 1
print(alist)
#[3, 4, 1, 6, 7, 2, 8, 10]
The order of the items in the list returned might seem weird but what actually happens is that the last appearance of every item is kept.
However, i would not recommend you to spend too much time with my code. Playing with i like this is not adviceable and the solutions (which might not satisfy your rules) using list(set(alist)) are of course better.