Why its not printing Pyramid Triangle? - loops

def triangle(rows):
num = rows
for i in range(1 , rows +1 ):
if i == num:
print((x*2 - 1)* "*")
else :
print(" ", end= "")
num -= 1
rows = int(input("How many rows of triangle?\n"))
triangle(rows)
Trial Answer:
First row has 1 star . Second row has 3 star . Third row has 5 star . Fourth row has 7 star and so on.
*
***
*****
*******
*********
Expected Answer:
*
***
*****
*******
*********
Please Give me explanation where my code is wrong because of which I am not getting Answer

Related

Can Someone please explain this Code to me

inputArray=[5, 1, 2, 3, 1, 4]
product = -1000
f = 0
for f in range(len(inputArray)):
try:
if product< inputArray[f] * inputArray[f+1]:
product = inputArray[f] * inputArray[f+1]
print product
except:
'no more'
print product
Result: 5,6
why doesn't it keep multiply the rest of the adjacent elements?
If you'd like that as an official answer, the explanation is below:
It does multiply on every iteration. It just doesn't print and redefine product unless product is less than the value of this iteration multiplied by next iteration. so visualize it like so:
-1000 < 5 so print. now the value of product is 5.
5 > 1 * 2 so do nothing.
5 < 2 * 3 so print. the value of product is now 6.
6 > 3 * 1 so do nothing.
6 > 1 * 4 so do nothing.
So you would have printed only 5 and 6.

pick up the most value element from matix matlab

I have matrix nx3 like this
A = [ 1 3 50;
1 4 80;
1 6 75;
2 3 20;
3 6 10;
6 8 20;
6 9 99;
. . .
. . .
]
I want to check the first index that have same
=> check the third element and pick the maximum value and re arrange matrix
it should be like
Ans = [1 4 80;
2 3 20;
6 9 99;
. . .
]
I was thinking use max() check to on the third element but how can I detect the first element on matrix that are repeated
To produce the same results as Luis Mendo
Ans = sortrows(A, 3);
[~, J] = unique(Ans(:,1));
Ans = Ans(J,:);
%// Obtain unique values of col 1. Each value will determine a group of rows:
ii = unique(A(:,1));
%// For each group of rows, compute maximum of column 3. This is done efficiently
%// with accumarray. Use its sparse option to avoid memory problems , in case
%// values of column 1 are very disperse:
kk = nonzeros(accumarray(A(:,1),A(:,3),[],#max,[],true));
%// Select indices of rows whose column 3 contains the maximum of the group
%// determined by column 1. This is done efficiently using bsxfun twice:
m = any(bsxfun(#eq, A(:,1).', ii) & bsxfun(#eq, A(:,3).', kk));
%// Build result:
result = A(m,:);
In your example:
result =
1 4 80
2 3 20
3 6 10
6 9 99

A case of a making-change (sort of). Find the minimal composition of weights

TLDR: (part 1) Need to print out the best composition of weights to reach a target weight. (part 2) Don't know what approach to choose. (part 3) Also, recursion is not my friend.
I am not asking for a solution, I am just looking for a direction.
PART 1
Some text first.
The input to the program is:
a number of weights
weights themselves
target weights I am supposed to compose
There always has to be a weight that = 1, so all the weights can be composed exactly.
I am supposed to print out the optimal composition of weights, for example
number of weights: 4
weights: 1, 3, 7, 10
target weight: 4
output: 2 x 7
PART 2
The first thing that came to my mind was the unbounded knapsack problem, where I would set all the values for weights to "1" and then I'd look for the lowest possible value in the knapsack. The problem is, my programming skills don't reach that level and my googling skills failed me when I wanted to find a fine article/code/video/whatever to understand it.
Then someone pointed out the making-change problem. The problem there is that it usually uses an array and I am expecting really large numbers, I cannot afford to alloc an array of size = target weight. Also, it seems to require quite a lot of magic if I want not only the lowest possible number of weights, but the exact counts.
My solution now, shall I?
sort the weights in descending order
count the number of weights yielded from the greedy algorithm
remove one biggest weight used and try to compose the weight without it
repeat 3 until I have removed all the "biggest weights" or the number of weights started to grow again
(for weights = 1, 3, 7, 10 and target = 14, greedy would give me 1 x 10 + 1 x 3 + 1 x 1, after the third step I would get (0 x 10 +) 2 x 7)
I got here. Only I need to repeat this not outside the recursive function (like I was doing until I realised it still doesn't give me the right results) but I need to move the loop into the recursive function.
PART 3
This is how parts of my code looks now:
for ( i = 0; i < weights_cnt; i ++ )
for ( j = 0; j <= weight / *(weights + i); j ++ )
{
*counter = 0;
if ( (res = greedyMagicImproved(weights + i, weight / *(weights + i) - j, weight, counter, min)) == 0 || min > *counter ) break;
else min = *counter;
}
It's a mess, I know. (the first recursive function I've ever written, sorry for that)
int greedyMagicImproved (int * weights, int limit, int weight, int * counter, int min)
{
if ( *counter > min ) return 0;
else if ( weight % *weights == 0 )
{
printf ("%d * %d\n", limit, *weights);
*counter += limit;
return *counter;
}
else if ( weight == 0 ) return *counter;
else if ( weight / *weights )
{
printf ("%d * %d + ", limit, *weights);
*counter += limit;
return (greedyMagicImproved(weights + 1, (weight - *weights * limit) / *(weights + 1), (weight - *weights * limit) % *weights, counter, min));
}
else return greedyMagicImproved(weights + 1, weight / *(weights + 1), weight, counter, min);
}
This one produces something like this:
Number of weights:
8
Actual weights of weights:
1 2 4 5 10 20 60 95
Weights to be composed:
124
GREEDY = 1 * 95 + 1 * 20 + 1 * 5 + 1 * 4
IMP = 1 * 95 + 1 * 20 + 1 * 5 + 1 * 4
2 * 60 + 1 * 4
6 * 20 + 1 * 4
... some more irrelevant results I'll deal with later
28
GREEDY = 1 * 20 + 1 * 5 + 1 * 2 + 1 * 1
IMP = 1 * 20 + 1 * 5 + 1 * 2 + 1 * 1
1 * 20 + 1 * 5 + 1 * 2 + 1 * 1
1 * 20 + 1 * 5 + 1 * 2 + 1 * 1
2 * 10 + 1 * 5 + 1 * 2 + 1 * 1
5 * 5 + 1 * 2 + 1 * 1
... some more results as well
While I get to see the correct result in the first case, I do not in the second.
So basically, my question is: Should I try to move the loop part into the recursion (and write it basically all over again because I have no idea how to do it) or should I go stealing/packing and making change?
Here is a DP formulation:
Let w[i], i=0,1,...p be the coin weights and f(t,i) be the number of coins needed to hit target t using only w[k], k >= i. When there is no possible way to make change, then f(t,i) is infinite. With this we know
f(t,i) = min_{n} [ n + f(t - n * w[i], i + 1) ]
In English, to hit the target with the minimum of coins using only coins i, i+1, ... p, choose all possible quantities n of coin i and then use the same DP to make change for the remaining amount using only coins i+1,i+2,..., finally choosing the solution that produced the minimum.
The base cases are common sense. For example f(0,_) = 0. You don't need any coins to hit a target of zero.
If T is the problem target, then the answer will be f(T,0).
Since you don't want the answer, I'll let you convert this to code. It's likely you'll get to answers faster if the weights are sorted in descending order.

matching two files contents using matlab and outputted the result as a matrix

I am new to Matlab. I need your help to solve my problem. I tried to implement several codes but unfortunately I could not be able to find the solution.
I have a file and I need to compare each row with the remaining and output the results as a matrix contains 1s of matched items and 0s otherwise. If two rows are overlapped using the 2 and 3 columns as shown in the example,the matrix has 1 . For example I have the following rows in the file.
1 X 10 20 A
2 Y 15 20 T
3 C 25 40 A
the output should be:
1 2 3
1 0 1 0
2 1 0 0
3 0 0 0
Really I would appreciate any help.
Thanks
That should do it
% open file
fh = fopen('test.txt');
% read data (adjust 10000 if necessary)
dat = textscan(fh, '%d %s %d %d %s', 10000);
% extract high and low values
hi = dat{4};
lo = dat{3};
% create grid
[ hig, log ] = meshgrid(hi, lo');
% compare high, low
overs = ~(log >= hig);
% check both ends & zero out diagonal
res = overs & overs' & ~logical(eye(length(hi)));
% close file
fclose(fh);
res

Algorithm to get the entries of a table?

Say I have this table of non-negative entries:
1 2 3 sum
1 4 5 1 10
2 6 12 7 25
3 0 3 14 17
4 7 2 5 14
sum 17 22 27 66
given:
the number of columns C and number of rows R
the two sums entries (the sum of each row and the sum of each column)
and the total (66 in this example)
The goal is to produce the entries of the table (the inner cells; not the same ones. but, the sum must be equal to the given ones for each row and each column)
all entries must be positive values.
Any pseudo code to do it?
Iterate through the table cells in any order you like. At each step put the largest number there that is still allowed by the two sum constraints.
For example if we go row by row:
10 0 0
7 18 0
0 4 13
0 0 14
Try my pseudo code. This rule named something like "Rule of North-West corner" (I unable find real name of this rule on wiki)
row = 1
col = 1
while (col <= C && row <= R)
Matrix[col, row] = Min(colsum[col], rowsum[row])
colsum[col] = colsum[col] - Matrix[col, row]
rowsum[row] = rowsum[row] - Matrix[col, row]
while (col <= C && colsum[col] == 0) col++
while (row <= R && rowsum[row] == 0) row++
Print Matrix;
Create a set of linear equations like;
X+ Y + .. = sum
For each row and each column.
And solve the using the standard methods of solving linear equations.

Resources