longest increasing subsequence(O(nlogn))

Let’s first look at the n^2 algorithm: Now the improvement happens at the second loop, basically, you can improve the speed by using binary search. Besides the array dp[], let’s have another array c[], c is pretty special, c[i] means: the minimum value of the last element of the longest increasing sequence whose length is … Read more

Backward function in PyTorch

Please read carefully the documentation on backward() to better understand it. By default, pytorch expects backward() to be called for the last output of the network – the loss function. The loss function always outputs a scalar and therefore, the gradients of the scalar loss w.r.t all other variables/parameters is well defined (using the chain rule). Thus, by default, backward() is called on a scalar … Read more

How do you get the magnitude of a vector in Numpy?

The function you’re after is numpy.linalg.norm. (I reckon it should be in base numpy as a property of an array — say x.norm() — but oh well). You can also feed in an optional ord for the nth order norm you want. Say you wanted the 1-norm: And so on.

Converting Hexadecimal String to Decimal Integer

It looks like there’s an extra space character in your string. You can use trim() to remove leading and trailing whitespaces: Or if you think the presence of a space means there’s something else wrong, you’ll have to look into it yourself, since we don’t have the rest of your code.

How to sort Map values by key in Java?

Short answer Use a TreeMap. This is precisely what it’s for. If this map is passed to you and you cannot determine the type, then you can do the following: This will iterate across the map in natural order of the keys. Longer answer Technically, you can use anything that implements SortedMap, but except for rare cases … Read more

Checking if a number is prime in Python

A pretty simple and concise brute-force solution to check whether a number N is prime: simply check if there is any divisor of N from 2 up to the square root of N (see why here if interested). The following code is compatible with both Python 2 and Python 3: And here’s a simpler Python 3 only … Read more