Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
PHP to Python
#1
Hi All,

I learning Python and I see that my knowledge of this language is very poor as I am trying to translate a function from PHP to Python but I cannot get results.

This is the code in PHP and below, my try in Python,
__________________

PHP Code
__________________

function getCombinations($arrays) {
	$result = array(array());
	foreach ($arrays as $property => $property_values) {
		$tmp = array();
		foreach ($result as $result_item) {
			foreach ($property_values as $property_value) {
				$result_item[$property] = $property_value;
				$tmp[] = $result_item;
			}
		}
		$result = $tmp;
	}
	return $result;
}

$combinations = getCombinations(
	array(
		'item1' => array('A', 'B'),
		'item2' => array('C', 'D'),
		'item3' => array('E', 'F'),
	)
);

var_dump($combinations);
__________________

MY TRY IN PYTHON
__________________

def getCombinations(arrays):
	result = []
	for property, property_values in arrays.items():
		tmp = []
		for result_item in result:
			for property_value in property_values:
				result_item[property] = property_value
				tmp.append(result_item)
		result = tmp
	return result
My intention is to learn where are my faults to continue learning.

Thanks a lot in advance.

Mapg
Reply
#2
What is the code supposed to do?
Reply
#3
Hi Gribouillis,

You are very kind. The intention of this script is to get all possible combinations between elements in the array.

The output is like that ...
array (size=8)
  0 => 
    array (size=3)
      'item1' => string 'A' (length=1)
      'item2' => string 'C' (length=1)
      'item3' => string 'E' (length=1)
  1 => 
    array (size=3)
      'item1' => string 'A' (length=1)
      'item2' => string 'C' (length=1)
      'item3' => string 'F' (length=1)
  2 => 
    array (size=3)
      'item1' => string 'A' (length=1)
      'item2' => string 'D' (length=1)
      'item3' => string 'E' (length=1)
  3 => 
    array (size=3)
      'item1' => string 'A' (length=1)
      'item2' => string 'D' (length=1)
      'item3' => string 'F' (length=1)
  4 => 
    array (size=3)
      'item1' => string 'B' (length=1)
      'item2' => string 'C' (length=1)
      'item3' => string 'E' (length=1)
  5 => 
    array (size=3)
      'item1' => string 'B' (length=1)
      'item2' => string 'C' (length=1)
      'item3' => string 'F' (length=1)
  6 => 
    array (size=3)
      'item1' => string 'B' (length=1)
      'item2' => string 'D' (length=1)
      'item3' => string 'E' (length=1)
  7 => 
    array (size=3)
      'item1' => string 'B' (length=1)
      'item2' => string 'D' (length=1)
      'item3' => string 'F' (length=1)
Maybe Python works in a different manner so you need to know its intention as code cannot be translated exactly. I thought that Python could have equivalent expressions. Seems I was wrong.

Thanks in advance for your help.

Best,
Mapg
Reply
#4
For Python could use itertools combinations().
import itertools as it
from pprint import pprint

my_dict = {'item1':['A', 'B'], 'item':['C', 'D'], 'item3':['E','F']}
combinations = it.product(*(my_dict[name] for name in my_dict))
all_combo = list(combinations)
print(f'size={len(all_combo)}')
pprint(all_combo)
Output:
size=8 [('A', 'C', 'E'), ('A', 'C', 'F'), ('A', 'D', 'E'), ('A', 'D', 'F'), ('B', 'C', 'E'), ('B', 'C', 'F'), ('B', 'D', 'E'), ('B', 'D', 'F')]
Reply
#5
Oh. What a change! Thank you very much. Seems that Python has many libraries.
Reply
#6
line 5 can be written also as
combinations = it.product(*my_dict.values())
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
I didn't know that this was going to be so complex.

I need to add range of numbers to the arrays used in the above mentioned function, but I see that range in Python is not for float numbers and is not inclusive, namely range is not including the last number.

Seems that we need to use extra functions to complement the default function in Python.

I was able to get ranges using floats using this function:
def float_range(start, stop, skip = 1.0, decimals = 2):
	for i in range(int(start / skip), int(stop / skip)):
		yield float(('%0.' + str(decimals) + 'f') % (i * skip))

my_float_range = float_range(0.45, 0.6, 0.01)

all_combo = list(my_float_range)
print(f'size={len(all_combo)}')
pprint(all_combo)

OUTPUT ...
size=15 [0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59]

BUT I need to get in the array 0.60 too!!
I have this function to get inclusive ranges, but is not valid for float numbers
def closed_range(slices):
	slice_parts = slices.split(',')
	[start, stop, step] = map(int, slice_parts)
	num = start
	if start <= stop and step > 0:
		while num <= stop:
			yield num
			num += step
	# if negative step
	elif step < 0:
		while num >= stop:
			yield num
			num += step

all_combo = list(closed_range('1, 6, 1'))
print(f'size={len(all_combo)}')
pprint(all_combo)

OUTPUT ... size=6 [1, 2, 3, 4, 5, 6]
How can I get inclusive ranges also valid for float numbers?

Thank you very much for your reply
Reply
#8
Use
>>> import numpy as np
>>> np.linspace(0.45, 0.6, 16)
array([ 0.45,  0.46,  0.47,  0.48,  0.49,  0.5 ,  0.51,  0.52,  0.53,
        0.54,  0.55,  0.56,  0.57,  0.58,  0.59,  0.6 ])
Reply
#9
(Apr-27-2019, 02:41 PM)snippsat Wrote: For Python could use itertools combinations().
import itertools as it
from pprint import pprint

my_dict = {'item1':['A', 'B'], 'item':['C', 'D'], 'item3':['E','F']}
combinations = it.product(*(my_dict[name] for name in my_dict))
all_combo = list(combinations)
print(f'size={len(all_combo)}')
pprint(all_combo)
Output:
size=8 [('A', 'C', 'E'), ('A', 'C', 'F'), ('A', 'D', 'E'), ('A', 'D', 'F'), ('B', 'C', 'E'), ('B', 'C', 'F'), ('B', 'D', 'E'), ('B', 'D', 'F')]

The answer is very good but unfortunately, the keys are lost, and I need them.

How can be preserved the output that PHP version is showing but using Python?, namely ...
Output:
array (size=8) 0 => array (size=3) 'item1' => string 'A' (length=1) 'item2' => string 'C' (length=1) 'item3' => string 'E' (length=1) 1 => array (size=3) 'item1' => string 'A' (length=1) 'item2' => string 'C' (length=1) 'item3' => string 'F' (length=1) 2 => etc ...
Reply
#10
That is the basic principle of pythonic code:

use built in libraries and use Object oriented / functional code that reduces the number of lines of code.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020