Why isn't my return statement working? - function

I have a function that converts a decimal value to binary. I understand I have the logic correct as I can get it to work outside of a function.
def decimaltobinary(value):
invertedbinary = []
value = int(value)
while value >= 1:
value = (value / 2)
invertedbinary.append(value)
value = int(value)
for n, i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n] = 0
else:
invertedbinary[n] = 1
invertedbinary.reverse()
value = ''.join(str(e) for e in invertedbinary)
return value
decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)
Let's say firstvalue = 5 and secondvalue = 10. The values returned each time the function is executed should be 101 and 1010 respectively. However, the values I get printed are the starting values of five and ten. Why is this happening?

The code works as expected, but you didn't assign the returned value:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
Note that there are easier ways to accomplish your goal:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'

Related

COUNTIFS: Excel to pandas and remove counted elements

I have a COUNTIFS equation in excel (COUNTIFS($A$2:$A$6, "<=" & $C4))-SUM(D$2:D3) where A2toA6 is my_list. C4 is current 'bin' with the condition and D* are previous summed results from my_list that meet the condition. I am attempting to implement this in Python
I have looked at previous COUNTIF questions but I am struggling to complete the final '-SUM(D$2:D3)' part of the code.
See the COUNTIFS($A$2:$A$6, "<=" & $C4) section below.
'''
my_list=(-1,-0.5, 0, 1, 2)
bins = (-1, 0, 1)
out = []
for iteration, num in enumerate(bins):
n = []
out.append(n)
count = sum(1 for elem in my_list if elem<=(num))
n.append(count)
print(out)
'''
out = [1, [3], [4]]
I need to sum previous elements, that have already been counted, and remove these elements from the next count so that they are not counted twice ( Excel representation -SUM(D$2:D3) ). This is where I need some help! I used enumerate to track iterations. I have tried the code below in the same loop but I can't resolve this and I get errors:
'''
count1 = sum(out[0:i[0]]) for i in (out)
and
count1 = out(n) - out(n-1)
''''
See expected output values in 'out' array for bin conditions below:
I was able to achieve the required output array values by creating an additional if/elif statement to factor out previous array elements and generate a new output array 'out1'. This works but may not be the most efficient way to achieve the end goal:
'''
import numpy as np
my_list=(-1,-0.5, 0, 1, 2)
#bins = np.arange(-1.0, 1.05, 0.05)
bins = (-1, 0, 1)
out = []
out1 = []
for iteration, num in enumerate(bins):
count = sum(1 for elem in my_list if elem<=(num))
out.append(count)
if iteration == 0:
count1 = out[iteration]
out1.append(count1)
elif iteration > 0:
count1 = out[iteration] - out[iteration - 1]
out1.append(count1)
print(out1)
'''
I also tried using the below code as suggested in other answers but this didn't work for me:
'''
-np.diff([out])
print(out)
'''

Use varargin for multiple arguments with default values in MATLAB

Is there a way to supply arguments using varargin in MATLAB in the following manner?
Function
func myFunc(varargin)
if a not given as argument
a = 2;
if b not given as argument
b = 2;
if c not given as argument
c = a+b;
d = 2*c;
end
I want to call the above function once with b = 3 and another time while the previous one is running in the same command window with a = 3 and c = 3 and letting b take the default value in the function this time. How can it be done using varargin?
Here's the latest and greatest way to write the function (using arguments blocks from R2019b)
function out = someFcn(options)
arguments
options.A = 3;
options.B = 7;
options.C = [];
end
if isempty(options.C)
options.C = options.A + options.B;
end
out = options.A + options.B + options.C;
end
Note that this syntax does not allow you to say options.C = options.A + options.B directly in the arguments block.
In MATLAB < R2021a, you call this like so
someFcn('A', 3)
In MATLAB >= R2021a, you can use the new name=value syntax
someFcn(B = 7)
Here are two ways to do this which have been available since 2007a (i.e. a long time!). For a much newer approach, see Edric's answer.
Use nargin and ensure your inputs are always in order
Use name-value pairs and an input parser
nargin: slightly simpler but relies on consistent input order
function myFunc( a, b, c )
if nargin < 1 || isempty(a)
a = 2;
end
if nargin < 2 || isempty(b)
b = 2;
end
if nargin < 3 || isempty(c)
c = a + b;
end
end
Using the isempty check you can optionally provide just later arguments, for example myFunc( [], 4 ) would just set b=4 and use the defaults otherwise.
inputParser: more flexible but can't directly handle the c=a+b default
function myFunc( varargin )
p = inputParser;
p.addOptional( 'a', 2 );
p.addOptional( 'b', 2 );
p.addOptional( 'c', NaN ); % Can't default to a+b, default to NaN
p.parse( varargin{:} );
a = p.Results.a;
b = p.Results.b;
c = p.Results.c;
if isnan(c) % Handle the defaulted case
c = a + b;
end
end
This would get used like myFunc( 'b', 4 );. This approach is also agnostic to the input order because of the name-value pairs, so you can also do something like myFunc( 'c', 3, 'a', 1 );

adding functions to self made calculator

Ok so I'm trying to make a working napier numeral calculator. I have gone through most of the steps I need to make it work. I need 2 more steps the function and converting it back to napier numbers. Currently I'm stuck on getting the functions to work. It just seems to skip that step. From what I can tell it should work and not be skipped. Could anyone tell me if I missed a step in the process of making the function.
def main():
response = 'y'
while response == 'y' or response == 'Y':
nap1 = getNapier()
num1 = napToInt(nap1)
print(num1)
nap2 = getNapier()
num2 = napToInt(nap2)
print(num1, num2)
operator = getOperator
result = doMath(num1, num2, operator)
response = input("Try another[y/n]")
def doMath(num1, num2, operator):
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "*":
answer = num1 * num2
else:
if operator == "/":
answer = num1 / num2
return doMath
def getOperator():
op = input("Enter operator: ")
while op not in "+-*/":
op = input("Error!!!! Enter operator: ")
return op
def napToInt(n):
result = 0
for ch in n:
result += 2 ** (ord(ch) - ord('a'))
return result
def getNapier():
nap = input("Enter Napier number: ")
while not nap.isalpha():
nap = input("Error!!! Enter Napier number: ")
return nap
main()
this is the result I get as you can see it gets the napier numbers and just stops
Enter Napier number: asdf
262185
Enter Napier number: adsf
262185 262185
Try another[y/n]
your line operator = getOperator should be operator = getOperator()

python function will not return value that is based on condition

I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def printStock(stockList, stockPrice, p):
for i in range(len(stockPrice)):
if stockPrice[i] > p:
p = stockList[i]
print("The stocks with a higher value are:", p)
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
searchStock(stockList, stockPrice, s)
p = s
printStock(stockList, stockPrice, p)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I also get an error saying "unorderable types int() > str()" regarding line 3. Basically the function printStock takes the three parameters and once the function is done it should print the names of the stocks higher than the value 'p'. The value of 'p' is the same as the value I get after calling searchStock function, but I cant seem to get it to work. Can someone please help me?
s is being returned from the function, but the return value is not being assigned to any variable on the outer scope.
Just replace
searchStock(stockList, stockPrice, s)
with
s=searchStock(stockList, stockPrice, s)
And everything should work as expected

HowTo: select all rows in a cell array, where a particular column has a particular value

I have a cell array, A. I would like to select all rows where the first column (for example) has the value 1234 (for example).
When A is not a cell array, I can accomplish this by:
B = A(A(:,1) == 1234,:);
But when A is a cell array, I get this error message:
error: binary operator `==' not implemented for `cell' by `scalar' operations
Does anyone know how to accomplish this, for a cell array?
The problem is the expression a(:,1) == 1234 (and also a{:,1} == 1234).
For example:
octave-3.4.0:48> a
a =
{
[1,1] = 10
[2,1] = 13
[3,1] = 15
[4,1] = 13
[1,2] = foo
[2,2] = 19
[3,2] = bar
[4,2] = 999
}
octave-3.4.0:49> a(:,1) == 13
error: binary operator `==' not implemented for `cell' by `scalar' operations
octave-3.4.0:49> a{:,1} == 13
error: binary operator `==' not implemented for `cs-list' by `scalar' operations
I don't know if this is the simplest or most efficient way to do it, but this works:
octave-3.4.0:49> cellfun(#(x) isequal(x, 13), a(:,1))
ans =
0
1
0
1
octave-3.4.0:50> a(cellfun(#(x) isequal(x, 13), a(:,1)), :)
ans =
{
[1,1] = 13
[2,1] = 13
[1,2] = 19
[2,2] = 999
}
I guess the Class of A is cell. (You can see in the Workspace box).
So you may need to convert A to the matrix by cell2mat(A).
Then, just like Matlab as you did: B = A(A(:,1) == 1234,:);
I don't have Octave available at the moment to try it out, but I believe that the following would do it:
B = A(A{:,1} == 1234,:);
When dealing with cells () returns the cell, {} returns the contents of the cell.