Sum of a list 2 elements by 2 elements [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I have a 25 elements list like
tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don't have to calculate the sum on the last element.
And it has to be done with a for loop for... any ideas?
Any help would be appreciated.
I tried on my side but without success.
i tried this :
for i in tab:
print(sum(i:len(tab))
it gives me a syntax error and i tried some of others things but didn't work...
i tried this too
for i in tab:
print(sum(i,i+1))
didn't work too
and when i do this
sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))
it gives me back : TypeError: 'int' object is not callable

You could iterate over the list with steps of 2.
orig_len = len(tab) # List length
tab1 = []
for i in range(0, orig_len - orig_len%2, 2):
tab1.append(tab[i] + tab[i+1])
print(tab1)
You have to round down the number to first smaller even number, which is that orig_len - orig_len%2 does.

Try this:
tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
print([sum(tab[i:i+2]) for i in range(0, len(tab),2)])
The output will be:
[11, 11, 6, 5, 7, 9, 6, 11, 6, 4, 2, 5, 5]

This can be achieved by:
tab = [6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
tab1 = []
initial_pos = 0
for i in range(2, len(tab), 2):
tab1.append(sum(tab[initial_pos:i]))
initial_pos = I
if i == len(tab) - 2:
tab1.append(sum(tab[i:]))
What is happening here is we are iterating through tab starting at the third element and summing the values of elements of the slice tab[0:2], then initial_pos will assume the value of 2 and I the value of 4, so in the next iteration we will be appending sum(tab[2:4])to tab1 and so forth.
The if statement makes sure this works for odd lists and even lists.

Related

Removing Duplicate Numbers in a list with a twist

I have looked around and found the
if numbers.count(x) >= 2:
numbers.remove(x)
print(numbers)
but I don't want to use that. I think lazy-ier way is to go like this:
numbers = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 2, 5, 12]
numbers.sort()
print(numbers)
duplicate = 0
for each_item in numbers:
if duplicate == each_item:
numbers.remove(each_item)
else:
duplicate += 1
print(numbers)
I, first, sort the list then print it for manual comparison. I add a variable called duplicate and set it to 0. I go thru the loop for each number in the list numbers. If I find the duplicate's value same as a number in the list, I remove it and go thru the loop, else I increase the value by 1 and print the list.
The problem is if there are more than 2 duplicates in the list it doesn't work. Which I don't understand why. I run the code in my head and it should work "flawlessly"?
Thank you for your time sensei's
Current output is;
[1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 12]
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 12]
Use a set to make things easy:
numbers = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 2, 5, 12]
s = set(numbers)
print(list(s))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12]
You are changing an iterable as you iterate over it. That causes unpredictable behavior, like "skipping" an item in that list. There's plenty of resources on the internet describing the details (for instance).
Instead, iterate over a copy:
for each_item in numbers[:]:
(...)

How to apply a function to every set of three in a list?

The list is 2, 4, 5, 1, 2, 3, 3, 5, 1
How would I get the output to be
2,4,5
1,2,3
3,5,1
And then be able to apply a function to each of these three lists?
its simple
mylist = [2, 4, 5, 1, 2, 3, 3, 5, 1]
subset_len = 3
print([mylist[subset_len*i:subset_len*(i+1)] for i in range(len(mylist)//subset_len)])
You can try with this:
data = [2, 4, 5, 1, 2, 3, 3, 5, 1]
elements_for_list = 3
splitted_data = [data[i: i+elements_for_list] for i in range(0, len(data), elements_for_list)]
for values in splitted_data:
# apply the sum function on each list
print(sum(values))

Modifying list with numbers in python

I am trying modify a list. Currently, there is a list with random number and I would like to change the list which creates maximum number of increase between numbers. Maybe I worded badly. For example, if list is [2,3,1,2,1], I would modify into [1,2,3,1,2] since 1->2, 2->3 and 1->2 in an increase which gives total of 3 increasing sequence. Any suggestions?
I would approach your problem with this recursive algorithm. What I am doing is sorting my list, putting all duplicates at the end, and repeating the same excluding the sorted, duplicate-free list.
def sortAndAppendDuplicates(l):
l.sort()
ll = list(dict.fromkeys(l)) # this is 'l' without duplicates
i = 0
while i < (len(ll)-1):
if list[i] == list[i+1]:
a = list.pop(i)
list.append(a)
i = i - 1
i = i + 1
if hasNoDuplicates(l):
return l
return ll + sortAndAppendDuplicates(l[len(ll):])
def hasNoDuplicates(l):
return( len(l) == len( list(dict.fromkeys(l)) ) )
print(sortAndAppendDuplicates([2,3,6,3,4,5,5,8,7,3,2,1,3,4,5,6,7,7,0,1,2,3,4,4,5,5,6,5,4,3,3,5,1,2,1]))
# this would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 3, 4, 5, 3, 5, 3, 5]

Append items that weren't removed into separate list [duplicate]

This question already has answers here:
How to delete an element from a list while iterating over it in Python? [duplicate]
(2 answers)
Closed 5 years ago.
I want to know how to append all the items that weren't removed into a new list.
challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]
def remove_values(thelist, value):
newlist = []
while value in thelist:
thelist.remove(value)
newlist.append()
bye = remove_values(challenge, max(challenge))
For example, if I remove all the 9s (the max), how do I append the rest into a new list?
challenge = [1, 0, 9, 8, 5, 4, 1, 9, 3, 2, 3, 5, 6, 9]
# This will append every item to a new List where the value not is max
# You won't need 2 lists to achieve what you want, it can be done with a simple list comprehension
removed_list = [x for x in challenge if x != max(challenge)]
print(removed_list)
# will print [1, 0, 8, 5, 4, 1, 3, 2, 3, 5, 6]

Removing the duplicate entries from a list by editing the list

Have a list arr = [1,3,4,5,2,3,4,2,5,7,3,8,1,9,6,2,1,2,1,3,4,3,4,6,9]
want to remove the duplicate values so that the original list should contains single instances of all elements. Do not want to create a extra list and append the elements from list. Also do not want to use inbuilt "set".
Tried to do that with some code as below:
l = len(arr)
for x in range(l):
for y in range(x+1,l):
if arr[x] == arr[y]:
del arr[y]
Tried the above code and its throwing error
"IndexError: list index out of range"
What I understand is whiling deleting the value the size of the list is changing for which its throwing the error. So I made the below changes. But still its failing with same error:
l = len(arr)
for x in range(l):
for y in range(x+1,l):
if arr[x] == arr[y]:
t = y
del arr[y]
y = t - 1
Can some one help me out on this?
Thanks in Advance.
You are trying to make the code more efficient by caching the length of the list in the local variable l. However, that is not helpful because the list is being trimmed inside the loop, and you are not keeping the cached length variable in sync.
for index in range(len(arr)-1,0,-1):
if arr[index] in arr[:index]:
del arr[index]
By going backwards through the array and looking for earlier occurrences of each element, you can avoid having to worry about the length of the list changing all the time.
This method also preserves the order in which elements occur in the original array. Note the instruction is to only remove duplicates (a.k.a. subsequent occurrences).
For example the list [9,3,4,3,5] should reduce to [9,3,4, 5] as the second occurrence of 3 is considered a duplicate and should be removed.
How about this approach:
>>> set(arr)
set([1, 2, 3, 4, 5, 6, 7, 8, 9]) #Just to compare it with the results below.
>>> arr = [1,3,4,5,2,3,4,2,5,7,3,8,1,9,6,2,1,2,1,3,4,3,4,6,9]
>>> arr.sort()
>>> arr
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 9]
>>> for i in arr:
while arr.count(i) > 1:
del arr[i]
>>> arr
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Another approach is to find, after sorting your list, the length of the sublist to delete for each number:
>>> arr = [1,3,4,5,2,3,4,2,5,7,3,8,1,9,6,2,1,2,1,3,4,3,4,6,9]
>>> arr.sort()
>>> arr
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 9]
>>> for i,j in enumerate(arr):
del arr[i+1:i+arr.count(j)]
>>> arr
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Categories

Resources