I have this code, which isn't for the moment optimized:
def capture_inputs(cleaner):
return cleaner(input("What are valid programming paradigms?").split(","))
def clean_input(user_input):
result = []
for paradigm in user_input:
result.append(paradigm.strip())
return result
def count_valid_programming_paradigms(paradigms):
valid_paradigms = {"imperative","functional","object-oriented","logical","declarative"}
given_paradigms = set(paradigms)
return len(valid_paradigms & given_paradigms)
def report_result(user_input, counter):
valid_paradigms_count = counter(user_input)
if counter(user_input) > 0:
print("You found {} valid paradigms".format(valid_paradigms_count))
else:
print("You did not find any valid paradigm")
report_result(capture_inputs(clean_input),count_valid_programming_paradigms)
My goal is to make a perfect function of this, so it follows the perfect paradigm. How can I optimize it, to be as perfect as it can. I'm very thankful about every answer to you guys!
-
\$\begingroup\$ In a bit of delightful irony, your quiz on programming paradigms was itself tagged with the incorrect paradigm. This is procedural programming and not functional. \$\endgroup\$Reinderien– Reinderien2022年08月28日 15:20:41 +00:00Commented Aug 28, 2022 at 15:20
1 Answer 1
"Perfect" is somewhat subjective, but there is simplification to be had here.
I don't think there's a lot of value in passing around function references as you do; the complexity doesn't warrant it. It also doesn't particularly warrant a "cleaner" separated from the input function.
Your use of set literals and set intersection is reasonable.
report_result
can just be your main
. Add the call to it from a __main__
guard.
Prefer string interpolation over .format()
.
Consider calling .lower()
for more forgiving string matching.
Suggested
from typing import Iterator, Iterable
def capture_inputs() -> Iterator[str]:
line = input("What are valid programming paradigms? ")
for answer in line.split(","):
yield answer.strip().lower()
def count_valid(paradigms: Iterable[str]) -> int:
valid_paradigms = {"imperative", "functional", "object-oriented", "logical", "declarative"}
given_paradigms = set(paradigms)
return len(valid_paradigms & given_paradigms)
def main() -> None:
inputs = capture_inputs()
n_valid = count_valid(inputs)
if n_valid > 0:
print(f"You found {n_valid} valid paradigms")
else:
print("You did not find any valid paradigm")
if __name__ == '__main__':
main()
An alternative counting expression that does not need to construct a second set could look like
return sum(1 for paradigm in paradigms if paradigm in valid_paradigms)
I have a weak preference for the first form over this one.
-
\$\begingroup\$
valid_paradigms
would be good as a "constant" \$\endgroup\$janos– janos2022年08月28日 16:32:55 +00:00Commented Aug 28, 2022 at 16:32