Python Function- Return Value is 'not defined' - function

For my encryption code, I am trying to a return a value from one function because it is used in the next. I keep getting an error, telling me that the name 'cipher_text' is not defined. Please help!
Error:
(line 7)
decryption (cipher_text, shift)
NameError: name 'cipher_text' is not defined
def main():
user_input = input ("Enter string: ")
shift = int(input ("Enter a shift that is between 1 and 26: "))
while shift<1 or shift>26:
shift = input ("ERROR: Shift must be between 1 and 26: ")
encryption (user_input, shift)
decryption (cipher_text, shift)
frequency (user_input)
def frequency(user_input):
freq_char = None
for char in user_input:
charcount = user_input.count(char)
if (charcount != 0):
freq_char = char
print (freq_char)
return fre_char
def encryption(user_input, shift):
cipher_text = ''
for char in user_input: #for every character in input
if char == ' ':
cipher = char
cipher_text += cipher
else:
cipher_num = (ord(char))+(shift)%26 #using ordinal to find the number
cipher= ''
cipher = chr(cipher_num)# using chr to convert back to a letter
cipher_text += cipher
print ("The encrypted text is:",cipher_text)
return(cipher_text)
def decryption (cipher_text, shift):
decrypt_text = ''
cipher_text = ''
for char in cipher_text: #for every character in the encrpted text
decrypt_num = (ord(char))+(int(shift))%26
decrypt= ''
decrypt = chr(decrypt_num)
decrypt_text += decrypt
print("The decrypted text is:", decrypt_text)
return(decrypt_text)
main()

Your problem is in the lines
encryption (user_input, shift)
decryption (cipher_text, shift)
as the exception tells you. If you had included the traceback with your question this would be very clear.
Variables you declare in one function are local to that function. This is a good thing! It lets you write functions like
def foo():
x = 1
return x * x
def bar():
for x in xrange(10):
print "Count: %s" % x
without them blowing each other up.
If you call a function that returns something and you want to use it, you need to use it directly, or assign it to something:
# assign
x = foo()
print x
# use directly
print "x is %s" % foo()
in your case, you can make a minimal change to assign the result of encryption to a new variable cipher_text
def main():
...
cipher_text = encryption(user_input, shift)
decryption(cipher_text, shift)
it would be equivalent (though less clear) to call this anything else
foobar = encryption(user_input, shift)
decryption(foobar, shift)
or even to avoid use of a variable altogether
decryption(encryption(user_input, shift), shift)

def main() should be def main(cipher_text)
You can also set a default value for cipeher_text:
def main(cipher_text=""):
user_input = input ("Enter string: ")
shift = int(input ("Enter a shift that is between 1 and 26: "))
while shift<1 or shift>26:
shift = input ("ERROR: Shift must be between 1 and 26: ")
encryption (user_input, shift)
decryption (cipher_text, shift)
frequency (user_input)
And then just call main() using a value example main('some value') or just empty if you defined a default value as said before.

Related

Read a binary array with mixed types

I am writing a function similar to this to read in binary formatted .ply files.
The linked function reads the header and the skips to the binary array, reading that in with numpy and I would like to do the same in Octave.
My code for reading the header is
fid = fopen('/path/to/file.ply');
tline = fgetl(fid); % read first line
len = 0;
prop = {};
dtype = {};
fmt = 'binary';
while ~strcmp(tline, "end_header")
len = len + length(tline) + 1; % increase header length, +1 includes EOL
tline = strsplit(tline); % split string
if strcmp('format', tline{1}) && strcmp('ascii', tline{2}) % test whether file is ascii
fmt = 'ascii';
end
if strcmp('element', tline{1}) && strcmp('vertex', tline{2}) % number of points
N = tline{3};
end
if strcmp('property', tline{1}) % identify fields
dtype = [dtype, tline{2}];
prop = [prop, tline{3}];
end
tline = fgetl(fid);
end
len = len + length(tline) + 1; % add 'end_header' to len
So I have arrays of data types
dtype =
{
[1,1] = float
[1,2] = float
[1,3] = float
[1,4] = int
[1,5] = int
[1,6] = int
[1,7] = float
[1,8] = float
[1,9] = float
}
and I know the shape of the array.
N = 61415
Is there a function that replicates numpy's fromfile and can I seek to the right location in my file (I know where the binary data starts in the file as I have len)
Following #tasos-papastylianou answer I tried
fseek(fid, len);
fread(fid, 3, 'float')
Which returns the correct 3 values, but the next value is an integer and therefore gives the incorrect answer.
fread(fid, 4, 'float')
arr =
-1.4298e+00
-5.3943e+00
1.6623e+01
1.5274e-43 <<<< should be 109
My solution
function pts = read_ply(fn)
fid = fopen(fn);
tline = fgetl(fid); % read first line
len = 0;
prop = {};
% dtype_map = {'float': 'f4', 'uchar': 'B', 'int':'i'}
dtype = {};
fmt = 'binary';
while ~strcmp(tline, "end_header")
len = len + length(tline) + 1; % increase header length, +1 includes EOL
tline = strsplit(tline); % split string
if strcmp('format', tline{1}) && strcmp('ascii', tline{2}) % test whether file is ascii
fmt = 'ascii';
elseif strcmp('element', tline{1}) && strcmp('vertex', tline{2}) % number of points
N = str2num(tline{3});
elseif strcmp('property', tline{1}) % identify fields
dtype = [dtype, tline{2}];
prop = [prop, tline{3}];
endif
tline = fgetl(fid);
endwhile
len = len + length(tline) + 1; % add 'end_header
% total file length minus header
fseek(fid, 0, 1);
file_length = ftell(fid) - len;
types = struct('float', 4, 'int', 4, 'float64', 8);
pts = struct();
seek_plus = 0;
for i = 1:length(prop)
fseek(fid, len + seek_plus);
dt = types.(dtype{i}); % dtype for field
pts.(prop{i}) = fread(fid, N, dtype{i}, int32(file_length / N) - dt);
seek_plus = seek_plus + dt;
endfor
This does not answer my original question as it involves a loop, but it seems fairly efficient. Arrays can be constructed as so.
xyz = [pts.x, pts.y, pts.z];
Your question confuses me a bit towards the end, since the most direct equivalent to numpy's saving an array in a numpy-specific binary format is octave's save which saves an array to an octave-specific binary format.
Having said that, this doesn't sound like what you want so I'm assuming the fromfile reference is a red herring.
In general if you have a binary file you want to open, read, or seek (i.e. place the cursor at a particular position), you can use the fopen, fread, and fseek commands. Also useful, ftell, frewind, etc.
These are all fairly simple commands. Just have a look at their documentation in the terminal (e.g. help fseek ).

Verilog conditional assign outputs X where there should be 1

I am currently building a sign extender in Verilog based on the one present in the ARMv8 processor, but after the first result is extended, every subsequent result makes a 1 in the output into an X. How do I get rid of the X?
The module and the quick test bench I made are shown below.
Sign Extender:
`timescale 1ns / 1ps
module SignExtender(BusImm, ImmIns);
output [63:0] BusImm;
input [31:0] ImmIns;
wire extBit;
assign extBit = (ImmIns[31:26] == 6'bx00101) ? ImmIns[25]:
(ImmIns[31:24] == 8'bxxx10100) ? ImmIns[23]:
(ImmIns[31:21] == 11'bxxxx1000xx0) ? ImmIns[20]:
1'b0;
assign BusImm = (ImmIns[31:26] == 6'bx00101) ? {{38{extBit}}, ImmIns[25:0]}:
(ImmIns[31:24] == 8'bxxx10100) ? {{45{extBit}}, ImmIns[23:5]}:
(ImmIns[31:21] == 11'bxxxx1000xx0) ? {{55{extBit}}, ImmIns[20:12]}:
64'b0;
assign BusImm = 64'b0;
endmodule
Test Bench:
`timescale 1ns / 1ps
`define STRLEN 32
`define HalfClockPeriod 60
`define ClockPeriod `HalfClockPeriod * 2
module SignExtenderTest;
task passTest;
input [63:0] actualOut, expectedOut;
input [`STRLEN*8:0] testType;
inout [7:0] passed;
if(actualOut == expectedOut) begin $display ("%s passed", testType); passed = passed + 1; end
else $display ("%s failed: 0x%x should be 0x%x", testType, actualOut, expectedOut);
endtask
task allPassed;
input [7:0] passed;
input [7:0] numTests;
if(passed == numTests) $display ("All tests passed");
else $display("Some tests failed: %d of %d passed", passed, numTests);
endtask
reg [7:0] passed;
reg [31:0] in;
wire [63:0] out;
SignExtender uut (
.BusImm(out),
.ImmIns(in)
);
initial begin
passed = 0;
in = 32'hF84003E9;
#10;
begin
passTest(out, 63'b0, "Stuff", passed);
#10;
in = 32'hf84093ea;
#10;
passTest(out, 63'b0, "Stuff", passed);
end
end
endmodule
You seem to be treating x as a "don't-care" value in your comparisons, but it is not. x is a specific value which represents "unknown". Since you drive your input signals to all known values (0 or 1), all your == comparisons resolve to x, and your output has x in it. You should only compare bits you are interested in. For example, change:
(ImmIns[31:21] == 11'bxxxx1000xx0) ? {{55{extBit}}, ImmIns[20:12]}:
to:
( (ImmIns[27:24] == 4'b1000) && (ImmIns[21] == 1'b0) ) ? {{55{extBit}}, ImmIns[20:12]}:
You need to make similar changes to all your comparisons.
Also, you drive BusImm with 2 continuous assignments. Get rid of this line:
assign BusImm = 64'b0;
These changes get the x out of your output.
Also consider using casez. Refer to IEEE Std 1800-2017, section 12.5.1 Case statement with do-not-cares.

BNF grammar definition for file path wildcard (glob)

I'm searching for some widely extended dialect (like this one https://github.com/vmeurisse/wildmatch + globstar **) described with BFN rules.
In any format or language. OMeta or PEG would be great.
I'm not sure to understand your question since the grammar for file path wildcard can be reduced to a simple regular expression. This grammar is defined by the Unix Shell.
You can find the BNF for Bash here: http://my.safaribooksonline.com/book/operating-systems-and-server-administration/unix/1565923472/syntax/lbs.appd.div.3
In Python programming language, a definition of the glob.glob() function is available in the documentation. This function use the fnmatch.fnmatch() function to perform the pattern matching. The documentation is available here: https://docs.python.org/2/library/fnmatch.html#fnmatch.fnmatch.
The fnmatch.fnmatch function translate a file path wildcard pattern to a classic regular expression, like this:
def translate(pat):
"""Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i+1
if c == '*':
res = res + '.*'
elif c == '?':
res = res + '.'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j+1
if j < n and pat[j] == ']':
j = j+1
while j < n and pat[j] != ']':
j = j+1
if j >= n:
res = res + '\\['
else:
stuff = pat[i:j].replace('\\','\\\\')
i = j+1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
return res + '\Z(?ms)'
That can help you to write de BNF grammar...
EDIT
Here is a very simple grammar:
wildcard : expr
| expr wildcard
expr : WORD
| ASTERIX
| QUESTION
| neg_bracket_expr
| pos_bracket_expr
pos_bracket_expr : LBRACKET WORD RBRACKET
neg_bracket_expr : LBRACKET EXCLAMATION WORD RBRACKET
A list of popular grammars parsed by the famous ANTLR tool is available here: http://www.antlr3.org/grammar/list.html.

Return a value from a function called in while loop

The point is to guess a random number choosen from an interval of integers and do it within a fixed numbers of attempts.
The main function asks the upper limit of the interval and the number of guesses the user can give. The core function then should return the guessed value so when the number is right the function should terminate immediately.
I put some print statement while debugging and I understood that the y value is not returned to the while statement from the core function.
# -*- coding: utf-8 -*-
def main():
from random import choice
p = input("choose upper limit: ")
t = input("how many attempts: ")
pool = range(p+1)
x = choice(pool)
i = 1
while ((x != y) and (i < t)):
core(x,y)
i += 1
def core(x,y):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
You want to assign the return value of core back to the local y variable, it's not passed by reference:
y = core(x)
You'll also need to set y before you go into the loop. Local variables in functions are not available in other functions.
As a result, you don't need to pass y to core(x) at all:
def core(x):
y = input("choose a number: ")
if y == x:
print("You gussed the right number!")
return y
elif y > x:
print("The number is lower, try again")
return y
else:
print("The number is higher, try again")
return y
and the loop becomes:
y = None
while (x != y) and (i < t):
y = core(x)
i += 1
It doesn't much matter what you set y to in the main() function to start with, as long as it'll never be equal to x before the user has made a guess.
y = -1
while ((x != y) and (i < t)):
y = core(x,y)
i += 1
You "initialize" y before the loop. Inside the loop you set y equal to the result of core() function.

How can you emulate recursion with a stack?

I've heard that any recursive algorithm can always be expressed by using a stack. Recently, I've been working on programs in an environment with a prohibitively small available call stack size.
I need to do some deep recursion, so I was wondering how you could rework any recursive algorithm to use an explicit stack.
For example, let's suppose I have a recursive function like this
function f(n, i) {
if n <= i return n
if n % i = 0 return f(n / i, i)
return f(n, i + 1)
}
how could I write it with a stack instead? Is there a simple process I can follow to convert any recursive function into a stack-based one?
If you understand how a function call affects the process stack, you can understand how to do it yourself.
When you call a function, some data are written on the stack including the arguments. The function reads these arguments, does whatever with them and places the result on the stack. You can do the exact same thing. Your example in particular doesn't need a stack so if I convert that to one that uses stack it may look a bit silly, so I'm going to give you the fibonacci example:
fib(n)
if n < 2 return n
return fib(n-1) + fib(n-2)
function fib(n, i)
stack.empty()
stack.push(<is_arg, n>)
while (!stack.size() > 2 || stack.top().is_arg)
<isarg, argn> = stack.pop()
if (isarg)
if (argn < 2)
stack.push(<is_result, argn>)
else
stack.push(<is_arg, argn-1>)
stack.push(<is_arg, argn-2>)
else
<isarg_prev, argn_prev> = stack.pop()
if (isarg_prev)
stack.push(<is_result, argn>)
stack.push(<is_arg, argn_prev>)
else
stack.push(<is_result, argn+argn_prev>)
return stack.top().argn
Explanation: every time you take an item from the stack, you need to check whether it needs to be expanded or not. If so, push appropriate arguments on the stack, if not, let it merge with previous results. In the case of fibonacci, once fib(n-2) is computed (and is available at top of stack), n-1 is retrieved (one after top of stack), result of fib(n-2) is pushed under it, and then fib(n-1) is expanded and computed. If the top two elements of the stack were both results, of course, you just add them and push to stack.
If you'd like to see how your own function would look like, here it is:
function f(n, i)
stack.empty()
stack.push(n)
stack.push(i)
while (!stack.is_empty())
argi = stack.pop()
argn = stack.pop()
if argn <= argi
result = argn
else if n % i = 0
stack.push(n / i)
stack.push(i)
else
stack.push(n)
stack.push(i + 1)
return result
You can convert your code to use a stack like follows:
stack.push(n)
stack.push(i)
while(stack.notEmpty)
i = stack.pop()
n = stack.pop()
if (n <= i) {
return n
} else if (n % i = 0) {
stack.push(n / i)
stack.push(i)
} else {
stack.push(n)
stack.push(i+1)
}
}
Note: I didn't test this, so it may contain errors, but it gives you the idea.
Your particular example is tail-recursive, so with a properly optimising compiler, it should not consume any stack depth at all, as it is equivalent to a simple loop. To be clear: this example does not require a stack at all.
Both your example and the fibonacci function can be rewritten iteratively without using stack.
Here's an example where the stack is required, Ackermann function:
def ack(m, n):
assert m >= 0 and n >= 0
if m == 0: return n + 1
if n == 0: return ack(m - 1, 1)
return ack(m - 1, ack(m, n - 1))
Eliminating recursion:
def ack_iter(m, n):
stack = []
push = stack.append
pop = stack.pop
RETURN_VALUE, CALL_FUNCTION, NESTED = -1, -2, -3
push(m) # push function arguments
push(n)
push(CALL_FUNCTION) # push address
while stack: # not empty
address = pop()
if address is CALL_FUNCTION:
n = pop() # pop function arguments
m = pop()
if m == 0: # return n + 1
push(n+1) # push returned value
push(RETURN_VALUE)
elif n == 0: # return ack(m - 1, 1)
push(m-1)
push(1)
push(CALL_FUNCTION)
else: # begin: return ack(m - 1, ack(m, n - 1))
push(m-1) # save local value
push(NESTED) # save address to return
push(m)
push(n-1)
push(CALL_FUNCTION)
elif address is NESTED: # end: return ack(m - 1, ack(m, n - 1))
# old (m - 1) is already on the stack
push(value) # use returned value from the most recent call
push(CALL_FUNCTION)
elif address is RETURN_VALUE:
value = pop() # pop returned value
else:
assert 0, (address, stack)
return value
Note it is not necessary here to put CALL_FUNCTION, RETURN_VALUE labels and value on the stack.
Example
print(ack(2, 4)) # -> 11
print(ack_iter(2, 4))
assert all(ack(m, n) == ack_iter(m, n) for m in range(4) for n in range(6))
print(ack_iter(3, 4)) # -> 125