How to make python stop looking if there is a negative value? - python

I have a dict:
ff = {("Tom Brady",45678 ): [[456.0, 4050.0], [0.32, 5.6]]}
and
f = {("Tom Brady",45678 ): [[456.0, 4050.0, -1000.0], [0.32, 5.6, 4.56]]}
I have this code:
def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int
for a in client_list[client][0]:
if a>0:
return 2
if a<0
return 1
the problem with this code is that when there is no negative value, python gives me an error telling me it cannot be NoneType. I want the code to give me an answer if there is a negative, but instead it only gives me an error.

Your current logic is:
def help_find_neg(lst: list[float]):
for element in lst:
if element > 0:
return 2
if element < 0:
return 1
# and if element == 0: go to the next element
If your lst consists only of zeros, the function will skip all of them (and return None).
This might be the reason behind your NoneType error.

You could make the list of lists (the value in your dictionaries) into one big list, and then use list comprehension to create a new list that only holds the negative numbers. If the length of this list comprehension result is bigger than 0, then you have negative numbers in any of the lists that is in the value of your dictionary.
def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
big_list = sum(client_list[client], [])
negatives = [i for i in big_list if i < 0]
if len(negatives) > 0:
return True
return False
(the sum is a little trick to create one list out of a list of lists).
As per comments; if you only need to know if there was a negative number (and you will never need to know what number(s) those were), you could simplify:
def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
big_list = sum(client_list[client], [])
for i in big_list:
if i < 0:
return True
return False

Related

How to check if a number in a list range

I have a float number x and a list range list_ = [[a, b], [c,d], [e,f]]
How can check if the number x is in the list. It means the function will return True in case of
a<=x <=b
or
c<=x <=d
or
e<=x <=f
Otherwise, the function will return False. Could you help me to write a Python code for the function
function (x, list_)--> True/False
Clean solution:
def function(x, list_):
return any([l[0] < x < l[1] for l in list_])
Optimized solution:
def function(x, list_):
for l in list_:
if l[0] < x < l[1]:
return True
return False
The idiomatic solution would be this:
def f(x: int, ls: List[Tuple[float, float]]) -> bool:
return any(a <= x <=b for (a, b) in ls)
Take specific note of the following:
Naming a function function is a super poor idea.
It is abnormal and therefore a poor idea to name a variable list_ just to avoid overriding a keyword.
Using the form any ensures that you quickly quit when you find a valid solution.
You can quickly destructure your tuple (or list, if you happen to pass a list) using the for (a, b) in ls clause.
This solution is as quick as if you use a for clause, but all of that is premature optimization anyway.
Using an explicit destructing ensures you have two and only two elements for your sublist.
It was requested that I check certain inputs:
>>> f(10.1, [[8.1, 12.1], [110, 120]])
True
Seems to work!
If you're running into NameError, the issue is simply one of the importation of types. You can either define f like so:
def f(x, ls):
... // As you would otherwise
Or import the required types to make the type-hinting work properly:
from typing import List, Tuple
def f(x: int, ls: List[Tuple[float, float]]) -> bool:
... // As you would otherwise
This has little to do with the original question or solution - it's just standard for type hinting in python.
def function(x,list__):
for [a,b] in list_data:
if a<=x<=b:
return True
return False
You can simply iterate through the list and find whether it's in range or not.
I'm generating the variable and the list randomly and calling a function that iterates and checks whether the variable lies within the range of any of the members of the list.
import numpy as np
def find_if_in_range(list_, var) -> bool:
for i in list_:
if i[0] <= var <= i[-1]:
return True
return False
var = np.random.randint(10)
list_ = np.random.randint(10, size=(3,2), dtype=np.uint8)
print(f"var: {var}")
print(f"list: {list_}")
res = find_if_in_range(list_, var)
print(res)
Output:
var: 0
list: [[0 6]
[2 7]
[7 9]]
True
Hope this helps.
Cheers.

I need to keep multiplying found values by two with a list and a value

They gave me the first two lines of code. I thought I knew how to do it but I don't really understand what I'm missing.
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
if original in nums:
for original in nums:
original = original * 2
print(original)
else:
print(original)
yeyo = Solution()
yeyo.findFinalValue()
I think this is what you're trying to accomplish?
from typing import List
class Solution:
def findFinalValue(self, number_list: List[int] = [1,2,3,4,5,6,7,8,9,10], search_value: int = 9) -> int: # Added some default values to test without adding parameters
_done = False # Created a bool value to act as a switch to disable the while loop
original_number = search_value # saving the original value since im recycling the original var below
while _done is False: # Keep doing until the switch above is turned off
if search_value in number_list: # The condition you needed set
search_value *= 2 # that action if condition is met
else:
_done = True # the off "switch"
return "Original Number: {} Search value multiplied up to: {}".format(original_number, search_value) # returns both using a formatted string
#return original_number # Uncomment this line and delete the other return to only return the original number
yeyo = Solution()
yeyo.findFinalValue([1,2,3,4,5,6,7,8,9,10], 2)

Max sum from a contiguous array(having atleast one element)

Given a list. I have to create sublists having at least one element, and then return the sublist having maximum sum.
here is what I tried :
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
lists=[[]]
for i in range(1,len(nums)+1):
for j in range(1,i):
lists.append(nums[j:i])
new_list=lists
sum_list=[]
for k in range(1,len(new_list)):
sum1=sum(new_list[k])
sum_list.append(sum1)
return max(sum_list)
this is giving this error :
ValueError: max() arg is an empty sequence
How do I tweek my code to remove the empty sublist.
You can check if the list is empty before applying the max() method like this:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
lists=[[]]
for i in range(1,len(nums)+1):
for j in range(1,i):
lists.append(nums[j:i])
new_list=lists
sum_list=[]
for k in range(1,len(new_list)):
sum1=sum(new_list[k])
sum_list.append(sum1)
if sum_list:
return max(sum_list)
else:
return 0 # or some default value you want

Type hints in python puzzled by from typing import Any

I have the following exercise:
Annotate with correct types the parameters and the return values of
the functions, as well as of the variables, in the program in the
other panel. For that, you only need to replace every occurrence of
Any, except for the very first line, by an appropriate type.
Example: The first Any in line 3, i.e., n: Any, must be replaced by
int. You can see that from the line 9.
While I understand the theory of type hints I don't get the exercise, most probably because I do not get at this point the use of Any.
Furthermore the exercise is ambiguous, it says to replace every occurrence of Any.
If this is the case would the first line be:
def get_half(n : int) -> int:
return n/2
If so it does not work.
from typing import Any #do not edit this line
def get_half(n : Any) -> Any:
return n/2
def print_half(n : Any) -> Any:
print(n/2)
y = get_half(10)
print_half(20)
def is_present(s : Any, char : Any) -> Any:
found : Any = False
l : Any = len(s)
for i in range(0, l):
if s[i] == char:
found = True
return found
print(is_present("john", "h"))
This is the correct solution thanks to your answers
This link was very useful
https://mypy-play.net/?mypy=latest&python=3.10
from typing import Any #do not edit this line
def get_half(n : int) -> float:
return n/2
def print_half(n : int) -> None:
print(n/2)
y = get_half(10)
print_half(20)
def is_present(s : str, char : str) -> bool:
found : bool = False
l : int = len(s)
for i in range(0, l):
if s[i] == char:
found = True
return found
print(is_present("john", "h"))
The first any is an int like the example said def get_half(n : int) -> Any: and the return value will differ depending if your exercise is for python 2 or 3.
Python2: def get_half(n : int) -> int:
Python3: def get_half(n : int) -> float:
The reason for this is that Python 2 always returns an int if you divide and int with an int. int/int=int And Python 3 uses "true division" and therefor returns an float. int/int=float
For more info see: https://en.wikibooks.org/wiki/Python_Programming/Operators

"TypeError: Parameters to generic types must be types. Got 0." in my function

Ive written a function that counts how often a number smaller than my compared_number is in a list. But when executing it. I get the error in the title. Heres my function:
def count_smaller(input_list: List[int], compared_number: int) -> int:
for l in List:
if compared_number<0:
break
elif compared_number<List[l]:
count+=1
return count
List is an object defining a type, not your actual list object. You can read more about type hinting in the documentation
As you iterate over the list with for l in input_list, use the element l of the list directly in your comparison :
def count_smaller(input_list: List[int], compared_number: int) -> int:
for l in input_list:
if compared_number<0:
break
elif compared_number<l:
count+=1
return count

Categories