def fn():
theList = []
for rev in range(5, 0, -1):
theList.append(rev)
print(theList)
fn()
I don't understand, why this won't execute?
My goal is to print something like this
[5,4,3,2,1,0]
[4,3,2,1,0]
[3,2,1,0]
[2,1,0]
[1,0]
[0]
Edit 1. Okey i added the comma(,) but the result is this
[5]
[5, 4]
[5, 4, 3]
[5, 4, 3, 2]
[5, 4, 3, 2, 1]
Which is not what i am looking for
You can get your output like this:
def fn():
theList = list(range(5, -1, -1))
for idx in range(len(theList)):
print(theList[idx:])
fn()
Output:
[5, 4, 3, 2, 1, 0]
[4, 3, 2, 1, 0]
[3, 2, 1, 0]
[2, 1, 0]
[1, 0]
[0]
Your code is using the wrong approach. Basically, your output shows that the list is full initially and goes on popping one element from the left on each iteration. Your approach starts with an empty list and adds an element on each iteration.
Also, range(5, 0, -1) is not the list you think it is. This is because the range function ignores the end value which is 0 here.
If you did this list(range(5, 0, -1)), you'd get [5, 4, 3, 2, 1] which obviously doesn't contain 0. So, to get the list you want, you'd have to do list(range(5, -1, -1)) like in the code above.
1)There is a typo in your function:
for rev in range(5, 0, -1):
2) you need to use your rev:
for rev in range(5, -1, -1):
print(range(rev,-1,-1))
Related
Im trying to get a percentaje from a list of numbers, but it is a little different than the usual methods.
Bassically I need to sum the first index of the list with the last index of the same list. I want the script to do this repeatedly until the lenght of the list equals 2.
Something like this:
list = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
list = [2, 2, 3, 2, 2]
list = [4, 4, 3]
list = [7, 4] #here the lenght = 2, so it stops.
final_list = [7, 4]
percentaje = f"%{final_list[0]}{final_list[1]}"
#OUTPUT
#"%74"
Can someone help me to do this? Im not so good with loops :(
This?
L = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
while len(L) > 2:
new_L = [L[i]+L[len(L)-1-i] for i in range(len(L)//2)]
if len(L)%2:
new_L.append(L[len(L)//2]) # add middle term alone if any
L = new_L
print(f"%{L[0]}{L[1]}")
list1 = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
while len(list1)!=2:
for i in range (0, int(len(list1)/2)):
list1[i] = list1[i] + list1[len(list1)-1]
list1 = list1[:-1]
print(list1)
output:
[7, 4]
How can I get product of nested list :
[[-1, 3, 1],[6, 1, 2],[4, 3, 1],[0, 1, 1]]
to:
[-3,12,12,1]
where eg : -1 * 3 * 1 = -3 and so on.
This is my current solution :
for i in range(len(array2)):
for j in range(len(array2[i])):
prod = array2[i][j] * array2[i][j + 1] * array2[i][j + 2]
print(prod)
I'm getting the following error :
IndexError: list index out of range
You might look at operator.mul combined with functools.reduce for this to make it short and very clear and totally avoid indexing (which is often the source of small errors):
from operator import mul
from functools import reduce
l = [[-1, 3, 1],[6, 1, 2],[4, 3, 1],[0, 1, 1]]
[reduce(mul, s) for s in l]
# [-3, 12, 12, 0]
Edit based on comment
If you want to ignore zeros, you can simply filter them out (this assumes that you don't have rows of all zeros, in which case it's not clear what the answer would be):
[reduce(mul, filter(None, s)) for s in l]
# [-3, 12, 12, 1]
Your index is out of bounds when you get j+1 and j+2, the correct way is to stop at len-2
array2 = [[-1, 3, 1],
[6, 1, 2],
[4, 3, 1],
[0, 1, 1]]
for i in range(len(array2)):
for j in range(len(array2[i])-2): # Check here the range
prod = array2[i][j] * array2[i][j + 1] * array2[i][j + 2]
print(prod)
Try the following function:
input_list = [[-1, 3, 1], [6, 1, 2], [4, 3, 1], [0, 1, 1]]
def compute_multiplication(nested_list):
for l in nested_list:
res = 1
for element in l:
res *= element
print(res)
With the final line being:
compute_multiplication(input_list)
This provides the following output:
-3
12
12
0
my_list = [[-1,3,1],[6,1,2],[4,3,1],[0,1,1]]
products = []
for sub_list in my_list:
partial_prod = 1
for item in sub_list:
partial_prod = partial_prod * item
products.append(partial_prod)
A solution using numpy.prod() :
import numpy
matrix = [
[-1, 3, 1],
[6, 1, 2],
[4, 3, 1],
[0, 1, 1]
]
for row in matrix:
prod = numpy.prod(row)
print(prod)
Assumption is that there are only three entries per row : a list comprehension should suffice. Multiply each item by the other in each row :
matrix = [
[-1, 3, 1],
[6, 1, 2],
[4, 3, 1],
[0, 1, 1]
]
first, make a condition to change zero values to 1 (this is based on the condition, that 0 be ignored and only the result of non zeros be returned)
filtered = [[ent if ent!= 0 else 1 for ent in row ] for row in matrix]
multiply each entry by the other
res = [start*middle*end for start,middle,end in filtered]
#[-3, 12, 12, 1]
if the number of entries is more than three, then #mark meyer's solution is apt for this
I wish to write a for loop that prints the tail of an array, including the whole array (denoted by i==0) Is this task possible without a branching logic, ie a if i==0 statement inside the loop?
This would be possible if there is a syntax for slicing with inclusive end index.
arr=[0,1,2,3,4,5]
for i in range(0,3):
print arr[:-i]
output:
[]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
wanted output:
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
You can use None:
arr=[0,1,2,3,4,5]
for i in range(0,3):
print arr[:-i or None]
for i in xrange(0, 3):
print arr[:(len(arr) - i)]
# Output
# [0, 1, 2, 3, 4, 5]
# [0, 1, 2, 3, 4]
# [0, 1, 2, 3]
The awkwardness arises from trying to take advantage of the :-n syntax. Since there's no difference between :0 and :-0, we can't use this syntax to distinguish 0 from the start from 0 from the end.
In this case it is clearer to use the :i indexing, and adjust the range accordingly:
In [307]: for i in range(len(arr),0,-1): print(arr[:i])
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2]
[0, 1]
[0]
arr[:None] means 0 from the end, and usually is sufficient.
Keep in mind the arr[:i] translates to arr.__getitem__(slice(None,i,None)). The : syntax is short hand for a slice object. And the slice signature is:
slice(stop)
slice(start, stop[, step])
slice itself is pretty simple. It's the __getitem__ method that gives it meaning. You could, in theory, subclass list, and give it a custom __getitem__ that treats slice(None,0,None) as slice(None,None,None).
Had a brain freeze, but this would do:
arr=[0,1,2,3,4,5]
for i in range(0,3):
print arr[:len(arr)-i]
Although I still wish python had nicer syntax to do these kind of simple tasks.
This question already has answers here:
python: most elegant way to intersperse a list with an element
(15 answers)
Closed 6 years ago.
I have a list like
[1, 2, 3, 4, 5]
and I want to add zeroes at odd indexes:
[1, 0, 2, 0, 3, 0, 4, 0, 5]
My first thought was to create a list with zeroes and replace them with the values from the original list.
listOfZeros = [0] * (2*len(list)-1)
j = 0
for i in range(0, len(listOfZeros)):
if (i%2 == 0):
listOfZeros[i] = h_temp[j]
j += 1
This actually works, but I do dislike for loops and adding another counter j. Isn't there a better way by using slicing?
You can use insert(). Looking at your output, assuming you are not counting index 0 as even.
a = [1,2,3,4,5]
for x in range(len(a)):
a.insert(2*x+1, 0)
one way is by using zip:
a = [1, 2, 3, 4, 5]
d = [x for t in zip (a, [0] * len(a)) for x in t][:-1]
When you use zip, you create list of tuples.
a = [1,2,3,4,5]
b = [0,0,0,0,0]
c = zip(a,b)
#zip (a,b) creates [(1,0),(2,0),(3,0),(4,0),(5,0)]
Then you loop over the set of tuples to arrange them into list:
d = [x for t in c for x in t] #creates [1,0,2,0,3,0,4,0,5,0]
and cut the last element (since you end with 5)
[x for t in c for x in t][:-1] #take out the last 0
#resulting in [1,0,2,0,3,0,4,0,5]
then you are done.
You can do it with a generator:
def zero_on_odd(mylist):
for i in mylist:
yield i
yield 0
a = [1, 2, 3]
with_zeros = list(zero_on_odd(a))[:-1]
If you want to go functional...
from itertools import chain, repeat
_list = [1,2,3,4,5]
list(chain(*zip(_list, repeat(0))))[:-1]
# [1, 0, 2, 0, 3, 0, 4, 0, 5]
If you want to be silly...
[int(i) for i in '0'.join(str(i) for i in _list)]
# still [1, 0, 2, 0, 3, 0, 4, 0, 5]
Or, if you want to be functional AND silly...
map(int, '0'.join(map(str, _list)))
# really, it's still [1, 0, 2, 0, 3, 0, 4, 0, 5]
# except in Python 3.X, there it's a map object...
But, you should probably opt for one of the custom generator solutions.
For the fun of it, here is an itertools solution:
from itertools import islice, chain
data = [1,2,3,4,5]
print list(islice(chain.from_iterable((x, 0) for x in data), 0, 2 * len(data)-1))
Giving:
[1, 0, 2, 0, 3, 0, 4, 0, 5]
Another zip way:
>>> li
[1, 2, 3, 4, 5]
>>> [e for t in zip(li,[0]*(len(li)-1)) for e in t]+[li[-1]]
[1, 0, 2, 0, 3, 0, 4, 0, 5]
You can also use range and slice assignment:
>>> li=[1,2,3,4,5]
>>> for i in range(1,len(li)+len(li)-1, 2): li[i:i]=[0]
...
>>> li
[1, 0, 2, 0, 3, 0, 4, 0, 5]
And, a list comprehension:
>>> [li[i/2] if not i%2 else 0 for i in range(len(li)*2-1)]
[1, 0, 2, 0, 3, 0, 4, 0, 5]
A hacky way:
>>> ls1 = [1, 2, 3, 4, 5]
>>> ls2 = []
>>> list(ls2.extend([n, 0]) for n in ls1)
[None, None, None, None, None]
>>> ls2
[1, 0, 2, 0, 3, 0, 4, 0, 5, 0]
Sorry if this is a duplicate. If I have a list of lists:
j0 = [i for i in range(4)]
j1 = [j0 for j in range(4)]
>>> [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
I can get an element from each list in turn using a list comprehension:
print [j1[k][k] for k in range(0,4)]
>>> [0, 1, 2, 3]
But I want an element from each list starting from the end (so working backwards), so the desired output is:
>>> [3, 2, 1, 0] # One item from each list
I tried this but its obviously wrong because j1[0][0] = 0:
print [j1[k][-k] for k in range(0,4)]
>>>[0, 3, 2, 1]
I can use the following, but is there a nicer way using a list comprehension?
nl = []
l = 0
for i in range(-1, -5, -1):
nl.append(j1[l][i])
l += 1
print nl
This is very similar to what you have tried. You had the right idea with -k, but have to subtract it from the length (along with another -1 since python indices start at 0).
print [j1[k][len(j0) - 1 - k] for k in range(0,4)]
[3, 2, 1, 0]
you can try
print [j1[k][k] for k in range(3, -1, -1)]