Appending elements while looping using append() is correct and it's a built-in method within Python lists.
However you can have the same result:
Using list comprehension:
result_t = [k for k in range(1,6)]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using + operator:
result_t = []
for k in range(1,6):
result_t += [k]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using special method __iadd__:
result_t = []
for k in range(1,6):
result_t.__iadd__([k])
print(result_t)
>>> [1, 2, 3, 4, 5]
Answer from Chiheb Nexus on Stack OverflowLoop over an an array of array
python - Iterating through a for loop with the size of an array - Stack Overflow
Why iterate over an array using the index?
Storing arrays in Python for loop - Stack Overflow
How does a 'for loop' work in Python?
Can a 'for loop' in Python be nested within another 'for loop'?
How can I iterate over a list using a 'for loop' in Python?
Videos
Appending elements while looping using append() is correct and it's a built-in method within Python lists.
However you can have the same result:
Using list comprehension:
result_t = [k for k in range(1,6)]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using + operator:
result_t = []
for k in range(1,6):
result_t += [k]
print(result_t)
>>> [1, 2, 3, 4, 5]
Using special method __iadd__:
result_t = []
for k in range(1,6):
result_t.__iadd__([k])
print(result_t)
>>> [1, 2, 3, 4, 5]
The range function returns an iterator in modern Python. The list function converts an iterator to a list. So the following will fill your list with the values 1 to 5:
result_t = list(range(1,6)) # yields [1, 2, 3, 4, 5]
Note that in order to include 5 in the list, the range argument has to be 6.
Your last example doesn't parse unless you assign t a value before the loop. Assuming you do that, what you're doing in that case is modifying t each time through the loop, not just producing a linear range. You can get this effect using the map function:
t = 0
b = 2
def f(i):
global t
t = i + b*t
return t
result_b = list(map(f, range(1, 5))) # Yields [1, 4, 11, 26]
The map function applies the f function to each element of the range and returns an iterator, which is converted into a list using the list function. Of course, this version is more verbose than the loop, for this small example, but the technique itself is useful.
Your solution seems correct - but it seems u have a couple of syntax errors if you're using python
You also have to re-initialize sum1 & sum2 between test cases. Right now you get the total sum of all arrs rather than arr[x]-hopefully that makes sense. You also have to remove duplicate numbers from the sum. For instance, if you're getting the sum of all numbers up to 20 - you'll end up adding 15 twice as it is divisible by 3 and 5. So the inner for loops will add it twice to the sum. So you'll need to remove 15 to get rid of duplicates.
for x in range(len(arr)): #by default range starts at o. therefore, range(len(arr)) = range(0, len(arr))
sum1 = 0 # you forgot to initialize sum1
sum2 = 0 # you forgot to initialize sum2
duplicates = 0 #you have to remove duplicates from the answer
for b5 in range (0, arr[x], 5): #you have to add the colons here
sum1 = sum1 + b5
for b3 in range (0, arr[x], 3): #you have to add the colons here
sum2 = sum2 + b3
for dup in range(0, arr[x], 3*5): # removes duplicates from the final sum
duplicates = duplicates + dup
sum = sum1 + sum2 - duplicates
print(sum)
This is an O(n^2) solution - you can drop it down to O(n) using a little bit of math.
You'll notice that the inner for loops can be represented using the formula sum(n)=ฮฃd*i=d*ฮฃi-where the summation starts at i = 0, end at โ(n-1)/dโ and d is the divisor (in the case of your question d=3 or 5).
for b5 in range (0, arr[x], 5):
sum1 = sum1 + b5
(https://en.wikipedia.org/wiki/Summation)
There is a very common summation formula that is commonly used to convert summations into a closed-form expression (something with finite steps - which is O(1))
ฮฃi=n*(n+1)/2
In the case of the inner loop - it would be sum(n) = d*(โ(n-1)/dโ)*(โ(n-1)/dโ+1)/2.
let,
f(n,d) = (โ(n-1)/dโ+1)/2
Therefore, the solution to your problem would be f(n,3)+f(n,5)-f(n,3*5)
Which would convert the inner for loops from O(n) to O(1). Which, means your entire solution would be O(n).
I'll let you figure out the code on your own. However, theoretically, there is a better solution; such that as arr grows indefinitely the work scales linearly rather than quadratically.
- Create Array with input number (Eg.
arr = [12, 15, 4]) - Iterate over the created Array
- In
forloop check if number are divisible by 3 and 5
Sample code:
arr = [12, 15, 4]
total = 0
for num in arr:
if num % 3 == 0 and num % 5 == 0:
total = total + num
print(total) # 15
I'm probably missing something major here, but it seems like in most educational contexts online like Leetcode and courses and such, when the examples iterate over an array they do so like:
array = [1,2,3,4,5]
for i in range(len(array)):
print(array[i])rather than just iterating the thing:
for i in array:
print(i)I'm guessing it's to do with time complexity since indexing arrays is quick, but what's the problem with the latter approach?
As comments and other answers have already laid out, a good way to do this is to store the arrays being returned by numpyarrayfunction in a normal Python list.
If you want everything to be in a single numpy array (for, say, memory efficiency or computation speed), and the arrays returned by numpyarrayfunction are of a fixed length n, you could make numpyarray multidimensional:
numpyarray = np.empty((5, n))
for i in range(5):
numpyarray[i, :] = numpyarrayfunction
Then you could do np.average(numpyarray, axis = 1) to average over the second axis, which would give you back a one-dimensional array with the average of each array you got from numpyarrayfunction. np.average(numpyarray) would be the average over all the elements, or np.average(np.average(numpyarray, axis = 1)) if you really want the average value of the averages.
More on numpy array indexing.
I initially misread what was going on inside the for loop there. The reason you're getting an error is because numpy arrays will only store numeric types by default, and numpyarrayfunction is returning a non-numeric value (from the name, probably another numpy array). If that function already returns a full numpy array, then you can do something more like this:
arrays = []
for i in range(5):
arrays.append(numpyarrayfunction(args))
Then, you can take the average like so:
avgarray = np.zeros((len(arrays[0])))
for array in arrays:
avgarray += array
avgarray = avgarray/len(arrays)