python list permutations [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate all permutations of a list in Python
I am given a list [1,2,3] and the task is to create all the possible permutations of this list.
Expected output:
[[1, 2, 3], [1, 3, 2], [2, 3, 1], [2, 1, 3], [3, 1, 2], [3, 2, 1]]
I can't even think from where to begin. Can anyone help?
Thanks

itertools.permutations does this for you.
Otherwise, a simple method consist in finding the permutations recursively: you successively select the first element of the output, then ask your function to find all the permutations of the remaining elements.
A slightly different, but similar solution can be found at https://stackoverflow.com/a/104436/42973. It finds all the permutations of the remaining (non-first) elements, and then inserts the first element successively at all the possible locations.

this is a rudimentary solution...
the idea is to use recursion to go through all permutation and reject the non valid permutations.
def perm(list_to_perm,perm_l,items,out):
if len(perm_l) == items:
out +=[perm_l]
else:
for i in list_to_perm:
if i not in perm_l:
perm(list_to_perm,perm_l +[i],items,out)
a = [1,2,3]
out = []
perm(a,[],len(a),out)
print out
output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Related

How do I consolidate multiple lists (nested list) into a single list? [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed last month.
for example, I get
[[], [2, 3, 4, 5]]
[[1], [3, 4, 5]]
[[1, 2], [4, 5]]
[[1, 2, 3], [5]]
[[1, 2, 3, 4], []]
And I want to convert first list into [2,3,4,5], next [1,3,4,5], et cetera.
I try to mutiply them all together but of course a list cannot mutiply a interger.
You can use itertools.chain:
>>> from itertools import chain
>>> list(chain.from_iterable([[1, 2], [4, 5]]))
[1, 2, 4, 5]

Counting the frequency of the first element of a list within a list [duplicate]

This question already has answers here:
counting element occurrences in nested lists
(3 answers)
Closed last year.
I'm trying to count the frequency of occurrence of the first element of a list within a list.
the list is:
list = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2], [1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
I want to count the first element of each list within the entire list and print to screen the number that appears the most frequent. Which in this example would be 4.
Any suggestions on how to do this?
If I create a counter to count frequencies using:
Counter(l[0] for l in firstValue).most_common())
If there was 2 or more numbers with the highest frequency of occurrences how would I select the smallest number?
E.g
counter = [(4, 3), (3, 3), (2, 2), (1, 1)]
How would I be able to sort this to print the smallest number that has the greatest frequency of occurrence. (e.g 3 in this example)
Just split your task into a two parts:
Retrieve first element from each inner list;
Sort elements in descending order by number of occurrences.
You can easily find an answer of each of this problem on Stack Overflow:
Extract first item of each sublist;
Sorting a List by frequency of occurrence in a list.
Even question you've additionally answered in comments already have been answered: How to access the first element or number in counter using Python.
You should make some research efforts before asking question otherwise you waste both yours time and time of users who will answer your question.
Anyway, let's go back to your problem.
To get first value of inner list you should iterate over outer list and retrieve first element from every item. With simple for loop it will look like this:
source_list = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
first_items_list = []
for inner_list in source_list:
first_items_list.append(inner_list[0])
You can also use list comprehension:
source_list = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
first_items_list = [inner_list[0] for inner_list in source_list]
Now we have to find max element in list of first items by frequency. To not reinvent the wheel you can apply collections.Counter and specifically it's Counter.most_common() method.
To initialize Counter you need to pass first_items_list generated in code above to Counter() constructor. Then you need to call Counter.most_common() and pass 1 to arguments as you need just most common element:
from collections import Counter
...
counter = Counter(first_items_list)
item, number_of_occurrences = counter.most_common(1)[0]
To simplify the code you can change list comprehension to generator expression and pass it directly into Counter constructor:
source = [[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2],
[1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]
print("Most common:", Counter(inner[0] for inner in source).most_common(1)[0][0])
You can use pandas for this, and the mode() function:
df = pd.DataFrame([[4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 1, 2], [1, 3, 4, 2], [2, 3, 4, 1], [2, 1, 3, 4]]) # creating a dataframe out of your list of list
df[0].mode() # returns an int64 object which is the most frequent item in the column (first column = first element of each of your list)
int(df[0].mode()) # to get the raw int value
Returns:
>>> df[0].mode()
0 4
dtype: int64
>>> int(df[0].mode())
4
Docs:
How to create a dataframe from a list of list: https://stackoverflow.com/a/43175477/2681435
mode() idea: https://stackoverflow.com/a/48590361/2681435

How to get all sub arrays of an array of length 2 or more in efficient way?

array =[1,2,3,4]
Resulting subarray should be...
[1,2],[2,3],[3,4],[1,2,3],[2,3,4],[1,2,3,4]
O(n)? Maybe if you had infinite memory with every possible subarray in the real/imaginary number system stored for efficient accessing, then sure, you can have any complexity algorithm you like.
...But realistically speaking, you're looking at something along the lines of O(n^3), regardless of how efficient you do it.
>>> [lst[i:j + 1] for i in range(len(lst)) for j in range(i + 1, len(lst))]
[[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]]
The one liner hides the two loops and the slicing operation, all of which add layers of complexity. However, it is as efficient and as fast as the underlying algorithm allows it to be.
You cannot get your result in O(N) in any way.
As there are 2^N - 1 - N sub arrays with size > 1, hence the total complexity would be O(2^N) as you have to get all the sub arrays.
For O(2^N) solution, you can search for well known problem of getting power set of a set.
You could always try this itertools.combinations() solution to get all contigous subarrays of length 2 or greater:
>>> from itertools import combinations
>>> array = [1, 2, 3, 4]
>>> [array[start:end+1] for start, end in combinations(range(len(array)), 2)]
[[1, 2], [1, 2, 3], [1, 2, 3, 4], [2, 3], [2, 3, 4], [3, 4]]

How to check if a list has duplicate numbers in Python [duplicate]

This question already has answers here:
How do I check if there are duplicates in a flat list?
(15 answers)
Closed 6 years ago.
So I have a list called puzzle which contains the follow lists:
puzzle = [[1, 3, 5, 5, 4],
[3, 5, 1, 3, 4],
[2, 3, 4, 5, 1],
[1, 5, 3, 2, 2],
[5, 4, 1, 3, 2]]
I would like to check each list inside puzzle and test if there are any duplicate numbers that are not zero, in which case the code would return false. How can I do this?
Almost the same approach -- except that you'd run it on a sub-list without zeros in it.
def has_dup(lst):
no_zeros = [x for x in lst if x != 0]
return len(set(no_zeros)) != len(no_zeros)
is_valid = any(has_dup(x) for x in puzzle)

Turn a list into a tuple of arguments [duplicate]

This question already has answers here:
Expanding tuples into arguments
(5 answers)
Closed 6 years ago.
Python itertools.product() takes coma separated 1D lists and returns a product. I have a list of divisors of a number in a form
l=[[1, a1**1,a1**2,..a1**b1],[1,a2**1,..a2**b2],..[1, an**1, an**2,..an**bn]]
When I pass it to itertools.product() as an argument I don't get the desired result. How can I feed this list of lists of integers to product()?
import itertools
print([list(x) for x in itertools.product([1,2,4],[1,3])])
# [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]] #desired
l1=[1,2,4],[1,3] #doesn't work
print([list(x) for x in itertools.product(l1)])
#[[[1, 2, 4]], [[1, 3]]]
l2=[[1,2,4],[1,3]] #doesn't work
print([list(x) for x in itertools.product(l2)])
#[[[1, 2, 4]], [[1, 3]]]
You need to use *l2 within the product() as * unwraps the list. In this case, the value of *[[1,2,4],[1,3]] will be [1,2,4],[1,3]. Here's your code:
l2 = [[1,2,4],[1,3]]
print([list(x) for x in itertools.product(*l2)])
# Output: [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]]
Please check: What does asterisk mean in python. Also read regarding *args and **kwargs, you might find it useful. Check: *args and **kwargs in python explained

Categories