Lua: Unexpected Iteration Result with Table - loops

I was playing around in Lua with a simple 'isPrime' function I made, and, ignoring the actual 'isPrime' function, which is irrelevant to this query, wrote the following code:
out = {}
for i = -10,20 do
out[i] = isPrime(i)
end
for k,v in ipairs(out) do
print(k,v)
end
My expectation was that the program would print every single key and its respective value, -10 through 20, but found instead that only 1 through 20 were printed. -10 through 0 were in the table, I found, after checking specifically for those key-value pairs, but oddly, they were never printed.
Can anyone explain why this happened? I feel I do not fully understand how Lua iterates and accesses its keys through the ipairs() function.

ipairs(t) will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value. That's not what you want. Just use the style of your first loop
for i = -10,20 do
print(i, out[i])
end

Related

Unable to find a correct output for the two-sum problem

Please mention the logical error in the below code as I am not getting a correct output. Also, do share the correct one to get an output of the indices only.
def find2Sum(A,X):
n=len(A)
for i in range(0,n):
l=[]
if X-A[i] in A:
l.append(i)
return l
nums = [1,4,6,44, 9,8]
target = 14
find2Sum(nums,target)
#Pradeepta Sahu
When you have target=8 the answer for nums=[1,4,6,44, 9,8] should be none because there are no such numbers. But with your code logic X-A[i] in A this for i = 1 will result into 8-4==4 and it will append index to L. This is the main logical bug in the code that you have written. Any number that is target/2 will be passed by your condition.
Aside this you also declared your list var inside the for loop but you are returning it outside the for loop.
This is wrong
for i in range(0,n):
l=[]
This is right
l=[]
for i in range(0,n):

Matlab, save output in array , loop

I want to create an array that can store the outputs each time that doing a loop. I think the problem is because in a every new iteration the numbers starts counting from the beginning so it stores only the last iteration! In each iteration the output is an array(7x3) so in total I have to have (28,3).But I tried a lot and i AM GETTING AN ARRAY (28,3) all with zeros except the last 7 rows.
Thank you very much
You can see the code below:
for t=1:ncell % in my case I have 4 cells
ti=sort(T,2)
tt= sort(Cell{t}.ExBot,2)
tq= sort(Cell{t}.ExTop,2)
te= sort(Cell{t}.ExBT,2)
%k=0
z=0
cc=[]
%%%%% for exbottom
I=ones(size(ti,1),1);
for j=1:size(tt,1)
for i=1:size(ti,1)
if tt(j,:)==ti(i,:)
k=k+1 ;
%c(k,:)=[ti(j,:), ti(j+1,:)]
I(i)=0;
cc(k,:)=Y(i,:);
cc(size(tt,1)+1,:)=cc(1,:)
else
end
end
end
end
Although more info would help as mentioned in the comments, from the information you've given, the problem is most likely in setting cc to empty when you start processing each cell.
cc=[];
On exiting the outermost loop you will only have results for the last iteration.
On a related note you may want to use isequal or all for the comparison of vectors i.e. if isequal(tt(j,:),ti(i,:))

Adding odd numbers in an array not providing the correct output

one of my ruby programs that detects odd numbers in an array and adds them together does not provide the correct output. Given that I am learning ruby and this is a logic mistake, I can't easily deduct where I make a mistake.
Here is the Code:
def odd_sum(numbers)
index = 0
result = 0
while index < numbers.length
if (numbers[index] % 2 != 0)
result += 1
end
index +=1
return result
end
end
puts odd_sum([1,2,4,5,7,9]) currently my output is 1 should be 22
puts odd_sum([0,6,4,4]) currently output 0
puts odd_sum([1,2,1]) currently output 1 should be 2
Question: Why is my output wrong? Any way to make this cleaner or better?
I'm running all this in a program called oddball.rb on cloud9.
return result will cause the code to exit right then and there... it will only ever add up the first number, then exit the whole method forever... it will never look at the other elements of the array.
Having now indented your code properly you can see that this line is inside the while loop...
probably you want that to be outside the while loop... it is much easier to see this kind of bug when you properly indent your code. You should always indent your code... it seems unimportant until you come across a bug like this... it's always important. it's a good habit to start now. ;)
have a look at your if-statement: result+=1, don't add 1 but add the the number you are currently testing: result += numbers[index]
SiS
def odd_sum(numbers)
index = 0
result = 0
while index < numbers.length
if (numbers[index] % 2 != 0)
result += 1
end
index +=1
return result
end
end
puts odd_sum([1,2,4,5,7,9]) currently my output is 1 should be 22
puts odd_sum([0,6,4,4]) currently output 0
puts odd_sum([1,2,1]) currently output 1 should be 2
On the line result += 1, you are adding 1 each time there is an odd number, so it's not a sum, but rather a count.
On the line return result, the program will immediately end when it hits the return. So, since the first number in the first array is odd, the program increments result by 1, and then returned result.
What you want to do is result += numbers[index], and return the result at the end of the while loop.
In Ruby, there's often a better way to do things, while loops are meant for when you don't know how many times you are looping. In this case, you know exactly how many times, so I would suggest using an iterator.
def odd_sum(numbers)
result = 0
numbers.each do |num|
result += num if num.odd?
end
end
Or even better
def odd_sum(numbers)
numbers.select(&:odd?).reduce(&:+)
end

How do I subtract a value from each element of an array in Lua?

I am trying to write a function to find the variance of a data set.
I am stuck on a small problem. I have an array, and I want to find how far each element in the array is from the average. Here is a simplified version of what I wrote:
>y={1,2,3}
>y_average=2
>y_diff={}
>for key, value in pairs(y) do y_diff[key]=(y[key]-y_average)
>>return unpack(y_diff)
>>end
-1
what I want to get: -1, 0, 1
Why does it only give me the first value and not all three?
Your return is breaking the loop in the first iteration as mentioned in a comment. Try this:
for i in ipairs(y) do
y_diff[i] = y[i] - y_average
end
print( table.concat(y_diff, '\t') )
table.concat doesn't have a limit on the amount of elements it can handle and it would be what you would use if you wanted to put these elements in a file faster than writing them one by one.

Basic Python loop

How does Python know what "i" is when it is not defined, shouldn't there be an error? Probably a simple explanation, but I am new to learning Python.
def doubles (sum):
return sum * 2
myNum = 2
for i in range (0,3):
myNum = doubles(myNum)
print (myNum)
Haha :-) People are marking down your question, but I know that is one question must have came in every person's mind. Specially those who learned Python through Online courses and not through a teacher in person.
Well let me explain that in layman's term,
The method that you used is specially used for 1) lists and 2) lists within lists.
For eg,
example1= ['a','b','c'] # This is a simple list
example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.
Now, 'a','b' & 'c' are items in list.
So by saying,
for i in example1:
print i
we are actually saying,
for item in the list(example1):
print item
-------------------------
People use 'i', probably taken as abbreviation to item, or something else.
I don't know the history.
But, the fact is that, we can use anything instead or 'i' and Python will still consider it as an item in list.
Let me give you examples again.
example1= ['a','b','c'] # This is a simple list
example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.
for i in example1:
print i
[out]: a
b
c
now in example2, items are lists within lists. --- also, now i will use the word 'item' instead of 'i' --- the results regardless would be the same for both.
for item in example2:
print item
[out]: ['a','b','c']
['a','b','c']
['a','b','c']
people also use singulars and plurals to remember things,
so lets we have a list of alphabet.
letters=['a','b','c','d']
for letter in letters:
print letter
[out]: a
b
c
d
Hope that helps. There is much more to explain.
Keep researching and keep learning.
Regards,
Md. Mohsin
Using a variable as a loop control variable does assign to it each time through the loop.
As to "what it is"... Python is dynamically typed. The only thing it "is" is a name, just like any other variable.
i is assigned the value in the loop itself, it has no value (it is not defined) before the Python interpreter reaches the for line.
Its similar to how other for loops define variables. In C++ for example:
for(int i=0; i<5; i++){
cout << i << endl;
}
Here the variable i is only exists once the for loop is called.
i is assigned a value when the for loop runs, so the Python interpreter will not raise an error when the loop is run
long story short it creates a new variable without having to be defined and its value is whatever number your loop is on, for example if you had written:
num = 0
for i in range(3):
print(num)
num = num + 1
so for the first time this loop ran 'i' would equal 0 (because python lists/loops etc always start on 0 not 1), the second time it would equal 1, etc. and the 'num' you can ignore it's just an example of code you could have in a loop which would print out numbers in ascending order.
Levin

Resources