Find index of item in list where sum of start of list to index is greater than X - list

I am looking for a fast implementation of the following code; using, for instance, map() or next():
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
total_so_far = 0
for i in l:
total_so_far += i
if total_so_far > 14:
break
print(i)
The code prints the index of item in list where sum of start of list to the index is greater greater than 14.
Note: I need to continuously update the link in another loop. Therefore, a solution in numpy would probably be too slow, because it cannot update a list in-place.

You can also make use of itertools.accumulate() together with enumerate() and next():
In [1]: from itertools import takewhile
In [2]: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: next(index for index, value in enumerate(accumulate(l)) if value > 14)
Out[3]: 5

Related

How to get a index of element in the array with Dlang?

I would like to get a index of array satisfying the condition.
Then, I'd like to get max of them.
With Ruby:
# normal array
array.index{|n| n>W }
# 2-dimensional array
matrix.map{|arr| arr.index{|n| n>W}}
How to do this with Dlang ?
You can use countUntil, it accepts a predicate :
[1, 2, 3, 4, 5, 6, 7, 8].countUntil!(c => c > 5).writeln;
To get the index of the max element, use the aptly name maxIndex function :
[1, 2, 3, 4, 5, 6, 7, 8].maxIndex.writeln;

How to switch values in a list to print an alternated version of the list?

I'm having some trouble figuring out how to switch numbers in a long list.
For example if were to have a list:
numbers = [1,2,3,4,5,6,7,8]
and wanted to instead print it in the form of:
numbers_2 = [2,1,4,3,6,5,8,7]
such that each pair would be switched, using a for-loop. I thought about doing something like:
for i in range(0, len(numbers), 2):
But wasn't really able to get much further.
Loop every second index and swap two adjacent items:
numbers = [1,2,3,4,5,6,7,8]
for i in range(1, len(numbers), 2):
numbers[i-1], numbers[i] = numbers[i], numbers[i-1]
Not sure about the other answers, but this one will also work with a list of an uneven length, and leave the last item untouched.
Take 2 halves, and rearrange them:
numbers = [1,2,3,4,5,6,7,8]
first = numbers[::2]
second = numbers[1::2]
numbers_2 = sum(map(list, zip(second, first)), [])
Try this:
def swap_array_elements (a):
for i in range (0, len(a) - 1, 2):
a[i], a[i +1] = a[i + 1], a[i]
return a
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print (swap_array_elements (a))
# prints: [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

How to find longest consistent increment in a python list?

possible_list = []
bigger_list = []
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
for i in range(0,len(new_list)):
# if the next index is not greater than the length of the list
if (i + 1) < (len(new_list)):
#if the current value is less than the next value
if new_list[i] <= new_list[i+1]:
# add the current value to this sublist
possible_list.append(new_list[i])
# if the current value is greater than the next, close the list and append it to the lager list
bigger_list.append(possible_list)
print bigger_list
How do I find the longest consistent increment in the list called new_list?
I expect the result to be
[[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]]
I can find the remaining solution from there myself.
One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list!
Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to).
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
subseq = [[]]
for e in new_list:
if not subseq[-1] or subseq[-1][-1] <= e:
subseq[-1].append(e)
else:
subseq.append([e])
This way, subseq ends up the way you want it, and you can use max to get the longest one.
>>> subseq
[[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]
>>> max(subseq, key=len)
[1, 4, 6, 6, 7]

Remove adjacent element in a list in python

I am trying to do a simple python program that removes all the adjacent elements in a list
def main():
a = [1, 5, 2, 3, 3, 1, 2, 3, 5, 6]
c = len(a)
for i in range (0, c-2):
if a[i] == a[i+1]:
del a[i]
c = len(a)
print a
if __name__ == '__main__':
main()
and the output is
[1, 5, 2, 3, 3, 2, 3, 5, 6] which is all fine!
If change the a list to a = [1, 5, 2, 3, 3, 1, 2, 2, 5, 6]
then it gives an error
index list out of range
**if a[i] == a[i+1]**
It shouldn't be complaining about the index out of range as I am calculating the len(a) every time it deletes an element in the list. What am I missing here?
for i in range (0, c-2):
This is not like a for loop in some other languages; it’s iterating over a list returned (once) by range. When you change c later, it does not affect this loop.
You can use while instead:
c = len(a)
while i < c - 2:
if a[i] == a[i + 1]:
del a[i]
c = len(a)
else:
i += 1
There’s also itertools.groupby:
import itertools
def remove_consecutive(l):
return (k for k, v in itertools.groupby(l))
Here's a slightly different approach:
origlist=[1, 5, 2, 3, 3, 1, 2, 3, 5, 6]
newlist=[origlist[0]]
for elem in origlist[1:]:
if (elem != newlist[-1]):
newlist.append(elem)
The itertools answer above may be preferred, though, for brevity and clarity...

Python (2.x) list / sublist selection -1 weirdness

So I've been playing around with python and noticed something that seems a bit odd. The semantics of -1 in selecting from a list don't seem to be consistent.
So I have a list of numbers
ls = range(1000)
The last element of the list if of course ls[-1] but if I take a sublist of that so that I get everything from say the midpoint to the end I would do
ls[500:-1]
but this does not give me a list containing the last element in the list, but instead a list containing everything UP TO the last element. However if I do
ls[0:10]
I get a list containing also the tenth element (so the selector ought to be inclusive), why then does it not work for -1.
I can of course do ls[500:] or ls[500:len(ls)] (which would be silly). I was just wondering what the deal with -1 was, I realise that I don't need it there.
In list[first:last], last is not included.
The 10th element is ls[9], in ls[0:10] there isn't ls[10].
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10] doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:
>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10
when slicing an array;
ls[y:x]
takes the slice from element y upto and but not including x. when you use the negative indexing it is equivalent to using
ls[y:-1] == ls[y:len(ls)-1]
so it so the slice would be upto the last element, but it wouldn't include it (as per the slice)
-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".
so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3].
The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.
I hope this is somewhat understandable.