accept kilo and mega ohms
This commit is contained in:
@@ -7,11 +7,11 @@ This repository aim to be a collection of useful scripts when working on small e
|
||||
## voltage\_divider.py
|
||||
#### input:
|
||||
(will ask the input through CLI if ran directly)
|
||||
+ a list of resistors values (floats) separated by commas or spaces.
|
||||
*example: 10 50 47 100*
|
||||
+ 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 5K 1M*
|
||||
+ a desired ratio \(0 ≤ ratio ≤ 1\) for the voltage divider
|
||||
*example: 0.4096*
|
||||
#### output:
|
||||
The 5 best resistor pairs (closest to the desired ratio).
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#!/bin/python
|
||||
import re
|
||||
|
||||
def find_bests(desired_ratio, resistors):
|
||||
# only keep the 5 best candidates
|
||||
candidates = []
|
||||
@@ -22,14 +24,27 @@ def find_bests(desired_ratio, resistors):
|
||||
|
||||
def parse_resistors(raw_input):
|
||||
values = []
|
||||
for token in raw_input.replace(',', ' ').split():
|
||||
try:
|
||||
v = float(token)
|
||||
if v <= 0:
|
||||
raise ValueError
|
||||
values.append(v)
|
||||
except ValueError:
|
||||
raise ValueError(f"Invalid resistor value '{token}'.")
|
||||
tokens = raw_input.replace(',', ' ').split()
|
||||
|
||||
for token in tokens:
|
||||
match = re.fullmatch(r'([0-9]*\.?[0-9]+)\s*([KM]?)', token)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid component 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
|
||||
|
||||
def get_ratio():
|
||||
@@ -45,7 +60,7 @@ def get_ratio():
|
||||
return desired_ratio
|
||||
|
||||
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)
|
||||
desired_ratio = get_ratio()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user