microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
source/pip/qsharp/openqasm/_utils.py
40lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | from .. import Result |
| 5 | |
| 6 | |
| 7 | def _map_qsharp_result_to_bit(v) -> str: |
| 8 | if isinstance(v, Result): |
| 9 | if v == Result.One: |
| 10 | return "1" |
| 11 | else: |
| 12 | return "0" |
| 13 | return str(v) |
| 14 | |
| 15 | |
| 16 | def _convert_result_arrays_to_bitstrings(obj): |
| 17 | if isinstance(obj, tuple): |
| 18 | return tuple([_convert_result_arrays_to_bitstrings(term) for term in obj]) |
| 19 | elif isinstance(obj, list): |
| 20 | # if all elements are Q# results, convert to bitstring |
| 21 | if all([isinstance(bit, Result) for bit in obj]): |
| 22 | return "".join([_map_qsharp_result_to_bit(bit) for bit in obj]) |
| 23 | return [_convert_result_arrays_to_bitstrings(bit) for bit in obj] |
| 24 | elif isinstance(obj, Result): |
| 25 | if obj == Result.One: |
| 26 | return 1 |
| 27 | else: |
| 28 | return 0 |
| 29 | else: |
| 30 | return obj |
| 31 | |
| 32 | |
| 33 | def as_bitstring(obj): |
| 34 | """ |
| 35 | Convert Q# results to bitstrings. |
| 36 | |
| 37 | :param obj: The object to convert. |
| 38 | :return: The converted object. |
| 39 | """ |
| 40 | return _convert_result_arrays_to_bitstrings(obj) |
| 41 | |