Getting Information about Optimal Solution from Multidimensional Knapsack Algorithm
I am building a multidimensional knapsack algorithm to optimize fantasy NASCAR lineups. I have the code thanks to another author and am now trying to piece back together the drivers the optimal solution consists of. I have written code to do this in the standard case, but am struggling to figure it out with the added dimension. Here's my code:
#open csv file
df = pd.read_csv('roster_kentucky_july18.csv')
print(df.head())
def knapsack2(n, weight, count, values, weights):
dp = [[[0] * (weight + 1) for _ in range(n + 1)] for _ in range(count + 1)]
for z in range(1, count + 1):
for y in range(1, n + 1):
for x in range(weight + 1):
if weights[y  1] <= x:
dp[z][y][x] = max(dp[z][y  1][x],
dp[z  1][y  1][x  weights[y  1]] + values[y  1])
else:
dp[z][y][x] = dp[z][y  1][x]
return dp[1][1][1]
w = 50000
k = 6
values = df['total_pts']
weights = df['cost']
n = len(values)
limit_fmt = 'Max value for weight limit {}, item limit {}: {}'
print(limit_fmt.format(w, k, knapsack2(n, w, k, values, weights)))
And my output:
Driver total_pts cost
0 A.J. Allmendinger 29.030000 6400
1 Alex Bowman 39.189159 7600
2 Aric Almirola 53.746988 8800
3 Austin Dillon 32.476250 7000
4 B.J. McLeod 14.000000 4700
Max value for weight limit 50000, item limit 6: 325.00072048
I'm looking to at least get the "cost" associated with each "total_pts" in the optimal solution, though it would be nice if I could have it draw out the "Driver" column of the dataframe instead (which I guess could be accessed by indices). Thanks.
See also questions close to this topic

Create new Pandas columns using the value from previous row
I need to create two new Pandas columns using the logic and value from the previous row.
I have the following data:
Day Vol Price Income Outgoing 1 499 75 2 3233 90 3 1812 70 4 2407 97 5 3474 82 6 1057 53 7 2031 68 8 304 78 9 1339 62 10 2847 57 11 3767 93 12 1096 83 13 3899 88 14 4090 63 15 3249 52 16 1478 52 17 4926 75 18 1209 52 19 1982 90 20 4499 93
My challenge is to come up with a logic where both the Income and Outgoing columns (which are currently empty), should have the values of (Vol * Price).
But, the Income column should carry this value when, the previous day's "Price" value is lower than present. The Outgoing column should carry this value when, the previous day's "Price" value is higher than present. The rest of the Income and Outgoing columns, should just have NaN's. If the Price is unchanged, then that day's value is to be dropped.
But the entire logic should start with (n + 1) day. The first row should be skipped and the logic should apply from row 2 onwards.
I have tried using shift in my code example such as:
if sample_data['Price'].shift(1) < sample_data['Price'].shift(2)): sample_data['Income'] = sample_data['Vol'] * sample_data['Price'] else: sample_data['Outgoing'] = sample_data['Vol'] * sample_data['Price']
But it isn't working.
I feel there would be a simpler and comprehensive tactic to go about this, could someone please help ?
Update (The final output should look like this):
For day 16, the data is deleted because we have two similar prices for day 15 and 16.

When I use basemap in python, longitude is sometimes reversed, flipping the map
In python, I use basemap (https://matplotlib.org/basemap/) for plotting spatial data, and I've used it for several years without any large problems. I recently had to reinstall python3 (through conda, along with a number of modules) and basemap now has a strange issue: under certain conditions, the map will be displayed with flipped longitudes, switching east and west. As an example, I use this code: https://matplotlib.org/basemap/users/robin.html. If I use that code asis, the map displays fine, but when I set lon_0=180, the map gets flipped, as shown in the image below.
Setting lon_0 to any positive number results in a flipped map, while 0 or negative numbers result in a correct map. lon_0 should simply set the central longitude of the plotted map, and should not have this behavior, so I'm unsure what's going on. Has anyone seen this behavior before, or have suggestions for how to fix it? I could alter my code to work around it, but I'd rather have things work properly.
I am using python3.7.3. I've tried updating basemap with the command "conda install c anaconda basemap", but it tells me that basemap is up to date already.
Here is the code. It is identical to the code linked above, but with lon_0 set to 180.
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # lon_0 is central longitude of projection. # resolution = 'c' means use crude resolution coastlines. m = Basemap(projection='robin',lon_0=180,resolution='c') m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') # draw parallels and meridians. m.drawparallels(np.arange(90.,120.,30.)) m.drawmeridians(np.arange(0.,360.,60.)) m.drawmapboundary(fill_color='aqua') plt.title("Robinson Projection") plt.show()
When I run the code, the only output is this, which seems unrelated:
map_test.py:36: MatplotlibDeprecationWarning: The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead. m = Basemap(projection='robin',lon_0=180,resolution='c')
Any ideas?

Use format() on variables
Is it possible to use "{}".format() logic but instead of "", to use a variable?
x = 1 y = 2 a = 'some {} random {} text' print(a.format(x, y))
I expect the following output:
some 1 random 2 text

Most Influencer City
My Problem goes like this:
Suppose the cities of world, each city has a degree of economic collaboration with other cities. I need to detect communities such that the degrees among different cities maximized, also I need the most influencer city which has as much degree with different cities as possible and if happened that two cities in the same community has the same value, then the maximum of one make it the winner.
I know this is typical situation for SNA, but I don't know which algorithm will serve my purpose more. so I need the guidance for that. and thank you in advance.

Return Rowland Sequence without the 1's
I have this homework problem where I'm required to write a method that calculates the difference between each 2 numbers in the Rowland's prime generating sequence and return the results without the 1's.
I tried doing a "for" loop and in it an "if" statement but it didn't really go anywhere (I'm a java newbie) so I resorted to a "dowhile" statement that is almost complete (I think) but I don't think it would really serve the purpose.
public static int removeone(GCD gcd, int n) { int sub; do { sub = removeone(gcd, n)  removeone(gcd, n  1); n++; } while (sub == 1); return sub;
now I believe this code will instead change the initial value of n entered (at least i think so) and of course I dont want that. So how should I make it return the sequence without the 1's, or omit the 1's from the sequence.
EDIT: for reference : http://oeis.org/wiki/Rowland%27s_sequence

What's wrong with this algorithm to adjust position x units 90 degrees relative to current angle?
Let's say I'm at (0, 0) (
this.location = { x: 0, y: 0 }
) and when I update my position (value = 1
orvalue = 1
) I want to move to the left or right (panning sideways) relative to the direction I'm facing. This function seems to work only if I'm facing a specific angle:updatePosition(value) { let angle = toRadians(this.angle  90); this.location.x += Math.cos(angle) * value; this.location.y += Math.sin(angle) * value; }
What's wrong with this? How can I fix it so that it always adjusts my position to the left or right of me relative to the angle I'm currently facing?
Example:
function toRadians(degrees) { return (degrees * Math.PI) / 180; } class Player { constructor() { this.angle = 0; this.location = { x: 0, y: 0 }; } updatePosition(value) { let angle = toRadians(this.angle  90); this.location.x += Math.cos(angle) * value; this.location.y += Math.sin(angle) * value; } } let player = new Player(); // desired output: { x: 0, y: 0 } console.log("starting location:", player.location); // pan 1 unit to the right player.updatePosition(1); // desired output: { x: 1, y: 0 } console.log("new location 1:", player.location); // rotate 90 degrees player.angle = 90; // pan 1 unit to the right player.updatePosition(1); // desired output: { x: 1, y: 1 } console.log("new location 2:", player.location);

How do I perform One Hot Encoding on lists in a pandas column?
Suppose I have a dataframe of which one column is a list (of a unknown values and length) for example:
df = pd.DataFrame( {'messageLabels': [['Good', 'Other', 'Bad'],['Bad','Terrible']]} )
I came across this solution but it isnt what I am looking for. How best to extract a Pandas column containing lists or tuples into multiple columns
in theory the resulting df would look like
messageLabels  Good Other Bad Terrible  ['Good', 'Other', 'Bad']  True True True False  ['Bad','Terrible'] FalseFalse True True
See above

Counting distinct using pandas groupby not working
All I am trying to do is iterate through a DataFrame and count the number of unique values using the pandas group by. I also sorted the data frame to no avail.
I've tried 15 different methods and have read every question/response thread I can find, and I have no idea why it isn't working.
Code to create the DF:
#list of queries is literally a python list of queries in no specified #order user_queries = pd.DataFrame(list_of_queries) user_queries = user_queries.rename(index=str, columns={0: "queries"}) # I only added the int 1 because pandas refused to just count the #queries themselves user_queries["count"] = 1
What it looks like before the groupby code
queries count 1234 test 1 1234 test 1 user_queries["query_counts"] = user_queries.groupby("queries")["count"].nunique() user_queries.head()
What it should look like
 ,queries,count,query_counts 1234,test ,1 ,2 
But instead of the "2", it gives me NaNs for every value instead. I feel like I'm missing something simple, but
The last column should have the sum of the column "count" grouped by the column "queries"

How to implement neural network pruning?
I trained a model in keras and I'm thinking of pruning my fully connected network. I'm little bit lost on how to prune the layers.
Author of 'Learning both Weights and Connections for Efficient Neural Networks', say that they add a mask to threshold weights of a layer. I can try to do the same and fine tune the trained model. But, how does it reduce model size and # of computations?

autoptimize + cache enabler: randomly single pages don't load stylesheet
To improve page speed and user experience, I've tested many plugins dedicated for this. So based on real results and many online testing (gtmetrix, google pagespeed, webpagetest) I moved to Autoptimize + Cache Enabler plugin solution.
1) What happens
I don't know why but randomly, only on some pages or only one, the content is loaded but completely without any css stylesheet, so the page comes out quite empty and all is messed up. Last time it happened, I've examined the page with chrome dev tools and I've noticed which the all autoptimize's stylesheets weren't there: like the site doesn't have any of my css.
Clearing first the cache of "Cache enabler" then the cache of "Autoptimize" everything turned nice again.
2) The problem
I think this happened after wordpress autouptades, but I'm not sure. Anyway, the real problem is that if it happens randomly and not only with WP updates, I can't control the situation and know when purge the cache and when not. So I could have "blank" pages for weeks and don't know anything about it: bounce +1000% :)
I've already set time duration of cache from "Cache Enabler" setting on 48h, so it should refresh automatically. Is it the right time to set? I cannot make the same for "Autoptimize" plugin because it does not provide this option of autopurge.
Before I change everything and move to other plugins and many other tests, does anybody know why this is happening and how I can fix it? Maybe disabling some optimizing setting on both plugins?
P.S. Unfortunately I can't provide you with the error page because it happens randomly and I can't generate the error by myself.
Autoptimize + cache enabler problems (maybe plugin configuration settings?)

Count the number of words & lines that has multiple vowels in python
I am working on this coding problem "Count the number of words & lines that have more than X vowels for every Y words in every Z line"
Basically the input string has multiple lines and I need to count words that has X or more vowels in them. But the constraint is I need to consider only alternate Zth line as well as alternate Yth word in those Zth lines. For e.g. let's say I need to count every 3rd word that has 2 or more vowels in every 3rd line. So here
X=2
,Y=3
,Z=3
. Check below input string:"1.When I first brought my cat home. 2.It cost a lot to adopt her. 3.I paid forty dollars for it. 4.And then I had to buy litter, a litterbox. 5.Also bought food, and dishes for her to eat out of. 6.There's a **leash** law for cats in Fort **Collins**. 7.If they're not in your yard they have to be on a leash. 8.Anyway, my cat is my best friend. 9.I'm glad I got her. 10.She sleeps under the covers with me when it's cold."
Output: Word Count: 2, Line Count: 1
So based on criteria of
Z=3
i.e. count every 3rd line so the lines to be considered areline number 3, 6, 9
. Also in these lines we need to countY=3 i.e. every 3rd word
. So words to be considered are"forty, it" from line 3
,"leash, cats, Collins" from line 6
and"I" from line 9
. Given this criteria, the matching words with 2 or more vowels are found only in line 6 with words"leash"
and"Collins"
so the output is WordCount = 2 and LineCount = 1.This is my first time writing anything in Python so wrote the basic below code:
class StringCount: #Count the number of words & lines that have more than X vowels for every Y words in every Z line. lines = list(); totalMatchedLines = 0; totalMatchedWords = 0; matchedChars = 0; def __init__(self, inputString, vowelCount, skipWords, skipLines, wordDelimiter, lineDelimiter): self.inputString = inputString; self.vowelCount = vowelCount; self.skipWords = skipWords; self.skipLines = skipLines; self.wordDelimiter = wordDelimiter; def splitLines(self): if self.inputString.strip() == "": print ("Please enter a valid string!"); return False; self.lines = self.inputString.splitlines(); def splitWords(self): self.matchedWords = 0; self.matchedLines = 0; self.linesLength = len(self.lines); if self.linesLength < self.skipLines: print ("Input string should be greater than {0}" .format(self.skipLines)); return False; lineCount = self.skipLines  1; wordCount = self.skipWords  1; lineInUse = ""; words = list(); while (lineCount < self.linesLength): self.matchedWords = 0; self.matchedLines = 0; self.words = self.lines[lineCount].split(); self.wordsLength = len(self.words); wordCount = self.skipWords  1; while (wordCount < self.wordsLength): self.matchedChars = 0; for i in self.words[wordCount].lower(): if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u'): self.matchedChars += 1; if self.matchedChars >= self.vowelCount: self.matchedWords += 1; wordCount += self.skipWords; if self.matchedWords > 0: self.matchedLines += 1; self.totalMatchedWords += self.matchedWords; self.totalMatchedLines += self.matchedLines; lineCount += self.skipLines; print ("WordCount = %s" % (self.totalMatchedWords)); print ("LineCount = %s" % (self.totalMatchedLines));
Since this is my first Python code, I wanted to check how to optimize this code in both performance and line optimization. Are there any tricks to shorten the multiple while loops and a for loop?
Any help is appreciated!

Multiple knapsack problem with equal profit and different weight
I am researching the load balancing problem in 5G system, but I am not sure if my problem is a NPcomplete problem.
The problem is: given a set of n items and a set of m knapsacks capacity of knapsacks are equal. 3. the weight of item j in knapsack i is w[i][j],that means weight of a item in each knapsack are different. 4. each profit of items are equal.
I am not trying to put all item in least knapsack like bin packing problem. I saw some similar question answered, but no one is identical to this case. In this case, the goal is to put as more as possible item with m knapsacks. Is the problem a NPcomplete problem?

Knapsack problem understanding a question
I don't understand this question and I would really appreciate it if someone could help. So it starts off with explaining the Knapsack Problem then it asks me to write a function that calculates the mean of each sample. Does this mean all I need to do is write a function that takes an array (argument list) of arrays (Xi's) and returns the means of all the arrays (Xi's) in argument list? This is what I've understood from this question but I don't think it is that simple or correct as it doesn't make any use of the Knapsack problem details.

Dynamic Programming Problem "Total rating must be highest after buying players with input price"
Players Input Table The problem is making total rating maximum , while buying one player from each position with some price. For example 29000€. You can use 27000€ but you can't use 29001€.
Note: You can only buy one player from each positions so if there are 6 positions and each position has 10 players , count of all possibilities is 11^6
All i can see is knapsack problem but i think there should be some great solution for this problem.
I already tried knapsack algorithm but it didn't work well for bigger inputs like 11 positions and each position have 50 players to check.
int DP() { int price = 29000; int positions = 3; // I tried this approach , it is unfinished though. int players = 3; int ratings[][] = new int[positions][players]; int prices[][] = new int[positions][prices]; int K[][][] = new int[positions][price][players]; for(int i = 0; i <= positions; i++) { for(int j = 0; j<=players; j++) { for(int w = 0; w<=price; w++) { if(i==0j==0w==0) // Base case. K[i][j][w]=0; else if(prices[i1][w1] <=w) K[i][j][w] = max(ratings[i1][j1] + K[i1][j1][wprice[i1][j1]], K[i1][j1][w]; else K[i][j][w] = K[i1][j1][w]; } } } return K[positions][players][price]; }
Example Output:
Enter the amount to spend (X): 100 000 Enter the number of the positions (N): 6 //The first N position Enter the number of the available players for each position (K): 5 // The first K players of each position DP results: Total ratings : 547 Total cost: 98 925 Players: 1Gianfranco Zola 2Jimmy Floyd Hasselbaink 3... 4...