Python / Add previous element from a list - python

I'm quite new to Python and trying to do something but cannot figure out how...
x = 20
list = [5, 3, 7]
I want to create a loop that add the previous element from the list to x
Loop 1 : result = 20+0 = 20 (no previous element)
Loop 2 : result = 20+5 = 25
Loop 3 : result = 20+5+3 = 28
So at the end result should look like that :
result = [20, 25, 28]
Any idea how I could achieve this result ?
Thank you for your help!

Here's how I'd do it:
>>> x = 10
>>> my_list = [5, 3, 7]
>>> [x + sum(my_list[:n]) for n in range(len(my_list))]
[10, 15, 18]
Note that naming a list list is a bad idea because it overwrites the builtin list function!

Try it:
x = 20
my_list = [5, 3, 7]
result = [x]
for i in range(len(my_list)-1):
x += my_list[i]
result.append(x)
print(result)

You can use a list comprehension:
x = 20
lst = [5, 3, 7]
lst = [x+sum([lst[i] for i in range(i)]) if i else x for i,n in enumerate(lst)]
print(lst)
Output:
[20, 25, 28]

Related

Python produce alternative numbers list from a list of n numbers

I have a list of n numbers. I want to group them in g groups. Also, I want to reverse elements in every odd group. Finally, I would combine all elements in even and odd groups into a new sublist. First I am giving what answer I am expecting and where I went wrong:
Expected answer:
num = 14
grp = 4
# A list of num natural numbers arranged in group (row) of 4 numbers
lst =
[0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13]
lst =
[[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13]]
# Reverse elements in odd rows
newlst =
[[0,1,2,3],
[7,6,5,4], # reversed here
[8,9,10,11],
[13,12]] # reversed here
# combine elements in all sublists by their position
# combine first element in all sublists into a new sublist
sollst =
[[0,7,8,13],[1,6,9,12],[2,5,10],[3,4,11]]
My solution:
num = 14
grp = 4
#### print
lst= list(range(0,num,1))
newlst= [lst[i:i+grp:1] for i in range(0,num,grp)]
evnlst = newlst[0::2]
oddlst = newlst[1::2]
newoddlst = [oddlst [i][::-1] for i in range(len(oddlst))]
sollst= evnlst + newoddlst
# This gives [[0, 1, 2, 3], [8, 9, 10, 11], [7, 6, 5, 4], [13, 12]]
from itertools import zip_longest
print([[x for x in t if x is not None] for t in zip_longest(fevngps)])
Present answer:
I reached the one step before the final answer and now I have to combine the lists of different lengths and I am running into an error
TypeError: 'int' object is not subscriptable
One approach:
from itertools import zip_longest
num = 14
grp = 4
lst = list(range(0, num, 1))
newlst = [lst[i:i + grp:1] for i in range(0, num, grp)]
# build new list where the sub-list are reversed if in odd indices
revlst = [lst[::-1] if i % 2 == 1 else lst for i, lst in enumerate(newlst)]
# zip using zip_longest and filter out the None values (the default fill value of zip_longest)
result = [[v for v in vs if v is not None] for vs in zip_longest(*revlst)]
print(result)
Output
[[0, 7, 8, 13], [1, 6, 9, 12], [2, 5, 10], [3, 4, 11]]

How do you compare and return duplicates in two different 2d list?

I would like to return the duplicates in two different 2d lists. But I'm having trouble figuring out what code to write. For example I would like variable "a" to compare to variable "b" and return the duplicates. Here are my two 2d list below.
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
I would like my results to be:
c = [[2,3,6,8],[15,17,21,22]]
You just need to check if a list in a is also in b or not.
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c=[]
for i in a:
if i in b:
c.append(i)
print(c)
Output:
[[2, 3, 6, 8], [15, 17, 21, 22]]
This should work, it should get you started -
import itertools
#Input lists
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
#Take a product of both the lists ( a X b )
z = itertools.product(a,b)
#Uncomment the following to see what itertools.product does
#[i for i in z]
#Return only the elements which the pair of the same element repeats (using string match)
[i[0] for i in z if str(i[0])==str(i[1])]
[[2, 3, 6, 8], [15, 17, 21, 22]]
one liner list comprehension approach:
dups = [i for i in a if i in b]
output:
[[2, 3, 6, 8], [15, 17, 21, 22]]
Try this:
a = [[2,3,6,8],[4,5,7,8,10],[15,17,21,22],[12,13,14,23,25]]
b = [[4,5,6],[15,17,21,22],[2,3,4],[2,3,6,8],[5,7,8,12,15],[7,12,14,17,32],[5,6,7,12,14]]
c = []
for i in a + b:
if (a + b).count(i) > 1 and i not in c:
c.append(i)
#mulaixi's answer is OK but in output list you may see duplicates.

how to returns the index of the smallest element in the list in python

In my code, returns the position of the smallest element in the list by use index() function, when I run the code, it run nothing. Please help me to figure out problem. Here is what I coded:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
Many thanks.
You can use min(list) and builtin function of list(list.index())
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
min_num = min(list1)
index = list1.index(min_num)
One way, it's possible using min, emumerate and lambda
myList = [23, 3, 6, 5, 12, 9, 7, 4]
min(enumerate(myList), key=lambda x:x[1])[0]
#1
Your code looks good, but you forgot to call the function. Add test_get_index_of_smallest(), and it will work!
Input:
def get_index_of_smallest(numbers):
smallest_index = []
for element in range (len(numbers)):
element = numbers.index(min(numbers))
smallest_index = element + 1
return smallest_index
def test_get_index_of_smallest():
list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print(get_index_of_smallest(list1))
test_get_index_of_smallest()
Output:
2
Edit:
You can further cut down your code. Here is a code that does the same thing:
Input:
def get_index_of_smallest(numbers):
return numbers.index(min(numbers))+1
print(get_index_of_smallest([23, 3, 6, 5, 12, 9, 7, 4]))
Output:
2
We can use list comprehension and enumerate here
min_idx = [idx for idx, item in enumerate(list1) if item == min(list1)]
[1]
Here is a expanded version of what is going on here
for idx, item in enumerate(list1):
if item == min(list1):
min_idx = idx
When we enumerate in it iterates for the index and item so what we can do is check each item v min(list1) if we get a match we can set our min_idx variable to the corresponding index of that item, cheers !

Sum integer list when next integer is the same value

So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.
input1 = [int(i) for i in str(1234441122)]
x= 0
So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.
The following will work. Zip together adjacent pairs and only take the first elements if they are the same as the second ones:
>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> sum(x for x, y in zip(lst, lst[1:]) if x == y)
11
While this should be a little less [space-]efficent in theory (as the slice creates an extra list), it still has O(N) complexity in time and space and is well more readable than most solutions based on indexed access. A tricky way to avoid the slice while still being concise and avoiding any imports would be:
>>> sum((lst[i] == lst[i-1]) * lst[i] for i in range(1, len(lst))) # Py2: xrange
11
This makes use of the fact that lst[i]==lst[i-1] will be cast to 0 or 1 appropriately.
Another way using itertools.groupby
l = [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]
from itertools import groupby
sum(sum(g)-k for k,g in groupby(l))
#11
You can try this:
s = str(1234441122)
new_data = [int(a) for i, a in enumerate(s) if i+1 < len(s) and a == s[i+1]]
print(new_data)
final_data = sum(new_data)
Output:
[4, 4, 1, 2]
11
No need for that list. You can remove the "non-repeated" digits from the string already:
>>> n = 1234441122
>>> import re
>>> sum(map(int, re.sub(r'(.)(?!\1)', '', str(n))))
11
You are simply iterating on string and converting character to integer. You need to iterate and compare to next character.
a = str(1234441122)
sum = 0
for i,j in enumerate(a[:-1]):
if a[i] == a[i+1]:
sum+=int(a[i])
print(sum)
Output
11
Try this one too:
input1 = [int(i) for i in str(1234441122)]
x= 0
res = [input1[i] for i in range(len(input1)-1) if input1[i+1]==input1[i]]
print(res)
print(sum(res))
Output:
[4, 4, 1, 2]
11
Here's a slightly more space efficient version of #schwobaseggl's answer.
>>> lst = [1, 2, 3, 4, 4, 4, 1, 1, 2, 2]
>>> it = iter(lst)
>>> next(it) # throw away first value
>>> sum(x for x,y in zip(lst, it) if x == y)
11
Alernatively, using an islice from the itertools module is equivalent but looks a bit nicer.
>>> from itertools import islice
>>> sum(x for x,y in zip(lst, islice(lst, 1, None, 1)) if x == y)
11

Add an unknown number of lists by index

I need to add every index of an unknown amount of lists together into one list.
An example of what I mean:
list_a = [1,2,3,4,5]
list_b = [2,4,6,8,10]
list_c = [3,6,9,12,15]
def sum_lists():
temp_list = []
for index in range(len(list_a)):
temp_list.append(list_a[index] + list_b[index] + list_c[index])
return temp_list
total = sum_lists()
The expected output of my example code would be:
total = [6,12,18,24,30]
How would I accomplish the summation of an unknown amount of lists, for example 20 lists? I won't have to do this addition over thousands of lists, but I wouldn't know how many lists I have to add initially.
Any help would be greatly appreciated. All of the lists will be of the same length.
Create a list of lists:
In [124]: big_list = [list_a, list_b, list_c]
Now, zip em up and apply sum to each one using map:
In [125]: list(map(sum, zip(*big_list)))
Out[125]: [6, 12, 18, 24, 30]
You have other alternatives to map. For example, using a list comprehension:
In [126]: [sum(x) for x in zip(*big_list)]
Out[126]: [6, 12, 18, 24, 30]
You can store lists in lists and sum over them.
You could have something like this:
list_a = [1,2,3,4,5]
list_b = [2,4,6,8,10]
list_c = [3,6,9,12,15]
list_of_lists = [list_a, list_b, list_c] # this could be 20+ lists
def sum_lists():
temp_list = []
for index in range(len(list_a)):
temp_list.append(sum([l[index] for l in list_of_lists]))
return temp_list
total = sum_lists()
Here's my alternative:
list_a = [1, 2, 3, 4, 5]
list_b = [2, 4, 6, 8, 10]
list_c = [3, 6, 9, 12, 15]
def sum_lists(*arg):
return [sum(i) for i in zip(*arg)]
results = sum_lists(list_a, list_b, list_c)

Categories