Using for loops and nested lists in python - list

I am trying to add each row of nested loop independently in order to find averages. I am missing a detail which may or may not derail my whole code.The code should compute the average of a given row of scores but drops the lowest grade.
def printAverages():
scores = [[100,100,1,100,100],
[20,50,60,10,30],
[0,10,10,0,10],
[0,100,50,20,60]]
total = 0
minValue = 100
counter = -1
for row in scores:
counter = counter + 1
for n in scores[0]:
total = total+n
if minValue > n:
minValue = n
total = total - minValue
print("Average for row",counter,"is",total)
total = 0
How do i make it so for n in score [0] takes the average of each row instead of only computing the average of the first row? I know that scores[0] commands the program to only read the first row, I just don't know how to change it.
Thank you

Remember, the XY problem.
# Sum of a list of numbers divided by the number of numbers in the list
def average(numbers):
return sum(numbers)/len(numbers)
# This is your data
scores = [[100,100,1,100,100],
[20,50,60,10,30],
[0,10,10,0,10],
[0,100,50,20,60]]
# enumerate() allows you to write FOR loops naming both the list element and its index
for (i, row) in enumerate(scores):
print("Average for row ", i, "is ", average(row))
Keep in mind that Python supports functional programming and encourages the programmer to write pure functions when possible!

the statement for n in scores[0]: will only go through the first column.
What you want it to say is for n in row:. That will have it go through each row, one row per loop of the outer loop

Related

How do i solve these variations of the 0-1 knapsack algorithm?

The knapsack can carry a maximum weight , say max_wt ; has n items with a given weightwt[] and a valueval[].I have two questions ( both seperate from each other ) :
What is the maximum value we can carry if there was a second limit to the volume we could carry , vol[ ] ?
What are the number of ways to carry a total of exactly z(< n) items such that their sum of values is divisible by a number , say 8 ?
My Attempt
For the first question i refered this stackoverflow post , but the only answer i could understand was one where the two constraints were merged ,but the run time complexity of that would be quite big i guess...what i was thinking was making a dp[i][j][k] , where i is the number of items selected , j is the max-wt selected at that point , k is the max-vol selected at that point and then my core of the code looked like
for(i=0 ; i < n ; i++) \\ n is no. of items
for(j=0 ; j < n ; j++)
for(k=0 ; k < n ; k++)
dp[i][j][k] = max( dp[i-1][j][k] , val[i] + dp[i-1][j-wt[j]][k-vol[k]]) ;
, this seems alright , but gives me wrong answer ... i cant guess why :(
I can't start to think of the second problem, my friend did it by taking three states dp[i][j][k] where i and j are just same as first question(the usual ones) while 'k' keeps track of the total items selected , this idea isnt getting in my head . Plus , what will a state store , it usually stores max value possible till given state in classical knapsack problems , here i guess a state will store total combinations divisible by 8 till that state , but i cant convert this into code .
p.s please try providing a solution with bottom up approach to the second question , i am very new to dynamic programming . ;)
Two-dimensional knapsack problem
let n be the number of items
let val[i] be the value of the i-th item
let w[i] be the weight of the i-th item
let v[i] be the volume of i-th item
let T[i,j,k] be the best value out of the first i items and having exactly weight j and volume k. T can be defined in some other way but this definition gives a short formula.
Finding best value
T[0,j,k] = 0
T[i,j,k] = T[i-1,j,k], when j<w[i] or k<v[i], otherwise:
T[i,j,k] = max( T[i-1,j,k] , T[i-1,j-w[i],k-i] + val[i] )
best possible value would be max T[n,j,k] for all j and k
Implementation notes
initialize base cases first for all j and k
loop i from 1 to n and be consistent with 1-based arrays indexes
loop j from 1 to max possible weight which is the sum of all weights, e.g. w[1]+w[2]+...w[n]
loop k from 1 to max possible volume
Counting number of ways to get an exact value with an exact number of items
let S[i,j,k,l] be the number of ways in which the first i items can be arranged with exactly weight j, value k, and l items.
S[0,j,k,l] = 0, except S[0,0,0,0] = 1
S[i,j,k,l] = S[i-1,j,k,l] + S[i-1,j-w[i],k-val[i],l-1]
number of ways to get exactly value y using exactly z items is the sum of T[n,j,y,z] for all j
Observations
There are many ways to look at these problems and to define the states T and S. This is but one of them. Implementations can also differ. The thumb-rule for dimensions is that another constraint in the sack or dimension in the items means another dimension in the formula. The thumb-rule for counting ways is that you add up instead of finding max.

To make an array non-decreasing using dynamic programing

I came accross this question in a programming contest, i think it can be solved by DP but cannot think of any, so plz help. Here's the questn :
There are n stack of coins placed linearly, each labelled from 1 to n. You also have a sack of coins containing infinite coins with you. All the coins in the stacks and the sack are identical. All you have to do is to make the heights of coins non-decreasing.
You select two stacks i and j and place one coin on each of the stacks of coins from stack'i' to stack'j' (inclusive). This complete operations is considered as one move. You have to minimize the number of moves to make the heights non-decreasing.
No. of Test Cases < 50
1 <= n <= 10^5
0 <= hi <= 10^9
Input Specification :
There will be a number of test cases. Read till EOF. First line of each test case will contain a single integer n, second line contains n heights (h[i]) of stacks.
Output Specification :
Output single integer denoting the number of moves for each test case.
for eg: H={3,2,1}
answer is 2
step1: i=2, j=3, H = {3,3,2}
step2: i=3, j=3, H = {3,3,3}

Computing avg test scores using a while loop

Ok so, I am trying to write a program using a 'while' loop to compute the the average of a certain # of test scores. My 1st input is the amount of tests, and every input afterwards is a set of scores (so say 1st input is 5, then the next 5 inputs are 5 different test scores). I have to input all the variables at once in order to find the sum of all the test scores and then the computed average.
I am completely stuck on how to do this and don't even know where to start.
Some pseudocode
total <- 0
N <- input number of tests
i <- 1
while i <= N
data[i] <- input data
total <- total + data[i]
i <- i + 1
avg <- total / N
To get you started but not give too much away...
To do this the way I think you want to do this:
First take input for the # of tests.
Cin >> test_amt;
Okay, so now you know how many tests there are. Great! So now you should use a while loop to go through each test and take in input for the score! I would use a for loop here, but if you want to use a while loop, then sure.
counter = 0;
while(counter != test_amt-1)
{
cin >> score;
//I would use a vector to store each score.
//this way, you easily know which score matches up with which test
score = 0;
counter++;
}
I hope this can get you started. If not, just let me know and I would be glad to help more.
You can store scores in a std::vector and calculate the sum with std::accumulate.
Take all the scores in a single variable by adding them one after other and finally get the average. Below I have given a hint that will help you to use while loop. But you can use your own logic for it:
int test_amount, counter = 0, total = 0, score;
int avg;
cout<<"Enter test amount"<<endl;
cin>>test_amount;
while(counter < (test_amount-1))
{
cout<<"Enter the test score"<<endl;
cin>>score;
total=total+score;
counter++;
}
avg = total/test_amount;
If you wish to store the scores as well you may think of vector or array. As the number of 'test amount' is not fixed, you can also go for dynamic array, linked list etc. Think about other approaches, post your own code and Google is also there with all kind of help.

Efficient method for finding the middle k-combination of n sorted elements

Suppose that I have a sorted array, N, consisting of n elements. Now, given k, I need a highly efficient method to generate the k-combination that would be the middle combination (if all the k-combinations were lexicographically sorted).
Example:
N = {a,b,c,d,e} , k = 3
1: a,b,c
2: a,b,d
3: a,b,e
4: a,c,d
5: a,c,e
6: a,d,e
7: b,c,d
8: b,c,e
9: b,d,e
10: c,d,e
I need the algorithm to generate combination number 5.
The Wikipedia page on the combinatorial number system explains how this can be obtained (in a greedy way). However, since n is very large and I need to find the middle combination for all k's less than n, I need something much more efficient than that.
I'm hoping that since the combination of interest always lies in the middle, there is some sort of a straightforward method for finding it. For example, the first k-combination in the above list is always given by the first k elements in N, and similarly the last combination is always given by the last k elements. Is there such a way to find the middle combination as well?
http://en.wikipedia.org/wiki/Combinatorial_number_system
If you are looking for a way to obtain the K-indexes from the lexicographic index or rank of a unique combination, then your problem falls under the binomial coefficient. The binomial coefficient handles problems of choosing unique combinations in groups of K with a total of N items.
I have written a class in C# to handle common functions for working with the binomial coefficient. It performs the following tasks:
Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters.
Converts the K-indexes to the proper lexicographic index or rank of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle and is very efficient compared to iterating over the set.
Converts the index in a sorted binomial coefficient table to the corresponding K-indexes. The technique used is also much faster than older iterative solutions.
Uses Mark Dominus method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.
The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to use the 4 above methods. Accessor methods are provided to access the table.
There is an associated test class which shows how to use the class and its methods. It has been extensively tested with several cases and there are no known bugs.
To read about this class and download the code, see Tablizing The Binomial Coeffieicent.
The following tested code will calculate the median lexicographic element for any N Choose K combination:
void TestMedianMethod()
{
// This test driver tests out the GetMedianNChooseK method.
GetMedianNChooseK(5, 3); // 5 choose 3 case.
GetMedianNChooseK(10, 3); // 10 choose 3 case.
GetMedianNChooseK(10, 5); // 10 choose 5 case.
}
private void GetMedianNChooseK(int N, int K)
{
// This method calculates the median lexicographic index and the k-indexes for that index.
String S;
// Create the bin coeff object required to get all
// the combos for this N choose K combination.
BinCoeff<int> BC = new BinCoeff<int>(N, K, false);
int NumCombos = BinCoeff<int>.GetBinCoeff(N, K);
// Calculate the median value, which in this case is the number of combos for this N
// choose K case divided by 2.
int MedianValue = NumCombos / 2;
// The Kindexes array holds the indexes for the specified lexicographic element.
int[] KIndexes = new int[K];
// Get the k-indexes for this combination.
BC.GetKIndexes(MedianValue, KIndexes);
StringBuilder SB = new StringBuilder();
for (int Loop = 0; Loop < K; Loop++)
{
SB.Append(KIndexes[Loop].ToString());
if (Loop < K - 1)
SB.Append(" ");
}
// Print out the information.
S = N.ToString() + " choose " + K.ToString() + " case:\n";
S += " Number of combos = " + NumCombos.ToString() + "\n";
S += " Median Value = " + MedianValue.ToString() + "\n";
S += " KIndexes = " + SB.ToString() + "\n\n";
Console.WriteLine(S);
}
Output:
5 choose 3 case:
Number of combos = 10
Median Value = 5
KIndexes = 4 2 0
10 choose 3 case:
Number of combos = 120
Median Value = 60
KIndexes = 8 3 1
10 choose 5 case:
Number of combos = 252
Median Value = 126
KIndexes = 9 3 2 1 0
You should be able to port this class over fairly easily to the language of your choice. You probably will not have to port over the generic part of the class to accomplish your goals. Depending on the number of combinations you are working with, you might need to use a bigger word size than 4 byte ints.

Number of Items in a Column inside a grid

How do you find number of items in a column inside a grid?
I have a grid (listview control to be specific), and have some items.
Some times a given row might not be full. ANd can have values in fewer than maximum columns. I need to find Number of items in a given Column.
If the grid is like
1 2 3
4 5 6
7
and if input column is 1, then we need to output 3, and 2 for input of 2 or 3.
I have variables to for ItemCount, CoulmnCount and RowCount which track number of items, rows and columns.
A very rudimentar way would be something like this:
int iItemCount=0,iItemInColumn=0;
for(int iCol=0;iCol<iColumnCount;iCol++)
for(int iRow=0;iRow<iRowCount;iRow++,iItemCount++)
if(iCol==iInputCol && iItemCount<iTotalItems)
iItemInColumn++;
Can you guys think of any sophesticated way, which does not need loops? possible utilizing just 3 variables which I already have for tracking?
Assuming 0-based indexes:
def itemsInColumn(itemCount, columnCount, inputColumn):
lastItemColumn = (itemCount - 1) % columnCount
if inputColumn <= lastItemColumn:
return (itemCount + columnCount - 1) / columnCount
else:
return itemCount / columnCount
It depends on the total number of items (itemCount) and the number of columns (columnCount). It just computes itemCount / columnCount, and rounds up or down depending on whether the input column is less than or equal to the last item's column.
The computation "(itemCount + columnCount - 1) / columnCount" is just a trick for rounding up using integer division. In general, given positive integers a and b: ceil(a / b) = (a + b - 1) div b, where div is integer division.