I'm translating a code from MATLAB to Python and I've encountered "nargin" and "nargout" which are MATLAB defined variables that check the input arguments of a function "nargin" and the output arguments "nargout". Is there an equivalent in Python?
I've tried this but it's giving me the wrong number of input arguments.
import sys
def my_function(arg1, *arg2):
n_args = len(sys.argv) -1
print("Number of arguments:", n_args)
Related
I wanted to learn how to use python modules in matlab. Therefore I wrote a trivial implementation of substring:
def substring(string, end, start=0):
if int(start) != 0:
return string[int(start):int(end)]
else:
return string[:int(end)]
I put it into a file named substring.py which is saved in the matlab working directory.
I added matlab work folder to python search path (followed the instructions here https://www.mathworks.com/help/matlab/matlab_external/call-user-defined-custom-module.html).
Then I tried to call my function in matlab:
x_label = py.substring.substring(fastaContent.id, int8(40));
I ran the matlab code and got this in console:
Error using substring (line 3)
Python Error: TypeError: slice indices must be integers or None or have an __index__ method
fastaContent.id is a valid string. I also wrapped 40 with int8() but it didn't help.
I would appreciate any help.
#Edit: I think it is worth mentioning that the function works fine called with python.
I'm very new to coding (started 2 days ago) and for practice a friend gave me the task of writing a program that provides either the nth Fibonacci number or the sequence up to the nth point. I successfully completed that task using input() and directly asking the user for an n, now he extended the task and asked me to try getting the same results using sys.argv
After extensive use of google I figured out how to print all the given arguments and count them, but I cannot figure out any way of using those arguments in a function. Unfortunately I also can't seem to find the right keywords for google, leaving me a little stuck in no mans land.
Here's my most recent attempt:
import sys
from math import sqrt
print('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Fibonacci = sys.argv[0]
value = sys.argv[1]
sequence = sys.argv[2]
def fib(value): int(1/sqrt(5)*(((1+sqrt(5))/2)**value-(((1-sqrt(5))/2)**value)))
print("The {}. value is".format(value), fib(value))
input("Close")
(Small detail, albeit unimportant: I translated the strings from German to English, which is also why it says "{}. value" rather than "{}st/nd/rd/th", the differentiation between those cases is a problem for a later date.)
Now I expect to be miles off target here, but using some of the expressions that worked for my input() based code is pretty much the last idea I have right now. Can anyone give me a pointer on how I can proceed here? Even a hint on what I should google would help, but as of now I'm completely out of ideas.
EDIT: I don't know if this is what you're supposed to do, but I've solved my problem and I thought I might as well post my code in case someone else stumbles upon this thread with a similar question. Here's my solution.
import sys
from math import sqrt
Fibonacci = sys.argv[0]
Entscheidung = (sys.argv[1])
n = int(sys.argv[2])
sequence = []
if Entscheidung == "Stelle":
def fib(n): return int(1/sqrt(5)*(((1+sqrt(5))/2)**n-((1-sqrt(5))/2)**n))
print("Die {}. Stelle beträgt:{}".format(n, fib(n)))
elif Entscheidung == "Folge":
def fib(n): return int(1/sqrt(5)*(((1+sqrt(5))/2)**n-((1-sqrt(5))/2)**n))
for i in range(n):
sequence.append(fib(i + 1))
print('[%s]' % ', '.join(map(str, sequence)))
input("Schließen")
Note that I'm still an absolute beginner and this solution might be inefficient, badly written, confusingly formatted, I wouldn't know. All I can guarantee is that it does the job.
Yup, n = int(sys.argv[2]) was the charm.
Now that you're an expert at cracking sys.argv, you might want to $ pip install click and let that package do some of the parsing for you: https://click.palletsprojects.com/en/7.x/
Conditionally executing def is an option, I suppose, but a bit odd.
Pasting the same definition into both if branches is not helpful.
Just def it once, up top.
Here's a refactoring of your code with the following changes:
Don't define the same function twice. Instead, define two separate functions, and decide which one to call depending on the desired semantics.
Don't capitalize variables. Capitalized names are conventionally reserved for class names in Python.
Remove the final input. Surely your friend wanted you to make a program which can be properly reused; requiring user interaction ruins that.
Don't use sys.argv[0] for anything. If it's not used, there's no need to capture it (and if you should need it later, it's still there).
Wrap the entry point in if __name__... so that this piece of code can be imported into another program without side effects.
from math import sqrt
def fib_nth(n):
return int(1/sqrt(5)*(((1+sqrt(5))/2)**n-((1-sqrt(5))/2)**n))
def fib_seq(n):
sequence = []
for i in range(n):
sequence.append(fib_nth(i + 1))
return sequence
if __name__ == '__main__':
import sys
entscheidung = sys.argv[1]
n = int(sys.argv[2])
if entscheidung == "Stelle":
print("Die {}. Stelle beträgt:{}".format(n, fib_nth(n)))
elif entscheidung == "Folge":
print('[%s]' % ', '.join(map(str, fib_seq(n))))
I called a Matlab function from Python, the function has 3 outputs. Python gives ValueError: not enough values to unpack (expected 3, got 2). Here's the Matlab function testCalledByPython:
function [otpt1, otpt2, otpt3] = testCalledByPython(inpt)
otpt1 = rand(inpt, inpt);
otpt2 = magic(inpt);
otpt3 = zeros(inpt, inpt);
This is the Python script to call the above function:
#!/usr/bin/env python3
import matlab.engine
eng = matlab.engine.start_matlab()
otpt1, otpt2, otpt3 = eng.testCalledByPython(2)
If I replace the last line by otpt1, otpt2 = eng.testCalledByPython(2), it runs, but the outputs are:
otpt1, otpt2
Out[5]:
(matlab.double([0.8147236863931789,0.12698681629350606]),
matlab.double([0.9057919370756192,0.9133758561390194]))
Obviously these are wrong outputs. How can I solve it?
I found the solution myself. It's actually explained in Matlab Documentation:
https://uk.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-python.html
So knowing there are 3 outputs, the way to do it is changing last line of Python script to:
otpt1, otpt2, otpt3 = eng.testCalledByPython(2, nargout = 3)
I also had the similar problem, however I was using the runtime method without API engine.
So knowing that I required/expected x outputs from the function, I added the argument of nargout = x inside the function that I wanted to use or get output from.
Problem
Calculate and print the factorial of a given positive integer. The integer can be as large as 100.
Here's a link to the problem
My effort
I have tried solutions on other compilers, they are working fine on other compilers, but on hackerrank its not working saying compile time error
# Enter your code here. Read input from STDIN. Print output to STDOUT
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
no = int(raw_input())
print fac(no)
Any help would be appreciated
This solution works just fine for Python 2 - I ran your code on Hackerrank and it passed all the test cases.
So, the compilation error is shown if the code is compiled with Python 3.
no = int(raw_input())
NameError: name 'raw_input' is not defined
That's true because raw_input must be replaced with input() in Python 3.
If the code with the correction is executed afterwards then there's another issue:
print fac(no)
^
SyntaxError: invalid syntax
Again, just add parentheses around fac(no) and then the code compiles and passes all the tests:
So, the full code is below:
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
no = int(input())
print (fac(no))
Here are the script I write.
Two question.
First, we need to print the blast result forming XML hit_id, hit_len and hit_def. First two are easy. But hit.def is the same as def. How to avoid it?
Second, we need to run the program on linux. This program should accept two sequence, one is protein and one is nucleic acid by using a optional argument. But I just cannot achieve this function.
It should work when
$ python my_program.py protein.fa tem.txt prot
last one is the argument option. I don't why the python just doesn't accept it as I write
f=sys.argv[3]
f1=str(sys.argv[3])
if f1 is 'prot':
function(filename,protflag=True)
Python always choose 'else'
# IMPORT
import sys
import subprocess
################################################################################
# FUNCTIONS
#execute BLAST, vailable type are protein and nuclien
def run_blast(filename,protflag=True):
"""execute BLAST, vailable type are prot or na"""
if protflag:
subprocess.call(['blastp','-query','filename','-db','nr','-outfmt','5','-out','prot.xml'])
else :
subprocess.call(['blastn','-query','filename','-db','nt','-outfmt','5','-out','na.xml'])
def read_XML(filename):
"""return hit_id length hit_def"""
from Bio.Blast import NCBIXML
name=str(filename)
record=NCBIXML.read(open(name))
for i in range(0,len(record.alignments)):
hit=record.alignments[i]
print 'hit_id'+hit.id+'\n'+'length'+hit.len+'\n'+'hit_def'+hit.def+'\n'#here is the problem .def
################################################################################
# MAIN
# write a function for the "main method"
def main(filename=sys.argv[1],protflag=True):
"""excuate BLAST with file then return the hit_id, length and hit_def"""
f=sys.argv[3]
f1=str(f)
if f is 'prot':
run_blast(filename,True)
read_XML("prot.xml")
elif f is 'na':
run_blast(filename,False)
read_XML("prot.xml")
else:
print 'only prot and na available'
if __name__ == '__main__':
# defaults to reading the system, see above :)
main()
The "else" clause is always chosen because you are using "is" instead of "==" to check the value of sys.argv[3].
From Is there a difference between `==` and `is` in Python?:
is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.
You should use
if f1 == 'prot':