Efficiently insert numbers - NumPy / Python - python

Returns a new vector where every element is separated by 4 consecutive zeros. Trying to achieve [4,2,1] --> [4,0,0,0,0,2,0,0,0,0,1]
def zero_insert(x):
y = np.zeros((5*(len(x)-1))+1, dtype=np.int)
for i in range(len(x)):
y[5*i] = x[i]
return y

Initialize and assign -
x = np.asarray(x) # convert to array
n = 4 # number of zeros to be inserted
N = n+1
out = np.zeros((len(x)-1)*N+1,dtype=x.dtype)
out[::N] = x

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.

How to check if an integer is greater than another by a certain value in python?

How could I check if the integers in y are greater than x by 2 or more?
For example if I have these variables and want to only return 7 and 10:
x = 3
y = [1,3,4,7,10]
x = 3
y = [1,3,4,7,10]
out = [] # list to store values
# Make a loop
for v in y:
if v - x >= 2: # check if greater than x by 2 or more
out.append(v) # store value
You can simply do
x = 3
y = [1,3,4,7,10]
threshold = 2
print([ele for ele in y if (ele-x) >= threshold])
Add 2 to x and compare with that.
x = 3
x_plus_2 = x + 2
result = [item for item in y if item >= x_plus_s]
You can use the NumPy package like this:
import numpy as np
x = 3
# Convert y to NumPy array
y = np.array([1,3,4,7,10])
y[y >= x+2]

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)

max n * n Reshape 2d numpy array function that discards lowest values and returns sum of col means?

I am working on this problem for my data science class:
Write a function that takes in an integer, and does the following:
Creates an array of the numbers from 0 up to that inputted integer
Reshapes it to be the largest n * n array that it could be, discarding any elements that are extra (i.e. if you want to make a 10 x 10, but have 102 elements, discard the last 2)
Returns the cumulative sum of the column means
I have the following code so far for the matrix reshaping, but it times out for large numbers. Any suggestions on how to complete the first step of this problem would be much appreciated.
import numpy as np
def ranged_arr(n):
ranged_arr = np.arange(0,n+1,1)
if len(ranged_arr)%int(len(ranged_arr)**0.5)== 0:
array = ranged_arr.reshape(int(len(ranged_arr)**0.5),int(len(ranged_arr)**0.5))
return array
else:
len(ranged_arr)%int(len(ranged_arr)**0.5)!= 0
idx = 0
new_arr = np.arange(0,n-idx,1)
while len(new_arr)%int(len(new_arr)**0.5)!= 0:
idx +=1
q = new_arr.reshape(int(len(new_arr)**0.5),int(len(new_arr)**0.5))
return q
From the code that #Alber8295 started, the rest of the problem:
def ranged_arr(n):
#Creates an array of the numbers from 0 up to that inputted integer
ranged_arr = np.arange(0,n+1)
#Reshapes it to be the largest n * n array that it could be
#Find the largest dim
largest_dim = math.floor(math.sqrt(n+1))
#Find the size of the array that will be reshaped
last_index = largest_dim**2
#Take the slice of the original array that could be reshaped
fitted_ranged_arr = ranged_arr[:last_index]
#Finally, reshape it!
reshaped_range_arr = fitted_ranged_arr.reshape((largest_dim,largest_dim))
# get the sum of the col means
#get the means of each col
col_means = np.mean(reshaped_range_arr,axis=0)
# get the sum of the means
sum_of_means = col_means.sum()
#Return everything, so you can check the steps
return ranged_arr,largest_dim,fitted_ranged_arr,reshaped_range_arr,col_means, sum_of_means
print(sum_of_means)
Let's keep it sweet and simple :)
First, let's decompose your problem, you have to:
1. Create an array of the numbers from 0 up to that inputted integer
2. Reshape it to be the largest m x m array that it could be
2.1. Find the largest dimension (m)
Now let's write that Python function!
def ranged_arr(n):
#Creates an array of the numbers from 0 up to that inputted integer
ranged_arr = np.arange(0,n+1)
#Reshapes it to be the largest n * n array that it could be
#Find the largest dim
largest_dim = math.floor(math.sqrt(n+1))
#Find the size of the array that will be reshaped
last_index = largest_dim**2
#Take the slice of the original array that could be reshaped
fitted_ranged_arr = ranged_arr[:last_index]
#Finally, reshape it!
reshaped_range_arr = fitted_ranged_arr.reshape((largest_dim,largest_dim))
#Return everything, so you can check the steps
return ranged_arr,largest_dim,fitted_ranged_arr,reshaped_range_arr
I uploaded it to my Github so you can check it with some tests here

indexerror in python with beaglebone black

y[i] = ADC.read("P9_40")
IndexError: list assignment index out of range
the code:
i = 1
x = []*1000
y = []*1000
for i in range(1000):
y[i] = ADC.read("P9_40") # adc input pin
x[i] = (int)(y*2147483648) # conversion of float to int
this code is read data from analogue pin of beaglebone black and store the result in array
In python you can't call a uncreated index of a list
x = []*1000 #creates only one empty list not 1000 list of list
y = []*1000 #like wise here
It should rather be like this
x = [[] for i in range(1000)]
y = [[] for i in range(1000)]
You don't create a 1000 element list by doing:
x = [] * 1000
y = [] * 1000
What you should do is create it with None values:
x = [None] * 1000
y = [None] * 1000
and then you can overwrite those None in your loop. None is better than
any integer value (like 0) that might come out of ADC.read(), as you can
check if the whole list is updated afterwards.

Categories