Outputs of a program - output

I am new to programming and I would like to know how to solve questions like this. I was told to expect questions like this on the exam. Can someone please tell me how I would go about solving something like this? Thanks.
x = 0
for num in range(5):
if num % 2 == 0:
x = x + 2
else:
x = x + 1
print(x)

You need to work on a skill which is to "be the compiler", in the sense that you should be able to run code in your head. Step through line by line and make sure you know what is happening. In you code example, you have
for num in range(5) means you will be iterating with num being 0,1,2,3 and 4. Inside the for loop, the if statement num % 2 == 0 is true when num/2 does not have a remainder (how % mods work). So if the number is divisible by 2, x = x+2 will execute. The only numbers divisible by 2 from the for loop are 0,2 and 4. so x=x+2 will execute twice. The else statement x = x +1 runs for all other numbers (1,3) which will execute 2 times.
Stepping through the for loop:
num = 0 //x=x+2, x is now 2
num = 1 //x=x+1, x is now 3, print(x) prints 3
num = 2 //x=x+2, x is now 5
num = 3 //x=x+1, x is now 6, print(x) prints 6
num = 4 //x+x+2, x is now 8
Therefore the answer is that 3 and 6 will be printed

In my opinion,
Whatever language you are using, you need to learn some common elements of the modern programming languages, such as flow-control (if...else in your case), loop(for, in your case)
Some common used functions, in your case, you need to what does range do in Python,
docs.python.org is a good place for you.
As you are new to programming, you can go with the flow in you mind or draw it on the paper.
Using x to store our final result
loop through every item in [0, 1, 2, 3, 4] <- range(5)
a. if
the number is divisible by 2
then increase x by adding 2 to it.
b. else
increase x by adding 1 and print it out
So the result would be :
3
6

Related

Finding generators of a finite field

How to find generators of a finite field Fp[x]/f(x) with f(x) is a irreducible polynomial over Fp.
Input: p (prime number), n (positive number), f (irreducible polynomial)
Output: g (generator)
I have p = 2, n =3, f = x^3 + x + 1
I am a newbie so I don't know where to start.
Do you have any solution? Plese help me step by step
To find a generator (primitive element) α(x) of a field GF(p^n), start with α(x) = x + 0, then try higher values until a primitive element α(x) is found.
For smaller fields, a brute force test to verify that powers of α(x) will generate every non-zero number of a field can be done.
cnt = 0
m = 1
do
cnt = cnt + 1
m = (m*α)%f(x)
while (m != 1)
if cnt == (p^n-1) then α(x) is a generator for GF(p^n).
For a faster approach with larger fields, find all prime factors of p^n-1. Let q = any of those prime factors. If α(x) is a generator for GF(p^n), then while operating in GF(p^n):
α(x)^(p^n-1) % f(x) == 1
α(x)^((p^n-1)/q) % f(x) != 1, for all q that are prime factors of p^n-1
In this case GF(2^3) is a 3 bit field and since 2^3-1 = 7, which is prime, then it's just two tests, shown in hex: x^3 + x + 1 = b (hex)
α(x)^7 % b == 1
α(x)^1 % b != 1
α(x) can be any of {2,3,4,5,6,7} = {x,x+1,x^2,...,x^2+x+1}
As another example, consider GF(2^4), f(x) = x^4 + x^3 + x^2 + x + 1 (hex 1f). The prime factors of 2^4-1 = 15 are 3 and 5, and 15/3 = 5 and 15/5 = 3. So the three tests are:
α(x)^f % 1f == 1
α(x)^5 % 1f != 1
α(x)^3 % 1f != 1
α(x) can be any of {3,5,6,7,9,a,b,e}
For larger fields, finding all prime factors of p^n-1 requires special algorithms and big number math. Wolfram alpha can handle up to around 2^128-1:
https://www.wolframalpha.com/input/?i=factor%282%5E64-1%29
This web page can factor large numbers and includes an explanation and source code:
https://www.alpertron.com.ar/ECM.HTM
To test for α(x)^(large number) = 1 or != 1, use exponentiation by repeated squaring while performing the math in GF(p^n).
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
For large fields, where p^n is greater than 2^32 (4 billion), a primitive polynomial where α(x) = x is searched for, using the test mentioned above.

Compute the mean of each element, the previous and the next in a row vector, for all elements starting from the second one - vectorized implementation

I'd like to compute the mean of each element, the previous and the next in a row vector, for all elements starting from the second one, and I'd like to do it with a vectorized implementation.
Suppose I have this row vector:
a = [4, 7, 1, 3, 2];
what I want to obtain is:
b = [4, 3.66, 2, 1.66];
which is, in turn, the mean of the subsequent triplets:
[4 7 1], [7 1 3], [1 3 2], [3 2 0] (the zero is conventional).
By the way, approximation to two figures is irrelevant here, it's just for the sake of the example.
I have come up with this code:
a = [4 7 1 3 2];
function shifted = generateShiftedValues(rowVec)
shifted = rowVec;
for i=2:3
shifted(i, :) = [rowVec(1, i:end), zeros(1, i-1)];
endfor
endfunction
b = mean(generateShiftedValues(a)(:, 1:end-1), 1)
but what I'd like to have is a fully vectorized implementation.
Is that possible? Any ideas?
Thank you very much indeed.
Convolution is the key to success.
I would go for this:
a = [4 7 1 3 2]
n = 3;
b = conv(a, ones(n, 1)) / n;
b = b(3:end-1)
a =
4 7 1 3 2
b =
4.00000 3.66667 2.00000 1.66667
One could easily build a generalized solution for any number of elements to be averaged and arbitrary "starting point". If you need such, maybe provide a general description in your question. If that "special case" is sufficient, that's all.
Hope that helps!

Writing Fibonacci Sequence Elegantly Python

I am trying to improve my programming skills by writing functions in multiple ways, this teaches me new ways of writing code but also understanding other people's style of writing code. Below is a function that calculates the sum of all even numbers in a fibonacci sequence up to the max value. Do you have any recommendations on writing this algorithm differently, maybe more compactly or more pythonic?
def calcFibonacciSumOfEvenOnly():
MAX_VALUE = 4000000
sumOfEven = 0
prev = 1
curr = 2
while curr <= MAX_VALUE:
if curr % 2 == 0:
sumOfEven += curr
temp = curr
curr += prev
prev = temp
return sumOfEven
I do not want to write this function recursively since I know it takes up a lot of memory even though it is quite simple to write.
You can use a generator to produce even numbers of a fibonacci sequence up to the given max value, and then obtain the sum of the generated numbers:
def even_fibs_up_to(m):
a, b = 0, 1
while a <= m:
if a % 2 == 0:
yield a
a, b = b, a + b
So that:
print(sum(even_fibs_up_to(50)))
would output: 44 (0 + 2 + 8 + 34 = 44)

idl radius of each pixel

I'm completely new to coding and have almost no idea what I'm doing. Currently I'm trying to find the radius of each pixel from the center of a galaxy in a fits file. I was told to try this by creating a blank array the same size as the fits file and I'm trying to use a for loop for each x value and another for each y. So far, I have the array and have attempted to create the for loops.
xcenter =249.8
ycenter =250.0
d=fltarr(500,500)
for i=0,499 do begin
d=d(i-xcenter,*)
endfor
for j=0,499 do begin
d=d(j-ycenter,*)
endfor
I know this look awful and I obviously have no idea what I'm doing. So if anyone can offer any help at all I'd be grateful.
Let's look at a simpler version first. Suppose you have 10 points on a line, and you want to calculate the distance of each point from some xref. IDL supports vector math, so you can do this:
xref = 5.4
x = dindgen(10)
distance = abs(x - xref)
I have used the DINDGEN command here, and you can look up the help. Now in a 2d case, you want 2-d arrays: one will be a 500 * 500 array containing the X coordinate of each pixel, the other containing the Y coordinate. So the arrays will have to be of the form,
0 1 2 3 ...
0 1 2 3 ...
0 1 2 3 ...
and
0 0 0 0 ...
1 1 1 1 ...
2 2 2 2 ...
We can generate them using the # operator. Note that IDL counts from 0 by default.
just_one = replicate(1d, 500) ; contains 1 1 1 1 ...
one_500 = dindgen(500) ; contains 0.0 1.0 2.0 ...
x = just_one # one_500
y = one_500 # just_one
Now you can calculate the distance as usual, d = sqrt(xx + yy), but using vector math again:
distance = sqrt( (x - xref) ^ 2 + (y - yref) ^ 2 )
This is a 500x500 array, which contains the distance of each pixel from your xref, yref points.

Iterating through matrix rows in Octave without using an index or for loop

I am trying to understand if it's possible to use Octave more efficiently by removing the for loop I'm using to calculate a formula on each row of a matrix X:
myscalar = 0
for i = 1:size(X, 1),
myscalar += X(i, :) * y(i) % y is a vector of dimension size(X, 1)
...
The formula is more complicate than adding to a scalar. The question here is really how to iterate through X rows without an index, so that I can eliminate the for loop.
Yes, you can use broadcasting for this (you will need 3.6.0 or later). If you know python, this is the same (an explanation from python). Simply multiply the matrix by the column. Finnaly, cumsum does the addition but we only want the last row.
newx = X .* y;
myscalars = cumsum (newx, 1) (end,:);
or in one line without temp variables
myscalars = cumsum (X .* y, 1) (end,:);
If the sizes are right, broadcasting is automatically performed. For example:
octave> a = [ 1 2 3
1 2 3
1 2 3];
octave> b = [ 1 0 2];
octave> a .* b'
warning: product: automatic broadcasting operation applied
ans =
1 0 6
1 0 6
1 0 6
octave> a .* b
warning: product: automatic broadcasting operation applied
ans =
1 2 3
0 0 0
2 4 6
The reason for the warning is that it's a new feature that may confuse users and is not existent in Matlab. You can turn it off permanentely by adding warning ("off", "Octave:broadcast") to your .octaverc file
For anyone using an older version of Octave, the same can be accomplished by calling bsxfun directly.
myscalars = cumsum (bsxfun (#times, X, y), 1) (end,:);