Use numpy to generate all possible combinations in a range using numpy in python
Is there a faster way to generate possible combinations without repetitions in numpy? For example, if I needed all 3 number combinations in range(1,5) I will get (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4).I'm using the following code which works but is quite slow for me and am wondering if there's a faster method:
from itertools import *
result=[]
for c in combinations(range(1,48), 6):
result.append(c)
See also questions close to this topic

Getting nan in tensorflow
I wanted to build a simple machine learning model with tensorflow so that I could understand the process of machine learning and be able do stuff myself.
The dataset that I decided to use are from kaggle.
https://www.kaggle.com/andonians/randomlinearregression/version/2
Since I'm a beginner I didn't want to divide the dataset into 2 parts, namely training and validation.
My code is as follows
train=train.reindex(np.random.permutation(train.index)) train['x']=train['x']/(train['x'].max()) train['y']=train['y']/(train['y'].max()) train_features=np.array(train[['x']]) train_label=np.array(train[['y']]) train_features=tf.convert_to_tensor(train_features) train_label=tf.convert_to_tensor(train_label) w=tf.convert_to_tensor(tf.Variable(tf.truncated_normal([1,700],mean=0.0,stddev=1.0,dtype=tf.float64))) b=tf.convert_to_tensor(tf.Variable(tf.zeros(1,dtype=tf.float64))) def cal(x,y): prediction=tf.add(tf.matmul(w,x),b) error=tf.reduce_mean(tf.square(yprediction)) return [prediction,error] y,cost=cal(train_features,train_label) learning_rate=0.05 epochs=3000 init=tf.global_variables_initializer() optimize=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) with tf.Session() as sess: sess.run(init) for i in list(range(epochs)): sess.run(optimize) print(sess.run(cost))
But the output that I get is nan. nan all the way upto 3000 lines( epochs is 3000).
I can't seem to figure out the reason. I even tried to run it without normalization i.e. without converting the values between 0 and 1. I have also decreased the learning rate to 0.0005. But it seems to have no effect.
Thanks in advance.
P.S. I have not included the test set as I first want to train and see if it works. I will add it later.

How does self.next = None store the address of next value in the linked list?
I am new to classes in Python. I am trying to implement linked lists. Can someone please explain to me how self.head.next.value outputs the next value in the list? Even though next is assigned to none but somehow it is able to print the right answer. I saw a similar post here How does self.next = None get the next value of l1? but the answer was not properly explained since I am not assigning anything to self.next.
class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element l = LinkedList(Element(1)) l.append(Element(2)) print (l.head.next.value)
The output shows : 2

Getting "SettingWithCopyWarning" while performing one hot encoding with pandas
I encountered the
SettingWithCopyWarning
in Python. I searched online but it seems that all the solutions do not work for me.The input data is like this:
id genre 0 1 Drama, Romance 1 2 Action, Drama 2 3 Action, Comedy 3 4 Thriller
The expected outcome should be:
id Drama Romance Action Comedy Thriller 0 1 1 1 0 0 0 1 2 1 0 1 0 0 2 3 0 0 1 1 0 3 4 0 0 0 0 1
I want to get the subset of the input data, add some columns and modify the added column, and return the subset. Basically, I DO NOT want to modify the original
data
, I just want to get a subset, which should be a brand new dataframe :# the function to deal with the genre def genre(data): subset = data[['id', 'genre']] for i, row in subset.iterrows(): if isinstance(row['genre'], float): continue genreList = row['genre'].split(', ') for genre in genreList: if genre in list(subset): subset.loc[i][genre] = 1 else: subset.loc[:][genre] = 0 subset.loc[i][genre] = 1 return subset
I tried many ways, but neither of them gets rid of the
SettingWithCopyWarning
:subset = data[['A', 'B']].copy()
.subset = data.filter(['A','B'], axis=1)
subset = pd.Dataframe(data[['A', 'B']])
subset = data.copy()
subset.drop(columns =['C','D'])
subset = pd.DataFrame({'id': list(data.id), 'genre': list(data.genre)})
Does anyone have any idea how to fix this? Or is there a way to surpress the warning?
Thanks in advance!!

How does a numpy view know where the values it's referencing are in the original numpy array?
As I understand it, a numpy array is an object storing values in a contiguous block of memory, while Python's builtin containers (list, tuple, set, dict) contain references to objects. Basic slicing of a numpy array returns a view containing a specified subset of those values.
On the surface, the view looks like another numpy array (type(aView) returns numpy.ndarray), but its values are not copies but rather the same values as those of the original array; altering the values of a view inplace alters the values of the original array as well.
How does a view do this? I would imagine a view should contain some sort of pointers to the values in the original array, but a couple things give me pause:
The values in the array aren't objects, and I don't know how references can be made to small pieces of the same object.
creating a copy of an array is much slower than making a view, and if the view is just an array of some sort of pointer values, I would expect both copies and views to be made with about the same speed.

After running the function, the function became an ndarray
I'm trying to write a code with exec and eval function to read lists of variables from a numpy .npz file.
See a previous post: With Michael Butscher's help exec name "templet_1h" is not defined , the function now is working. However, I met another awkward situation.
Before I execute the function type(read_file) was a function, after I excute the function type(read_file) became a class "numpy.ndarry".
Can someone help me to explain it a bit? How to solve it?
def read_file(file_names_2): global templet_1h import numpy as np Delete_elements=["arr_0"] evaluate_1= "templet_1h=np.load(\"./" +file_names_2+ ".npz\")"; exec(evaluate_1,globals()) for i in (templet_1h.files): if not ( (i in Delete_elements) ): evaluate_2= i+"="+"templet_1h[\"" + i + "\"]"; exec(evaluate_2,globals()) del templet_1h return

ValueError: Error when checking input: expected input_1 to have shape (256, 256, 1) but got array with shape (259, 259, 1)
ValueError: Error when checking input: expected input_1 to have shape (256, 256, 1) but got array with shape (259, 259, 1)

Having a table of elements equality , calculate number of "unique" elements
I have two tables: table of product ids:
table p_test:
id: 1 2 3 4
and a table of all possible combinations of a product tested with every other product for equality (let't say I test their pictures and if the pictures are equal  I assume they are same product): table p_match_test:
p_id_1, p_id_2, is_same 1 2 0 1 3 0 1 4 1 2 3 1 2 4 0 3 4 0
as you can see in this example there is total of 4 products. Product 1 was tested for equality with product 4 and they were found "same", same thing about products 2 and 3. This means that there are only two "unique" products (2 unique pictures for 4 products).
What I want to achieve is to have a count of unique pictures in any group of products so the result will be:
products_count unique_products_count 4 2
I tried this query:
select count(p.id) as products_count, sum(if(not exists(select * from p_match_test t where (p.id = t.p_id_1 or p.id = t.p_id_2) and t.is_same = 1), 1, 0)) as unique_products_count from p_test p
but it counts only products that have no duplicates instead of counting "unique" images. How do I achieve my goal?

Find every possible disposition of elements in a list keeping elements and list length
I would like to find every combination of elements in a list, by switching the order of the elements, while keeping their count and the length of the list.
For example, for the list:
[1,2,1,3]
I would like to obtain the following:
[1,1,2,3] [1,1,3,2] [1,2,1,3] [1,2,3,1] [1,3,1,2] [1,3,2,1] [2,1,1,3] [2,1,3,1] [2,3,1,1] [3,1,1,2] [3,1,2,1] [3,2,1,1]
Be aware that same elements, such as the two 1 in the original list, are not seen as separate ones, so the two possibilities
[1a,1b,2,3]
and[1b,1a,2,3]
must be counted as one 
Calculate possible combinations of banknotes in Java
I have this question: how can I calculate all the possible combinations of banknotes in Java given a number of banknotes? The output should be like this:
You can only use bills of 20€, 50€ and 100€.
200€ = 10 * 20€
200€ = 5 * 20€ + 2 * 50€
200€ = 2 * 100€
...
I cannot think about a solution for this. Thanks.