This question already has answers here:
How to get all possible combinations of a list’s elements?
(32 answers)
Closed 4 years ago.
I want to write a code which gives me all the possible combinations of n elements in a k length k>n.The issue with this code is that i run out of memory quite fast.I was wondering if someone knew how to fix this with generators.I don't want to get all the possible combinations of a list elements. I want to get all the combinations of the elements in a certain length.
Thanks.
def allstrings(alphabet, length):
"""Find the list of all strings of 'alphabet' of length 'length'"""
if length == 0: return []
c = [[a] for a in alphabet[:]]
if length == 1: return c
c = [[x,y] for x in alphabet for y in alphabet]
if length == 2: return c
for l in range(2, length):
c = [[x]+y for x in alphabet for y in c]
return c
if __name__ == "__main__":
for p in allstrings(['a','b','c'],4):
print (p)
import itertools
itertools.combinations('alphabet', length)
From How to get all possible combinations of a list’s elements?
Related
This question already has answers here:
Insert in a list random of 0 and 1 with a certain number of 1's
(4 answers)
Closed 3 years ago.
What's the shortest way (as in short code) to get a list of length n with p < n randomly allocated ones else zero. Say n = 6 and p = 2, I'd like something like [0,1,0,0,1,0].
First create a list with the correct number of 1s and 0s and then shuffle it:
import random
def random_ones(n, p):
ls = [1] * p + [0] * (n - p)
random.shuffle(ls)
return ls
You could sample the indices:
from random import sample
l = [0] * n
idxs = sample(range(n), p)
for idx in idxs:
l[idx] = 1
Or shorter:
from random import sample
idxs = sample(range(n), p)
l = [1 if i in idxs else 0 for i in range(n)]
This is perhaps not the most efficient way of doing it, but I feel it's a little simpler and easier to understand, so hopefully you'll be able to use it in future. :)
from random import randint
list,counter=[],0
for i in range(n):
list.append(1 if randint(1,2)==2 and counter!=p else 0)
counter+=1
This question already has answers here:
Computing average of non-zero values
(3 answers)
Closed 3 years ago.
How to get mean from list that is partially empty example [0,2,4,0,4,0,0,0,0,10]
So mean should be (2+4+4+10)/4 = 5 , but statistics.mean() divides by the overall amount of numbers in the list (which in this case is 10).
So in my case I need to get mean from the list of numbers which are divisible by 3 (list b)
import random
import statistics
a = []
b = []
c = [0,2,4,0,4,0,0,0,0,10]
for x in range (10):
a.append(random.randint(0,101))
for x in a:
if x%3==0:
b.append(x)
else:
b.append(0)
average = statistics.mean(b)
print('a',a)
print('b',b)
print('Srednia',average)
You can filter out the zeros from the list using a for-loop perhaps
from statistics import mean
c = [0,2,4,0,4,0,0,0,0,10]
#Filter out 0's
non_zero_c = [item for item in c if item]
#Calculate mean from non zero numbers
print(mean(non_zero_c))
The output will be 5
In alternative to creating a list of only non-zero elements you can count them
non_zero_mean = sum(x) / sum(element != 0 for element in x)
here I'm using the "trick" that from a math point of view in Python (like in C and C++) True == 1 and False == 0.
Another alternative is
non_zero_mean = sum(x) / (len(x) - x.count(0))
Very quickly, the easiest way is to use some list comprehension to select the part of the list that interest you.
Example:
"How to get mean from list that is partially empty example [0,2,4,0,4,0,0,0,0,10] "
a = [0,2,4,0,4,0,0,0,0,10]
a_selection = [elt for elt in a if elt != 0]
m = sum(a_selection)/len(a_selection)
Same for divisible by 3:
b_selected = [elt for elt in b if elt%3==0]
This question already has answers here:
How to get all subsets of a set? (powerset)
(32 answers)
Closed 4 years ago.
[1,2,3]
I have this list and want to print all subsets of this list using recursion. I am getting the output using the following code but is there any better/easier way? Without typecasting it to a set.
def recur_subset(arr):
if len(arr)==0:
print(arr)
else:
for i in range(0, len(arr)):
print(arr[0:i+1])
for j in range(2, len(arr)):
print([arr[0], arr[j]])
return recur_subset(arr[1:len(arr)])
You could use itertools to do the heavy lifting:
import itertools
def recur_subset( s, l=None ):
if l == None:
l = len(s)
if l > 0:
for x in itertools.combinations( s, l ):
print(list(x))
recur_subset( s, l-1 )
Note: This only prints non-empty subsets; add else: print([]) at the end to include the empty subset.
This question already has answers here:
Is there a zip-like function that pads to longest length?
(8 answers)
Closed 6 years ago.
When I run the following code, I seem to 'lose' values, yet I'm not sure why. Are there any other ways to print out two lists next to each other?
What I wish to do is to create a list of integers, from the users input, in a long. It should then separate them into positive and negative values, in ascending order.
The original code is:
import numpy as np
import random
print( "(This will create a list of integers, UserInput long. Then separate"
"\nthem into positive and negative values in ascending order.)")
userI = input("\nHow many integers would you like, between the values of -100 and 100?: ")
userI = int(userI)
Ints = []
for A in range(userI):
Ints.append(random.randint(-100, 100))
print('\n', len(Ints))
def quad(N):
Ints_pos = []
Ints_neg = []
for B in N:
if B >= 0:
Ints_pos.append(B)
else:
Ints_neg.append(B)
return (Ints_pos, Ints_neg)
pos, neg = quad(N = Ints)
pos = sorted(pos)
neg = sorted(neg, reverse=True)
print('\nPositive', ' Negative'
'\nValues:', ' Values:')
for C, D in zip(pos, neg):
print('-> ', C, ' -> ', D)
input("\nPress 'Enter' to exit")
Keep in mind that when using zip:
The iterator stops when the shortest input iterable is exhausted.
You should consider using itertools.zip_longest and provide a dummy value to pad the shorter iterable.
This question already has answers here:
Sort a list to form the largest possible number
(9 answers)
Closed 6 years ago.
x = [9,2,1]
l=[]
for i in range(len(x)):
p = max(x)
l.append(p)
x.remove(p)
print(l)
b = int(''.join(str(n) for n in l))
print(b)
The answer I got is 921
But if the list is [9,2,11].This won't work.
x = [9,2,11]
from itertools import combinations
l=combinations(x, len(x))
print max(map(lambda k: int("".join(map(str,k))),l))
You can use combinations here.
Output:
9211