Selecting NumPy array range, including the last element - python

If I want to select all elements of a NumPy array, up to index N, I can write:
x = my_array[:N]
For example, if I want to select all elements, up to index 5, I can write:
N = 5
x = my_array[:N]
Or, if I want to select all elements, up to and including the penultimate element, I can write:
N = -1
x = my_array[:N]
But what if I want to select all elements up to and including the final element? How can I do this using the above notation?
I tried:
N = -0
x = my_array[:N]
But this returns a blank array.
p.s. Yes, I could just write out x = my_array[:], but I need it to be in the format my_array[:N], where N is defined dynamically.

Using your method:
N = len(my_array)
x = my_array[:N]
You could then specify any arbitrary value of N if you only wish to slice up to that index. You could also specify the length of your array directly, if known.
To illustrate this...
my_array = [1, 2, 3, 4, 5]
N = len(my_array)
x = my_array[:N]
my_array == x
...returns True.

Related

Pad both sides of 1D array while keeping edge indices

Given a 1D array x of size n and some index i where 0 <= x <= len(arr), I would like to be able to extract x[i] along with l neighboring elements to the left and l neighboring elements to the right, like this:
>>> i = 5
>>> l = 2
>>> x = np.arange(9,)
>>> def crop_array(arr):
'''do something'''
>>> crop_array(x)
array([2,3,4,5,6])
The thing is, I would like to keep all of these arrays the same size, so if i = 1 - l < 0, then I want to pad the array to yield something like array([0,1,2,3,4]). The would also hold true in cases where i + l > len(x), except the padding would be on the other side.
I'm trying to pad both sides of the array and then slice it:
def crop_array(arr, l, i):
x = np.zeroes(len(arr) + 2 * l)
x[l:len(x)-l] = arr
but I'm not sure how I can make it so that I can reindex the array to get the elements I want.
Whoops, figured it out. I can just add l to i.

Need to remove every third element in a list of 10 elements - getting index error

I keep getting IndexError: list assignment index out of range. My logic is as follows: The print(x) shows that 6 is printed out before getting the error. Working through the code logically, 6 % 4 == 0 is true, so the code should delete numbers[6 - 1] which is numbers[5]. After that, x is incremented to 7, and the loop will not iterate again.
Can someone please point out where I am incorrect? TIA.
# create list from user specifications
numbers = []
size = int(input("Enter the number of elements: "))
for i in range(0, size):
numbers.append(int(input("Enter an element: ")))
# Iterate through each element. If an elements index is a multiple of 3,
# delete it.
x = 1
while x <= size:
print(x)
if ((x) % 3) == 0:
del(numbers[x - 1])
x = x + 1
print("The list is: ")
print(numbers)
The problem is that the array changes size during the loop. When the index is indeed a multiple of three, the del operation removes the element from the array, thus numbers no longer have a size of size, but your index variable x will still go up to the value of size-1 which is above the last index of your modified array.
An easy way is to build a copy of the list instead of removing elements from it, and ignoring all elements with index multiple of 3.
# create list from user specifications
numbers = []
size = int(input("Enter the number of elements: "))
for i in range(0, size):
numbers.append(int(input("Enter an element: ")))
# Iterate through each element. If an elements index is a multiple of 3,
# delete it.
x = 1
filtered = []
while x <= size:
print(x)
if not ((x % 3) == 0):
filtered.append(numbers[x-1])
x = x + 1
numbers = filtered
print("The list is: ")
print(numbers)
When you delete an item in a list, the remaining items shift left, changing their index. After the first delete, you either have to change your index value or use a different technique completely. Python is well suited for filtering lists with "comprehensions". Use that, and the enumerate function that will emit the values plus their index, and you can simplify this greatly.
numbers = [1,2,3,4,5,6,7,8,9,10]
numbers = [value for index, value in enumerate(numbers, 1) if index % 3]
print(numbers)

How can I make my output group all numbers together?

So I'm trying to find how to group similar numbers into different lists. I tried looking at some sources like (Grouping / clustering numbers in Python)
but all of them requires the importation of itertools and use itertools.groupby, which I dont want because I dont want to use built in functions.
Here is my code so far.
def n_length_combo(lst, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(lst)):
m = lst[i]
remLst = lst[i + 1:]
for p in n_length_combo(remLst, n - 1):
l.append([m] + p)
return l
print(n_length_combo(lst=[1,1,76,45,45,4,5,99,105],n=3))
Edit: n: int represents the number of groups permitted from one single list, so if n is 3, the numbers will be grouped in (x,...), (x,....) (x,...) If n = 2, the numbers will be grouped in (x,..),(x,...)
However, my code prints out all possible combinations in a list of n elements. But it doesnt group the numbers together. So what I want is: for instance if the input is
[10,12,45,47,91,98,99]
and if n = 2, the output would be
[10,12,45,47] [91,98,99]
and if n = 3, the output would be
[10,12] [45,47] [91,98,99]
What changes to my code should I make?
Assuming n is the number of groups/partitions you want:
import math
def partition(nums, n):
partitions = [[] for _ in range(n)]
min_, max_ = min(nums), max(nums)
r = max_ - min_ # range of the numbers
s = math.ceil(r / n) # size of each bucket/partition
for num in nums:
p = (num - min_) // s
partitions[p].append(num)
return partitions
nums = [10,12,45,47,91,98,99]
print(partition(nums, 2))
print(partition(nums, 3))
prints:
[[10, 12, 45, 47], [91, 98, 99]]
[[10, 12], [45, 47], [91, 98, 99]]
You are trying to convert a 1d array into a 2d array. Forgive the badly named variables but the general idea is as follows. It is fairly easy to parse, but basically what we are doing is first finding out the size in rows of the 2d matrix given the length of the 1d matrix and desired number of cols. If this does not divide cleanly, we add one to rows. then we create one loop for counting the cols and inside that we create another loop for counting the rows. we map the current position (r,c) of the 2d array to an index into the 1d array. if there is an array index out of bounds, we put 0 (or None or -1 or just do nothing at all), otherwise we copy the value from the 1d array to the 2d array. Well, actually we create a 1d array inside the cols loop which we append to the lst2 array when the loop is finished.
def transform2d(lst, cols):
size = len(lst)
rows = int(size/cols)
if cols * rows < size:
rows+=1
lst2 = []
for c in range(cols):
a2 = []
for r in range(rows):
i = c*cols + r
if i < size:
a2.append(lst[i])
else:
a2.append(0) # default value
lst2.append(a2)
return lst2
i = [10,12,45,47,91,98,99]
r = transform2d(i, 2)
print(r)
r = transform2d(i, 3)
print(r)
the output is as you have specified except for printing 0 for the extra elements in the 2d array. this can be changed by just removing the else that does this.

I want to create array problem using python

You all have seen how to write loops in python. Now is the time to implement what you have learned.
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].
Input Format:
The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)
Output Format:
Print the resultant array elements separated by a space. (no space after the last element)
Example:
Input:
4
2 5 3 1
Output:
3883
Explanation:
Here array A is [2,5,3,1] os reverse of this array is [1,3,5,2] and hence the resultant array is [3,8,8,3]
My solution is not working.
my solution is:
r=input()
r=int(r)
result_t = []
d=[]
for i in range(0, r):
c=input()
c=int(c)
t = i
result_t.append(c)
d=reversed(result_t)
d=int(d)
s=result_t+d
for i in range(0, r):
print(s[i])
You just need to loop over both result_t and d. You can use zip() to combine two lists so you can loop over them in parallel:
r=input()
r=int(r)
result_t = []
for i in range(r):
c=input()
c=int(c)
result_t.append(c)
d = reversed(result_t)
result = [x + y for x, y in zip(result_t, d)]
print(result.join(" "))
You can also do it without making the reversed list.
result = [x + result_t[-(i+1)] for i, x in enumerate(result_t)]
When you use a negative index in a list, it counts from the end. You have to add 1 before negating, because the last element is -1 (since -0 is the same as 0, which is the first element).
"can only concatenate list (not "list_reverseiterator") to list"
reversed(result_t) returns not the list but iterator
try:
rev = []
for i in reversed(result_t):
rev.append(i)
print(rev)
Try This One:
x = input()
result_t = [int(x) for x in input().split()]
rev = [x for x in reversed(result_t)]
result = [int(x) + int(y) for x, y in zip(result_t, rev)]
for i in result:
print(i,end=" ")
Here array A is [2,5,3,1] and reverse of this array is [1,3,5,2] and hence the resultant array is [3,8,8,3].
a = []
n = int(input("Enter the number of elements"))
for i in range(n):
x = int(input("Enter the elements"))
a.append(x)
print(a)
res = []
b = [None] * len(a)
for i in range(0, len(a)):
b[i] = a[i]
b.reverse()
print(b)
for i in range(0, len(a)):
res.append(a[i] + b[i])
print(res)

How to combine two or more lists by adding each element [duplicate]

This question already has answers here:
How to sum columns of an array in Python
(13 answers)
Closed 4 years ago.
I have lists that contain only integers like [1,2,3] and [4,5,6]. Some times I even have [7,8,9] or more lists. How do I add each elements together to form a new list of the same length?
[1,2,3] + [4,5,6] + [7,8,9] = [12,15,18]
I know that the above would just append the elements and create a longer list (with 9 elements), but instead I would like to add the lists element-wise.
You can put the lists in a list, zip the sub-lists after unpacking them with the * operator, and map the sum to a list:
l = [[1,2,3], [4,5,6], [7,8,9]]
print(list(map(sum, zip(*l))))
This outputs:
[12, 15, 18]
Edit: The above is for Python 3.x. If you're using an earlier version, you can use itertools.izip instead of zip, and you would not need to call the list constructor:
import itertools
l = [[1,2,3], [4,5,6], [7,8,9]]
print map(sum, itertools.izip(*l))
Numpy is well suited for this task, although it might be slight overkill for your case.
Let's say you have
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
You can turn them into an array and sum across them:
np.array([x, y, z]).sum(axis=0)
You could use a similar approach with regular lists and zip:
[sum(col) for col in zip(x, y, z)]
You can do it like this:
#Create the list
x = [1,2,3,12,13]
y = [4,5,7,11]
z = [7,8,9,14,15,16]
#create a list with the list length
lenList = [len(x),len(y),len(z)]
finalList = []
#get the minimum and maximum list length
minLen = min(lenList)
maxLen = max(lenList)
#if the three list have the same length then you can simply sum the element
if(maxLen == minLen):
for j in range(maxLen):
finalList.append(x[j]+y[j]+z[j])
else:
#if the list have different length look for the minimum value
while(lenList[0] != lenList[1] or lenList[0] != lenList[2]):
minLen = min(lenList)
maxLen = max(lenList)
#if the min len is the x list then add some zero
if(lenList.index(minLen) == 0):
#change the len to the max len
lenList[0] = maxLen
for a in range(minLen,maxLen):
x.append(0)
#if the min len is the y list then add some zero
elif(lenList.index(minLen) == 1):
lenList[1] = maxLen
for b in range(minLen,maxLen):
y.append(0)
#if the min len is the z list then add some zero
elif(lenList.index(minLen) == 2):
lenList[2] = maxLen
for c in range(minLen,maxLen):
z.append(0)
#sum all the element
for j in range(0,maxLen):
finalList.append(x[j]+y[j]+z[j])
print finalList
output:
[12, 15, 19, 37, 28, 16]
Comments:
This program can sum all the list element and insert the result in another list. You can sum 3 list, with infinite element and without having the same list length. If you need to sum more list just edit this part:
while(lenList[0] != lenList[1] or lenList[0] != lenList[2]):
minLen = min(lenList)
maxLen = max(lenList)
#if the min len is the x list then add some zero
if(lenList.index(minLen) == 0):
#change the len to the max len
lenList[0] = maxLen
for a in range(minLen,maxLen):
x.append(0)
#if the min len is the y list then add some zero
elif(lenList.index(minLen) == 1):
lenList[1] = maxLen
for b in range(minLen,maxLen):
y.append(0)
#if the min len is the z list then add some zero
elif(lenList.index(minLen) == 2):
lenList[2] = maxLen
for c in range(minLen,maxLen):
z.append(0)
Here you can add:
elif(lenList.index(minLen) == 3):
lenList[3] = maxLen
for c in range(minLen,maxLen):
listN.append(0)
After that you have to add the list:
#Create the list
x = [1,2,3,12,13]
y = [4,5,7,11]
z = [7,8,9,14,15,16]
listN = [0,0,0]
#create a list with the list length
lenList = [len(x),len(y),len(z),len(listN)]
And in the sum iteration you have to change:
#sum all the element
for j in range(0,maxLen):
finalList.append(x[j]+y[j]+z[j],listN[j])
an alternative method if you know the length of the sub lists are 3
a = [1,2,3] + [4,5,6] + [7,8,9]
[sum([a[3*q+i] for q in range(len(a)//3)]) for i in range(len(a)//3)]
output
[12,15,18]
alternatively
dicta = {q:i for q,i in enumerate(a)}
[sum([dicta[3*q+i] for q in range(len(a)//3)]) for i in range(len(a)//3)]
you can just swap the 3's out with what ever length you use, but since you showed in your code that they where already laid to gether, i wouldn't be able to read it automaticly. What goes for the alternative solution, then dictionaries uses hashes so if your list gets big it won't be a problem.

Categories