patternpythonMinor
Finding if a given number is in a given range based on a flag
Viewed 0 times
numberflagrangebasedfindinggiven
Problem
Question Description:
Given a number
The link to the problem is here.
Below is my first attempt. Please feel free to review it based on best practices, style and any other efficient solution.
Given a number
n, return True if n is in the range 1..10, inclusive. Unless outsideMode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.in1to10(5, False) → **True**
in1to10(11, False) → **False**
in1to10(11, True) → **True**The link to the problem is here.
Below is my first attempt. Please feel free to review it based on best practices, style and any other efficient solution.
def in1to10(n, outside_mode):
if(n>1 and n<10):
return not outside_mode
else:
return outside_mode or n is 10 or n is 1Solution
The logic is confusing. A direct translation of the problem specification is possible, and clearer.
Let's deal with the first half of the problem:
Given a number \$n\$, return
Then it's natural to write:
Now we can deal with the second half:
Let's deal with the first half of the problem:
Given a number \$n\$, return
True if \$n\$ is in the range \$1 ..10\$, inclusive.Then it's natural to write:
def in1to10(n):
return 1 <= n <= 10Now we can deal with the second half:
def in1to10(n, outside_mode):
if outside_mode:
return n = 10
return 1 <= n <= 10Code Snippets
def in1to10(n):
return 1 <= n <= 10def in1to10(n, outside_mode):
if outside_mode:
return n <= 1 or n >= 10
return 1 <= n <= 10Context
StackExchange Code Review Q#66967, answer score: 7
Revisions (0)
No revisions yet.