I am looking for a Pascals triangle using python script
I have done till here and have no idea how to add on
numstr= raw_input("please enter the height:")
height = int( )
tri = []
row1 = [1]
row2 = [1, 1]
tri.append(row1)
tri.append(row2)
while len(tri) < height:
You would have to take the last row there is in the triangle and create the next one like this:
Put a 1 at the start of the new row
For every number in the last row except the last, calculate the sum of the number and its right neighbor and put it into the new row
Put another 1 at the end of the new row
You could also calculate the new numbers using binomial coefficients, though that's likely a little more work to get right.
Here's the correct way to make pascal's triangle.
http://ptri1.tripod.com/
http://en.wikipedia.org/wiki/Pascal%27s_triangle
Actually, the next row is crossed axis sum of last row. For example, if the last row is [1, 1], the next row would be:
[1, 1]
+ [1, 1]
-----------
= [1, 2, 1]
[1, 2, 1]
+ [1, 2, 1]
--------------
= [1, 3, 3, 1]
So, the loop body can be like this:
tri.append(map(lambda x, y: x + y, [0] + tri[-1], tri[-1] + [0]))
try the scipy pascal module:
from scipy.linalg import pascal
pascal(6, kind='lower')
output:
array([[ 1, 0, 0, 0, 0, 0],
[ 1, 1, 0, 0, 0, 0],
[ 1, 2, 1, 0, 0, 0],
[ 1, 3, 3, 1, 0, 0],
[ 1, 4, 6, 4, 1, 0],
[ 1, 5, 10, 10, 5, 1]], dtype=uint64)
here is my solution to generate a pascal triangle
def factorial(x):
return 1 if x == 0 else x * factorial(x - 1)
def triangle(n):
return [[factorial(i) / (factorial(j) * factorial(i - j)) for j in range(i + 1)] for i in range(n)]
This is python code for Pascal's triangle:
# python code for Pascal's Triangle
# printPascal() function for printing pascal's triangle.
def printPascal(N):
# declaring 2 array
arr = [1]
temp = []
print("pascal's triangle of", N, "Rows...")
# calculating next rows.
for i in range(N):
# printing current row.
print("rows", i+1, end=" : ")
for j in range(len(arr)):
print(arr[j], end=' ')
print()
# calculating next rows.
temp.append(1)
for j in range(len(arr)-1):
temp.append(arr[j] + arr[j + 1])
temp.append(1)
# copy next row to current row.
arr = temp
# initialize temp to empty array.
temp = []
# Driver code
N = 9
printPascal(N)
For more details:https://algorithmdotcpp.blogspot.com/2021/07/print-n-rows-of-pascals-triangle-in-cpp-and-python.html
// C++ code for pascal triangle
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
long unsigned int Factorial(long unsigned int Number)
{
long unsigned int Fact=0;
if (Number==0)
return (long unsigned int) 1;
else
{ Fact=Number*Factorial(Number-1);
return Fact;
}
}
long unsigned int Combination(long unsigned int num1,long unsigned int num2)
{
long unsigned int Comb,num3;
long unsigned int Factor1, Factor2,Factor3;
Factor1=Factorial(num1);
Factor2=Factorial(num2);
num3=num1-num2;
Factor3=Factorial(num3);
Comb=Factor1/(Factor2*Factor3);
return(Comb);
}
int main()
{
long unsigned int i,j,Num=0;
long unsigned int **Matrix;
clrscr();
printf(" %d\n " ,sizeof(long unsigned int));
printf("Enter Index of Square Matrix Num =: ");
scanf ("%lu",&Num);
Matrix=(long unsigned int **) malloc(Num*Num*sizeof(long unsigned int *));
for( i=0;i<Num;i++)
{ for (j=0;j<Num;j++)
{ *(*(Matrix+i)+j)=0;
}
}
for(i=0;i<Num;i++)
{ for(j=0;j<=i;j++)
{ printf(" %lu " , *(*(Matrix+i)+j)); }
printf("\n");
}
for(i=0;i<Num;i=i+1)
{
for(j=0;j<=i;j=j+1)
{
*(*(Matrix+i)+j)=Combination(i,j);
}
printf("\n");
}
for(i=0;i<Num;i++)
{
for(j=0;j<=i;j++)
{
// printf(" \n %lu %lu \n",i,j);
printf(" %lu ",*(*(Matrix+i)+j) );
}
printf("\n");
}
getch();
return(0);
}
C# solution:
public IList<IList<int>> Generate(int numRows) {
var result = new List<IList<int>>();
var item1 = new List<int>();
item1.Add(1);
result.Add(item1);
if (numRows == 1)
return result;
var item2 = new List<int>();
item2.Add(1);
item2.Add(1);
result.Add(item2);
if (numRows == 2)
return result;
var i = 2;
while (i != numRows)
{
var data = result.Last().ToArray();
var n = data.Length;
var item = new int[n + 1];
item[0] = 1;
item[n] = 1;
for (var x = 1; x < n; x++)
item[x] = data[x - 1] + data[x];
result.Add(item);i++;
}
return result;
}
Related
Basically my problem is that I'm trying to manually translate stuff that Python3 does easily into a C program. My first hurdle is literally input comprehension. Here is the sample input:
5
12
34 10
22 20 55
123 30 x 99
So as we can see, there are numbers, spaces, and characters in this input. I handled it in Python pretty easily, like so:
n = int(input()) #first line is always a single integer
matrix = [[' ' for i in range(n)] for j in range(n)] #declaring matrix of just space chars
for i in range(1,n):
line = input().split(' ') #gets rid of all spaces
for j in range(len(line)):
try:
matrix[i][j] = int(line[j])
matrix[j][i] = int(line[j]) #mirrors same value on opposite part of the matrix
except:
matrix[i][j] = 'x'
matrix[j][i] = 'x'
This results in the following matrix:
[[' ', 12, 34, 22, 123]
[12, ' ', 10, 20, 30]
[34, 10, ' ', 55, 'x']
[22, 20, 55, ' ', 99]
[123, 30, 'x', 99, ' ']]
So basically, I want to figure out how to do this in C. I have seen posts about how to read inputs dynamically, how to receive space-separated integers, and how to malloc integer space, but I have no idea how to put all of that stuff together. I would really appreciate some help. Ideally I want to store all these integers into a 2D array of integers like shown above.
EDIT: This is as far as I've gotten (code butchered from other people's helpful answers):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
int n; //number of cities
scanf("%d", &n);
printf("%d\n", n);
int *matrix = (int*)malloc(n*n*sizeof(int));
int i=0, j=0;
int *line = matrix;
char temp;
for (int k=0;k<n;k++)
{
do {
scanf("%d%c", &line[i], &temp);
i++;
} while(temp != '\n');
for(j=0; j<i; j++) {
printf("%d ", matrix[j]);
}
printf("\n");
}
free(matrix);
free(n);
return 0;
}
Output of this code:
5
5
12
12
34 10
12 34 10
22 20 55
12 34 10 22 20 55
123 30 x 99
^From above, first '5' is my input, second '5' is outputted, first '12' is my input, second is outputted, and so on. Code breaks in the last line. I understand that each time, it dumps everything stored in the 'buffer' that is the int * matrix. I don't know how to handle other characters like the 'x'. Ideally I would like to replace the 'x' in the matrix with a -1 or something.
I think it is really a mistake to mix scanf with getchar, but I believe the correct way to avoid scanf here is to pass n as a parameter (eg, read it from argv[1] rather than from the input stream). Also, your python is not really a matrix, but is a list of lists, and it would probably be cleaner to use a list of lists in the C implementation. But here is one approach to using a large array.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
struct entry {
enum { unknown, number, character } type;
union {
int v;
char x;
} value;
};
static int
die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(EXIT_FAILURE);
}
int
main(void) {
int n, c = '\n', p = EOF, row = 0;
if( scanf("%d", &n) != 1 || n < 1 ) {
die("Invalid input in row %d (%c)", row, c);
}
struct entry *matrix = calloc(n * n, sizeof *matrix);
struct entry *t = matrix - 1, *e = matrix + n * n;
while( (c = getchar()) != EOF) {
if( isdigit(c) ) {
if( t->type == character ) {
die("Invalid input in row %d (%c)", row, c);
}
t->type = number;
t->value.v = t->value.v * 10 + c - '0';
} else if( isspace(c) && c != p ) {
t += 1;
if( t >= e ) {
die("Invalid input in row %d (%c)", row, c);
}
if( c == '\n' ) {
t->type = character;
t->value.x = ' ';
t = matrix + n * ++row;
}
} else {
if( t->type != unknown ) {
die("Invalid input in row %d (%c)", row, c);
}
t->type = character;
t->value.x = c;
}
p = c;
}
/* Display the matrix */
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < n; j++ ) {
t = matrix + (( j > i ) ? (n * j + i) : (n * i + j));
switch( t->type ) {
case number:
printf("%8d", t->value.v);
break;
case unknown:
printf("%8s", "??");
break;
case character:
printf(" '%c'", t->value.x);
}
}
putchar('\n');
}
}
This solution is not as robust against whitespace issues in the input as a scanf solution would be, and does not handle runs of space or mixed space and tabs. Fixing that is left as an exercise for the reader.
I started studying Scala. It's difficult for me to understand Scala's collections.
I want to program the Partition function, but I'm referring to code already written using Python.
Could you tell me Scala's same code.
I use sbt 2.12.0.
I want to process big data.
I heard that the Vector type is fast, so I'm trying to use it, but can you tell me if there is a more appropriate collection type?
The Stream type was difficult to handle for me, but data could be stored using a lot of reverse.
Is the calculation slower if reverse processing is performed each time?
Python version
class PartitionNumbers:
def __init__(self):
self.points_list = list()
def _partition_function(self, n, k, tmp_list=[]):
if n == 0:
self.nums_list.append(tmp_list)
elif n == 1:
self.nums_list.append(tmp_list + [1])
elif k == 1:
self.nums_list.append(tmp_list + [1] * n)
else:
if n >= k:
self._partition_function(n - k, k, tmp_list + [k])
self._partition_function(n, k - 1, tmp_list)
return self.points_list
def create(self, n):
self.points_list = list()
return self._partition_function(n, n)
This code produces the following result:
pn = PartitionNumbers()
pn.create(3) # -> [[3], [2, 1], [1, 1, 1]]
pn.create(6) # -> [[6], [5, 1], [4, 2], [4, 1, 1], [3, 3], [3, 2, 1], [3, 1, 1, 1], [2, 2, 2], [2, 2, 1, 1], [2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]
Scala version
object PartitionNumbers {
def partitionFunction(n: Int, k: Int, v: Vector[Int] = Vector(), numsVector: Vector[Int] = Vector()): Vector[Int] = {
var tmp: Vector[Int] = Vector()
if (n == 0) {
tmp ++= numsVector ++ v
} else if (n == 1) {
tmp ++= numsVector ++ v ++ List(1)
} else if (k == 1) {
tmp ++= numsVector ++ append(n, v)
} else {
if (n >= k) {
partitionFunction(n - k, k, v :+ k, numsVector)
}
partitionFunction(n, k - 1, v, numsVector)
}
tmp
}
def append(n: Int, v: Vector[Int]): Vector[Int] = {
if (n == 0) {
v
} else {
append(n - 1, v :+ 1)
}
}
def create(n: Int): Vector[Int] = {
partitionFunction(n, n)
}
}
I expect the output that same Python version, but the actual output is
Vector()
Vector()
(Add: 2019-09-27 17:49[JST])
I tried Stream type version. In my understanding that Stream type is able to add element at the head only, so the order of the numbers is reversed form the fist code.
The purpose of this code is to get the maximum value from the calculation result using the Partition Numbers.
import scala.math.floor
class PartitionNumbers(startNum: Int, point: Int) {
var maxNum = 0
var tmpNum = 0
private def appendOnes(n: Int, s: Stream[Int] = Stream.empty[Int]): Stream[Int] = {
if (n == 0) s
else appendOnes(n - 1, 1 #:: s)
}
private def partition(n: Int, k: Int, tmpStream: Stream[Int] = Stream.empty): Int = {
if (n == 0) tmpNum = addPercent(tmpStream)
else if (n == 1 | k == 1) tmpNum = addPercent(appendOnes(n))
else {
if (n >= k) partition(n - k, k, k #:: tmpStream)
partition(n, k - 1, tmpStream)
}
if (maxNum < tmpNum) maxNum = tmpNum
maxNum
}
def searchMax(n: Int = point): Int = {
partition(n, n)
}
def addPercent(usePointsStream: Stream[Int], num: Int = startNum): Int = {
if (usePointsStream.isEmpty) {
num
} else {
addPercent(usePointsStream.init, floor(num * (100 + usePointsStream.last) / 100).toInt)
}
}
}
It gave me next results:
val pn_1 = new PartitionNumbers(100, 10)
println(pn_1.searchMax()) // -> 110
val pn_2 = new PartitionNumbers(1000, 50)
println(pn_2.searchMax()) // -> 1630
The output of this code is correct, but PartitionNumbers.point can't process up to 100.
I need that is handling over 1,000.
What do I need right away: type understanding or other algorithm considerations?
(Add: 2019-09-28 03:11[JST])
add question: Fixed Scala code using Partition Numbers with Stream calculate, BUT too slowly
Python's lack of types is what makes it hard to transfer over.
It seems that even though tmp_list's type would be Vector[Vector[Int]], this:
(tmp_list + [2]) + [1] == [1, 2]
which is insane, it should be [[1], [2]] if it was strongly typed.
Given that, here is a direct translation:
class PartitionNumbers {
private var pointsList: Vector[Vector[Int]] = null
private def partition(n: Int, k: Int, tmpList: Vector[Int] = Vector.empty): Vector[Vector[Int]] = {
if (n == 0) pointsList :+= tmpList
else if (n == 1) pointsList :+= (tmpList :+ 1)
else if (k == 1) pointsList :+= (tmpList ++ (1 to n).map(_ => 1).toVector)
else {
if (n >= k) partition(n - k, k, tmpList :+ k)
partition(n, k - 1, tmpList)
}
pointsList
}
def create(n: Int): Vector[Vector[Int]] = {
pointsList = Vector.empty
partition(n, n)
}
}
If you want to process big data however using "raw scala" (nothing like spark for example) a stream would be the way to go. This is because it can read data a bit at a time and keep constant memory. It will take a change of mindset into a more FP style to understand how to use them properly however.
I would recommend Akka streams or FS2 streams to do the job.
Here is a video from the Scala Toronto about FS2, its worth the watch:
https://www.youtube.com/watch?v=B1wb4fIdtn4&t=2s
I'm trying to implement a code that lists all possible combinations of a Knapsack problem using recursion. I have difficulty with recursion. I tried to solve it and got nothing, so I did some research and I found a code in Java Python, but I'm having a hard time trying to rewrite that code in C++.
Here is the solution code, in Java Python:
items = [1,1,3,4,5]
knapsack = []
limit = 7
def print_solutions(current_item, knapsack, current_sum):
#if all items have been processed print the solution and return:
if current_item == len(items):
print knapsack
return
#don't take the current item and go check others
print_solutions(current_item + 1, list(knapsack), current_sum)
#take the current item if the value doesn't exceed the limit
if (current_sum + items[current_item] <= limit):
knapsack.append(items[current_item])
current_sum += items[current_item]
#current item taken go check others
print_solutions(current_item + 1, knapsack, current_sum )
print_solutions(0,knapsack,0)
I found that code in this link
Here is what I tried to do..
#include <iostream>
using namespace std;
void AddItem(int item, int *knapsack) {
int i = 0;
while (knapsack[i] != -1)
i++;
knapsack[i] = item;
};
void printKnapsack(int *knapsack, int n) {
cout << "[";
for (int i = 0; i < n; i++)
if (knapsack[i] != -1)
cout << knapsack[i] << ",";
}
void print_solutions(int current_item, int *knapsack, int current_sum, int *items, int n, int limit) {
//if all items have been processed print the solution and return
if (current_item == n - 1) {
printKnapsack(knapsack, n);
return;
};
//don't take the current item and go check others
print_solutions(current_item + 1, knapsack, current_sum, items, n, limit);
//take the current item if the value doesn't exceed the limit
if (current_sum + items[current_item] <= limit) {
AddItem(items[current_item], knapsack);
current_sum += items[current_item];
};
//current item taken go check others
print_solutions(current_item + 1, knapsack, current_sum, items, n, limit);
};
int main() {
int current_item = 0;
int current_sum = 0;
int limit, n;
cout << "Type the maximum weight ";
cin >> limit;
cout << "How many items? ";
cin >> n;
int* knapsack;
knapsack = new int[10];
for (int i = 0; i < 10; i++)
knapsack[i] = -1;
int * items;
items = new int[n];
cout << "Type weights.";
for (int i = 0; i < n; i++) {
cin >> items[i];
};
print_solutions(0, knapsack, 0, items, n, limit);
return 0;
}
With the input:
7 // limit
5 // number of items
1 1 3 4 5 // items
I expect to get the following final result:
[]
[5]
[4]
[3]
[3, 4]
[1]
[1, 5]
[1, 4]
[1, 3]
[1]
[1, 5]
[1, 4]
[1, 3]
[1, 1]
[1, 1, 5]
[1, 1, 4]
[1, 1, 3]
But all I get is arrays filled with 3 and 4 instead of getting all actual solutions.
In short
There is a major issue in your transcription of the algorithm from python to C++ related to the language semantics related to parameter passing.
In full details
When in python you write the following:
print_solutions(current_item + 1, list(knapsack), current_sum)
Then list(knapsack) is a copy from the knapsack list. So the recursive call in the middle leaves the original knapsack unchanged, whereas the second recursive call changes the original knapsack:
print_solutions(current_item + 1, knapsack, current_sum)
In your C++ code however, in both case you work on the original knapsack list (the arrays parameters are passed by references), so that knapsack gets completely messed up:
//don't take the current item and go check others
print_solutions(current_item + 1, knapsack, current_sum, items, n, limit);
How to make it work ?
Either you create a temporary array and copy knapsack in it, or, much better, you start to use vector , which will make your C++ life much easier (making attention to pass by value or by reference).
The following version uses a vectors. The & in the parameter means that it's an argument passed by reference (i.e. the original vector can be changed). Note that we do no longer need to pass n, as the vector knows its length, as list do in python:
void print_solutions(int current_item, vector<int>& knapsack, int current_sum, const vector<int>& items, int limit) {
//if all items have been processed print the solution and return
if (current_item == items.size() ) {
printKnapsack(knapsack);
return;
};
//don't take the current item and go check others
vector<int> knapcopy = knapsack;
print_solutions(current_item + 1, knapcopy, current_sum, items, limit);
//take the current item if the value doesn't exceed the limit
if (current_sum + items[current_item] <= limit) {
knapsack.push_back(items[current_item]);
current_sum += items[current_item];
//current item taken go check others
print_solutions(current_item + 1, knapsack, current_sum, items, limit);
};
};
Here an online demo.
I am debugging on the following problem and posted problem statement and code. My question is, I think for loop (for i in range(m) and for j in xrange(n)) is not correct, since it only consider rectangles from the top row? Please feel free to correct me if I am wrong. Thanks.
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
def maximalRectangle(self, matrix):
if not matrix:
return 0
m, n, A = len(matrix), len(matrix[0]), 0
height = [0 for _ in range(n)]
for i in range(m):
for j in xrange(n):
height[j] = height[j]+1 if matrix[i][j]=="1" else 0
A = max(A, self.largestRectangleArea(height))
return A
def largestRectangleArea(self, height):
height.append(0)
stack, A = [0], 0
for i in range(1, len(height)):
while stack and height[stack[-1]] > height[i]:
h = height[stack.pop()]
w = i if not stack else i-stack[-1]-1
A = max(A, w*h)
stack.append(i)
return A
My solution in Java:
public class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] length = new int[rows][cols];
int result = 0;
for (int i = 0; i < rows; i++) {
length[i][0] = Character.getNumericValue(matrix[i][0]);
result = Math.max(result, length[i][0]);
}
for (int j = 0; j < cols; j++) {
length[0][j] = Character.getNumericValue(matrix[0][j]);
result = Math.max(result, length[0][j]);
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == '1') {
length[i][j] = Math.min(
Math.min(length[i - 1][j], length[i][j - 1]),
length[i - 1][j - 1]) + 1;
result = Math.max(result, length[i][j] * length[i][j]);
}
}
}
return result;
}
}
Supposed my input is [1, 4, 2, 5, 1, 2, 3] . Then we can create a
structure like this:
...X...
.X.X...
.X.X..X
.XXX.XX
XXXXXXX
1425123
When water is poured over the top at all places and allowed to runoff,
it will remain trapped at the 'O' locations:
...X...
.XOX...
.XOXOOX
.XXXOXX
XXXXXXX
1425123
we have to find a total number of trapped 'O' in a given list.
My program is able to give me the correct output but when I run it
against different test cases, it gives me a memory error. Is there any way I can reduce the space complexity of this program?
def answer(heights):
row = len(heights)
col = max(heights)
sum = 0
matrix = [['X' for j in range(i)] for i in heights]
for i in range(col):
rainWater = []
for j in range(row):
try:
rainWater.append(matrix[j][i])
except IndexError:
rainWater.append('0')
sum += ''.join(rainWater).strip('0').count('0')
return sum
print answer([1, 4, 2, 5, 1, 2, 3])
The list array will have at least 1 element and at most 9000 elements. Each element will have a value of at least 1, and at most 100000.
Inputs:
(int list) heights = [1, 4, 2, 5, 1, 2, 3]
Output:
(int) 5
Inputs:
(int list) heights = [1, 2, 3, 2, 1]
Output:
(int) 0
This can be solved in linear time with linear memory requirements in the following way:
def answer(heights):
minLeft = [0] * len(heights)
left = 0
for idx, h in enumerate(heights):
if left < h:
left = h
minLeft[idx] = left
minRight = [0] * len(heights)
right = 0
for idx, h in enumerate(heights[::-1]):
if right < h:
right = h
minRight[len(heights) - 1 - idx] = right
water = 0
for h, l, r in zip(heights, minLeft, minRight):
water += min([l, r]) - h
return water
The arrays minLeft and minRight contain the highest level at which water can be supported at a place in the array if there was a wall of infinite size on the right or left side respectively. Then at each index, total water that can be contained is the minimum of the water levels supported by the left and the right side - height of the floor.
This question deals with this problem in higher dimension (relating it to the Watershed problem in image processing): The Maximum Volume of Trapped Rain Water in 3D
The code's in c#. O(N) time, O(1) space. Using two pointers, and 2 integer variable to track. Can't figure out a more optimized way for this question.
public int Trap(int[] height) {
if(height == null || height.Length == 0)
return 0;
int max = 0;
int vol = 0;
int left = 0;
int right = height.Length - 1;
while(left<= right)
{
if(height[left] < height[right])
{
max = Math.Max(max,height[left]);
vol = vol + (max-height[left]);
left++;
}
else
{
max = Math.Max(max,height[right]);
vol = vol + (max-height[right]);
right--;
}
}
return vol;
}
You could solve this problem with a single loop (the following example is written in Java):
public static int trapw(int[] check) {
int sum = 0, ml = 0, mr = 0, clen = 0;
if ((clen = check.length-1) <= 1)
return 0;
int[] r = new int[clen+1];
for (int k = 0, lidx = clen; k <= clen; k++, lidx = clen - k) {
ml = Math.max(ml, check[k]); mr = Math.max(mr, check[lidx]);
if (k < lidx) {
r[k] = ml; r[lidx] = mr;
} else if (lidx == k) {
// Middlepoint
r[k] = Math.min(ml, mr); sum += Math.max(r[k] - check[k], 0);
} else {
r[k] = Math.max((Math.min(ml, r[k]) - check[k]), 0);
r[lidx] = Math.max((Math.min(mr, r[lidx]) - check[lidx]), 0);
sum += r[k] + r[lidx];
}
}
return sum;
}