On trying to implement a recusion based technique to find powerset of a list, there was different behaviour in the c and python implementation.
It was first tried in python using pseudocode as follows
def(f, n):
if n<N:
f(s.append(n+1), n+1)
f(s, n+1)
if n==N:
# all elements end up here
f([], 1)
This calls the sets upto N, starting from 2 by adding another element and not adding in other.
My c code is as follows
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#define u8 uint8_t
#define N 4
void f(bool *s, u8 n){
printf("%*s", 4*n, "");
printf("[");
for(int i=2;i<=N;i++)
if(s[i]) printf("%d ", i);
printf("]n");
if(n<N){
f(s, n+1);
s[n+1] = true;
f(s, n+1);
}
if(n==N){}
}
int main(){
bool s[N+1] = {false};
f(s, 1);
}
To avoid using dynamic list, I’ve used an boolean array. The problematic code is probably the if block with n<N
check. This code uses tabs to space between different levels of recursion to debug easier
The same for python
N = 4
def f(s, n):
print('t'*n, s)
if n<N:
f(s+[n+1], n+1)
f(s, n+1)
if(n==N):
pass
f([], 1)
C output
[]
[]
[]
[]
[4 ]
[3 4 ]
[3 4 ]
[3 4 ]
[2 3 4 ]
[2 3 4 ]
[2 3 4 ]
[2 3 4 ]
[2 3 4 ]
[2 3 4 ]
[2 3 4 ]
Python output
[]
[2]
[2, 3]
[2, 3, 4]
[2, 3]
[2]
[2, 4]
[2]
[]
[3]
[3, 4]
[3]
[]
[4]
[]
epestr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.