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

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

Related

Attemtping to solve twoSums leet code problem why doesn't the walrus operator with dict.get() work in python3

Prompt: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
def twoSum(nums: list, target: int) -> list:
lookup_table = {}
for index, num in enumerate(nums):
if second_index := lookup_table.get(target - num):
return [second_index, index]
lookup_table[num] = index
I'm using python 3.10 so I know the walrus operator has been implemented. I think it has something to do with the use of returning None from the get call or the return value from lookup_table.get().
Test Case I'm using:
twoSum([2,7,11,15], 9)
Currently returning: None
The dict.get will return None if the key is not found in the dictionary. You want to check for that (note, index 0 is valid and currently in your code it will evaluate to False):
def twoSum(nums: list, target: int) -> list:
lookup_table = {}
for index, num in enumerate(nums):
if (second_index := lookup_table.get(target - num)) is not None:
return [second_index, index]
lookup_table[num] = index
print(twoSum([2, 7, 11, 15], 9))
Prints:
[0, 1]

Comparing time complexity for two solutions for same python problem statement

We have first solution as :
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))
Ans second approach for the same problem as :
class Solution(object):
def containsDuplicate(self, nums):
hset = set()
for idx in nums:
if idx in hset:
return True
else:
hset.add(idx)
Question : Both having time complexity equal to O(N), but actual time taken has major difference between two approaches. Why is this the case ?

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

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

What is python pass by reference not working?

I have a solution for generating permutations of an array which is as follows:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
ji.append(nums[i])
self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
ji.pop()
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
Idea is to use another array that appends each element from original array one by one skipping before appended elements. But when doing it like this, I am getting an output of list of empty lists.
Online I saw someone do the same except they did it like this:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
I have no idea why their solution worked and mine did not, I had the same logic as theirs but I don't understand the difference. Can someone please explain why the second one worked and the first one did not?

"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