hello, given a list L, I want to split the list into sublists with sum of elements 10 when possible and when not to sublists with sum < 10 - list

for example having L=[7,8,3,2,5,4,1,5,5,8,8], a possible split is [7,3], [8,2], [5,5] [5,4,1] and [8], [8] since there is no possibilities to have sublists of sum 10 anymore
def divide_list(lst):
sublists = []
current_sublist = []
current_sum = 0
def add_to_sublist(num):
nonlocal current_sublist, current_sum
current_sublist.append(num)
current_sum += num
if current_sum >= 10:
sublists.append(current_sublist)
current_sublist = []
current_sum = 0
for num in lst:
if current_sum + num <= 10:
add_to_sublist(num)
else:
remaining_sum = 10 - current_sum
add_to_sublist(remaining_sum)
divide_list([num] + lst[lst.index(num)+1:])
break
if current_sublist:
sublists.append(current_sublist)
remaining = lst[lst.index(sublists[-1][-1])+1:] if sublists else lst
while remaining:
current_sublist = [remaining.pop(0)]
current_sum = current_sublist[0]
while current_sum < 10 and remaining:
num = remaining.pop(0)
current_sublist.append(num)
current_sum += num
sublists.append(current_sublist)
###
return sublists
lst = [6,4,5,5,7,3,9,1,8,2,7,4,5]
sublists = divide_list(lst)
print(sublists)
this is an example where after there is no longer a sublist with a sum of 10 i got [7, 4], [5]

Related

how do you split a list into 3 lists, for each list in a list? Python Beginner

list1= [[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9]]
Result should be:
list2 = [[1,2,3],[4,5,6],[7,8,9],[1,2,3],[4,5,6],[7,8,9],[1,2,3],[4,5,6],[7,8,9]]
This should work for any list divisible by 3 as well.
list1 = [1,2,3,4,5,6,7,8,9]
Result:
list2 = [[1,2,3],[4,5,6],[7,8,9]]
I tried using:
list2 = [list1[i:i + n] for i in range(0,len(list1),n)]
No luck.
Answer:
list_1 = [either Nested or not Nested]
check_list_type = any(isinstance(i, list) for i in list_1)
if check_list_type == True:
split_list = [z[j: j + 3] for z in list_1 for j in range(0, len(z) - 2, 3)]
if check_list_type == False:
length = int(len(list_1)/3)
split_list = [list_1[i:i + length] for i in range(0,len(list_1),length)]
print(split_list)
Allows you to split any list into 3 more lists.
Try this:
list2 = [lst[j: j + 3] for lst in list1 for j in range(0, 7, 3)]
A slightly more generic approach:
list2 = [lst[j: j + 3] for lst in list1 for j in range(0, len(lst) - 2, 3)]

Python: Compare the length of different lists and return the longest

I would like to compare 5 lists regarding their length and return the longest list.
I don't have any idea...
Maybe something like this:
a = [1,1,1,1]
b = [1]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,1,1,1,1]
L = [a,b,c,d,e]
def compare(lists):
counter = count()
previous = lists[0]
group_index = next(counter)
for value in lists:
if len(value) >= len(previous):
...
The result should be 'e'.
below is py3
a = [1,1,1,1]
b = [1]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,1,1,1,2]
f = [1,1,1,1,1,2]
L = [a,f,b,c,d,e]
def compare(lists):
previous = lists[0]
for value in lists:
if len(value) >= len(previous):
previous=value
return previous
Rsss=compare(L)
print(Rsss)
print([ k for k,v in locals().items() if v == Rsss][0])
python 2 change items to iteritems
print() to print

Python. <Remove Element> in a list

Title:
172. Remove Element
Description:
Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don't matter.
My Answer:
On LintCode
def removeElement(self, A, elem):
# write your code here
if A == []:
return A
if elem in A:
sortedA = sorted(A)
li = []
for i in xrange(len(sortedA)):
if sortedA[i] == elem:
li += [i]
newLength = sortedA[:min(li)] + sortedA[max(li)+1:]
return newLength
else:
return A
On my mac
A = [0,4,4,0,0,2,4,4]
elem = 4
def sss(A, elem):
if A == []:
return A
if elem in A:
print A
sortedA = sorted(A)
print sortedA
li = []
for i in xrange(len(sortedA)):
# print type(i)
if sortedA[i] == elem:
li += [i]
print li
newLength = sortedA[:min(li)] + sortedA[max(li)+1:]
print newLength
return newLength
else:
return A
print sss(A, elem)
This answer On my mac work's good, but On LintCode doesn't accept.
Why not use a list comprehension to filter out the unwanted elements?
class Solution:
def removeElement(self, A, elem):
A[:] = [item for item in A if item != elem]
return len(A)
The key here is the slice notation on the left hand side of the assignment. This makes it an "in place" operation, so the original list A is mutated, rather than a copy being made.
Example usage:
>>> l = [1, 2, 3, 4, 4, 5, 4, 10, 11, 4]
>>> len(l)
10
>>> Solution().removeElement(l, 4)
6
>>> l
[1, 2, 3, 5, 10, 11]
>>> len(l)
6
Although this is an old post, yet would like to add the different approaches I tried. Time Complexity is O(n) in all cases.
Method I: Override the elements if they are not val (Logical Approach)
def removeElement(self, nums: List[int], val: int) -> int:
i : int = 0 # This will be an index pointer & will provide the sixe at the end
for j in range(len(nums)):
if nums[j] != val: # if the values are not same
nums[i] = nums[j] # Override the value at location i
i+=1
return i
Method II: Override the val with last array element (Logical Approach)
def removeElement(self, nums: List[int], val: int) -> int:
i: int = 0
n: int = len(nums)
while(i<n):
if(nums[i] == val):
# Replace the element with last array element & reduce the array size by 1
nums[i] = nums[n-1]
n -=1
else:
i +=1
return n
Method III -- Improved form of Method 2 (Python way)
def removeElement(self, nums: List[int], val: int) -> int:
i : int = 0
n : int = len(nums)
while i< n :
print(i, nums, n)
if val in nums[:n]:
i = nums.index(val,0,n)
nums[i] = nums[n-1]
n -=1
else:
break
return n
Method IV -- Python way
def removeElement(self, nums: List[int], val: int) -> int:
nums[:] = [x for x in nums if x !=val]
return len(nums)
All of them have an average runtime of around 36ms and memory utilization around 13.8MB.

Multiply a list of ints using list comprehension

Is there a way to do this with list comprehension?
for i in range(0, len(x)):
if i == 0:
sum = x[i]
else:
sum = sum * x[i]
I've tried this:
[total for i in x if i == 0 total = x[i] else total = total * x[i]]
and this:
[total = x[i] if i == 0 else total = total * x[i] for i in x]
I saw that there is a way to do it with enumerate but I was wondering if there is a way to do it in one line just using list comprehension. I'm not trying to solve a problem, I'm just curious.
I think what you need is reduce, but not list comprehension.
from operator import mul
s = [1, 2, 3]
print reduce(mul, s, 1)
Or using list comprehension:
class Mul(object):
def __init__(self):
self.product = 1
def __call__(self, x):
self.product *= x
return self.product
s = [1, 2, 3, 4, 5]
m = Mul()
[m(x) for x in s]
I'm gonna prefix this with "you do not want to do this". No really. But if you did...
# whatever your input is
x = [1, 2, 3, 4, 5]
# set the initial total to 1, and wrap it in a list so we can modify it in an expression
total = [1]
# did I mention you shouldn't do this?
[total.__setitem__(0, xi * total.__getitem__(0)) for xi in x]
print total[0]
120

Finding the numbers in a list that add up to a sum Python

I need to define a function that finds the numbers within a list that add up to a given sum. I want to do this function recursively.
This is what I have so far, I think I need to work on my recursion and base cases.
def findsum ( x , y ) :
pile = []
z = x-y[0]
if x == 0 :
return pile
elif y == [] :
return pile
else:
index = 0
n = len ( y )
while index < n:
if sum( y[:index]) == x - y[index]:
pile += y[index]
y = y[:index]
x = x - y[index]
index += 1
return pile + findsum ( x , y )
How can I edit this to find the the numbers in list y that add up to the sum x while using recursion.