accept kilo and mega ohms

This commit is contained in:
2025-12-13 16:21:36 +01:00
parent ef8b6c104e
commit 6709df960d
2 changed files with 27 additions and 12 deletions

View File

@@ -7,8 +7,8 @@ This repository aim to be a collection of useful scripts when working on small e
## voltage\_divider.py ## voltage\_divider.py
#### input: #### input:
(will ask the input through CLI if ran directly) (will ask the input through CLI if ran directly)
+ a list of resistors values (floats) separated by commas or spaces. + a list of resistors values (floats) separated by commas or spaces, accept K and M suffixes for kilo and mega ohms values.
*example: 10 50 47 100* *example: 10 50 47 100 5K 1M*
+ a desired ratio \(0 ≤ ratio ≤ 1\) for the voltage divider + a desired ratio \(0 ≤ ratio ≤ 1\) for the voltage divider
*example: 0.4096* *example: 0.4096*
#### output: #### output:

View File

@@ -1,4 +1,6 @@
#!/bin/python #!/bin/python
import re
def find_bests(desired_ratio, resistors): def find_bests(desired_ratio, resistors):
# only keep the 5 best candidates # only keep the 5 best candidates
candidates = [] candidates = []
@@ -22,14 +24,27 @@ def find_bests(desired_ratio, resistors):
def parse_resistors(raw_input): def parse_resistors(raw_input):
values = [] values = []
for token in raw_input.replace(',', ' ').split(): tokens = raw_input.replace(',', ' ').split()
try:
v = float(token) for token in tokens:
if v <= 0: match = re.fullmatch(r'([0-9]*\.?[0-9]+)\s*([KM]?)', token)
raise ValueError if not match:
values.append(v) raise ValueError(f"Invalid component value '{token}'")
except ValueError:
raise ValueError(f"Invalid resistor value '{token}'.") number = float(match.group(1))
if number <= 0:
raise ValueError(f"Invalid component value '{token}' (must be positive)")
suffix = match.group(2)
if suffix == 'K':
multiplier = 1e3
elif suffix == 'M':
multiplier = 1e6
else:
multiplier = 1.0
values.append(number * multiplier)
return values return values
def get_ratio(): def get_ratio():
@@ -45,7 +60,7 @@ def get_ratio():
return desired_ratio return desired_ratio
def get_inputs(): def get_inputs():
raw_input_resistors = input("Enter resistor values (floats) separated by spaces or commas: ") raw_input_resistors = input("Enter resistor values separated by spaces or commas: ")
resistors = parse_resistors(raw_input_resistors) resistors = parse_resistors(raw_input_resistors)
desired_ratio = get_ratio() desired_ratio = get_ratio()