Try and Except statement - Automate The Boring Stuff {collatz() program} - python-3.7

I have been trying to complete a task from automate the boring stuff.
This is the task."Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.
Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.Add try and except statements to the previous project to detect whether the user types in a noninteger string."
def collatz(num):
ev_odd = num % 2 #detecs whether number is odd or even
if ev_odd == 1:
num = num * 3 + 1
else:
num = num//2
print(num)
global number
number = num
#the program
print('enter an integer')
number = int(input())
collatz(number)
while number != 1:
collatz(number)
i made this code it is working fine.But I am unable to use try and except statement to this..Help me out. Other recommendation to improve this code are requested.
Regards

Related

How to save and pass a variable in Matlab

I can find / identify all digits in a number using a recursive function.
My issue is trying to sum the number through each recursion.
I had to initialize sum = 0 at the top of my function statement, and when I return through recursion, I'm always resetting sum back to zero. I do not know how to save a variable without first initalizing it.
Code is below;
function output= digit_sum(input)
sum=0
if input < 10
output = input
else
y=rem(input,10);
sum=sum+y
z=floor(input/10);
digit_sum(z)
end
output=sum
end

unique with "with" operator in systemverilog

I am a new SystemVerilog user and I have faced a strange (from my point of view) behavior of combination of unique method called for fixed array with with operator.
module test();
int arr[12] = '{1,2,1,2,3,4,5,8,9,10,10,8};
int q[$]
initial begin
q = arr.unique() with (item > 5 ? item : 0);
$display("the result is %p",q);
end
I've expected to get queue {8,9,10} but instead I have got {1,8,9,10}.
Why there is a one at the index 0 ?
You are trying to combine the operation of the find method with unique. Unfortunately, it does not work the way you expect. unique returns the element, not the expression in the with clause, which is 0 for elements 1,2,3,4 and 5. The simulator could have chosen any of those elements to represent the unique value for 0(and different simulators do pick different values)
You need to write them separately:
module test();
int arr[$] = '{1,2,1,2,3,4,5,8,9,10,10,8};
int q[$]
initial begin
arr = arr.find() with (item > 5);
q = arr.unique();
$display("the result is %p",q);
end
Update explaining the original results
The with clause generates a list of values to check for uniqueness
'{0,0,0,0,0,0,0,8,9,10,10,8};
^. ^ ^ ^
Assuming the simulator chooses the first occurrence of a replicated value to remain, then it returns {arr[0], arr[7], arr[8], arr[9]} from the original array, which is {1,8,9,10}

Race condition using a code segment

Please help me to get an idea to solve this question.I have tried several sequence to race condition, but i couldn't get a correct one.
every time the value of x is same.
This is the way I've tried
Under the assumption that a line isn't to be considered an atomic operation, you can split up any of the lines modifying x based on its own value into a read and write part. Doing this only for one, for example from the increase function, yields:
y = 5;
int temporary = x; // read value
temporary += y;
x = temporary; // write modified value back
x++; // this could be split up similarly
z = /* whatever */;
With this "expanded" code sequence you should have no problem finding sequences of operations with different result values for x.

Return " i " value when if-statement is true

I have created a matrix with row 1 full of strings and 4 other rows with numbers. They are created in a handle class with the object "Projekter".
So in the object "Projekter" row 1, the first value is blank, but the second value is 'Ole'. So I know that 'Ole' is in (1,2). x is the name/string I want to search for, which in this case is 'Ole'.
As you see below it should search row 1 from column 2 untill the last name/string and if i = 'Ole', it should bring me the value 2 because " i " should be equal 2.
A is just a controller if the function works, but at this point it doesn't.
The error it gives is "Undefined function 'eq' for input arguments of type 'cell'."
How do I fix this so it return the " i " value when the statement is correct?
Thank you in advance!
function number(obj,x)
A = [];
for i = 2:size(obj.Projekter,2)
if obj.Projekter(1,i)==x
A = A + 1;
end
end
disp(A)
end
Maybe you have to index the cell content:
your_cell = {'a_string'};
your_string = your_cell{1};
function [returnValue] = number(obj,x)
for i = 2:size(obj.Projekter,2)
if obj.Projekter{1,i}==x
returnValue = i;
return;
end
end
end
Note the change from obj.Projekter(1,i)==x to obj.Projekter{1,i}==x (use curly braces instead of parens). I have then specified that returnValue will hold the value that should be returned by doing function [returnValue] = number(obj,x). We then set returnValue equal to i and return from the function when the condition of the if statement is true.
As suggested in the comments, it is probably better to do:
function [returnValue] = number(obj, x)
returnValue = find(strcmp(x, obj.Projekter) == 1);
strcmp(x, obj.Projektor) will give you an array the length of obj.Projekter with 1's wherever the strings match, and 0's where they don't, you can then find the indices that are set to 1. This has the added benefit of
not using a loop so it's faster
Giving you every occurrence of a match, not just the first one.

Error using minus in MATLAB

temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));
This line gives the following error:
Error using ==> minus
Not enough input arguments.
The following are the definitions of pb and pw.
pw=struct('fitness',[],'pos',{});
pb=struct('fitness',[],'pos',{});
pos is a 2 x 1 array.
When tracking down errors like this, I break the problem up into smaller bits. Especially when the logic isn't readily apparent. Not only does it provide a path that can be used to step through your function using the debugger, but it also makes it more readable.
I've taken liberty with the intermediate variable names.
thisPb = pb(1,num);
thisPw = pw(1,num);
initialPos= pw.pos(i,1);
finalPos = pb.pos(i,1);
whos initialPos finalPos
temp(i,1) = rand(1) * (finalPos - initialPos);
The line with whos will print out the values. Make sure that finalPos and initialPos are both numbers.
One way that you can get this error is when num is an empty matrix.
The expression
>> s(x).a
can return a variable number of outputs, depending on the size of x.
If x = [1,2,3] for example, it will return three values (as long as s has at least three elements).
If x = [] on the other hand, then s(x).a will return no outputs, so the expression
>> disp(s(x).a)
will give you a Not enough input arguments error, which is almost certainly what you're seeing. You should check that num is not empty.
Are you sure, that all values are really initialised? Try to check this before your codeline.
disp(pb(1,num).pos(i,1))
disp(pw(1,num).pos(i,1))
temp(i,1) = rand(1)*(pb(1,num).pos(i,1) - pw(1,num).pos(i,1));