Sunday, March 3, 2019

Cartesian product code in python php

---php----
$a[0] = ['please', 'could you', ''];
$a[1] = ['create', 'make', ''];
$a[2] = ['a', 'an', ''];
$a[3] = ['quick', 'short',''];

$combined = array();
for($i = 0; $i < count($a); ++$i) {
$combined = combine($combined, $a[$i]);
}

print_r($combined);

function combine($a, $b) {
if(!$a) return $b;
if(!$b) return $a;
$out = array();
for($i = 0; $i < count($a); ++$i) {
for ($j = 0; $j < count($b); ++$j) {
$curr = trim($a[$i].' '.$b[$j]);
$out[] = $curr;
}
}
return $out;
}

---python 1 ---
def combine(a, b):
if not a:
return b
if not b:
return a
out = []
for ai in a:
for bi in b:
out.append((ai + ' ' + bi).strip())
return out

arr = []
arr.append(['please', 'cortana please', ''])
arr.append(['create', 'make', ''])
arr.append(['a', 'an', ''])
arr.append(['quick', 'short',''])
arr.append(['note'])

combined = []
for ci in arr:
combined = combine(combined, ci)
print(len(combined))
for e in combined:
print(e)
--------------------------

Python 2:
def find(all1, ans, i):
if i == len(all1):
print(ans)
return
j = 0
while j < len(all1[i]):
ans.append(all1[i][j])
find(all1, ans, i+1)
ans.pop()
j += 1


all1 = []
all1.append(["hi", "hey"])
all1.append(["there", "here"])
all1.append(["cute", "handsome"])

ans = []
find(all1, ans, 0)

No comments:

Blog Archive