Issue with map function - python

Below is the hacker rank code and x is not being mapped to instance args.Can someone please provide me with a reason?https://www.hackerrank.com/challenges/python-lists/problem
if __name__ == '__main__':
N = int(input())
l=[]
for _ in range(N):
line = input().split()
cmd = line[0]
args= line[1:] # <=> here we have 0, 1 or 2 parameters, right?
"""if cmd!= "print":
cmd += "(" + ",".join(args)+")"""
#x = ",".join(map(str,args))
if len(args) == 2:
x, y = map(int, args)
if cmd == "insert":
l.insert(x, y)
elif len(args) == 1:
x = map(int,args)
if cmd == "remove":
l.remove(x)
elif cmd == "append":
l.append(x)
elif cmd == "sort":
l.sorted()
elif cmd == "pop":
l.pop()
elif cmd =="reverse":
l.reverse()
elif cmd == 'print':
print(l)

Your issue is with this line:
x = map(int,args)
This does not work like the line you have in a different branch of your code:
x, y = map(int, args)
The reason is that the first one binds the name x to the map call. It doesn't unpack the map object to get the single value it will yield. For that you'd need:
x, = map(int, args) # note the comma!
But if you know that you have only a single value in args, there's really no need to call map on it at all. Just use x = int(args[0]) instead.

You have couple of issues in your code.
By x = map(int,args) (line 16), x becomes a map object. To obtain integer from this map, first convert it into a list and then use indexing. x = list(map(int,args))[0] will solve your issue. Or you could simply use x = int(args[0]).
list has no sorted function, change l.sorted() to l.sort().

Related

How to solve pylint (too-many-return-statements) elegantly?

The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful?
def func():
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0
You could try something like this:
def foo(x):
nums = ['one','two','three','four','five','six','seven']
return 'This is ' + nums[x-1]
to solve your example. And you could solve your scenario like this:
def func():
functions = [do_something1,do_something2,...]
for function in functions:
ret = function()
if ret != 0:
return ret
return 0
Check out this example.
It converted:
def func(x):
if x == 1:
return "hi1"
if x == 2:
return "hi2"
if x == 3:
return "hi3"
if x == 4:
return "hi4"
if x == 5:
return "hi5"
if x == 6:
return "hi6"
if x == 7:
return "hi7"
to:
d = {1: "hi1", 2: "hi2", 3: "hi3", 4: "hi4", 5: "hi5", 6: "hi6", 7: "hi7"}
def func(x):
return d[x]
Just to silence it another option is:
def func(x):
if x == something1:
res = "something1"
elif x == something2:
res = "something2"
elif x == something3:
res = "something3"
elif x == something4:
res = "something4"
elif x == something5:
res = "something5"
elif x == something6:
res = "something6"
elif x == something7:
res = "something7"
else:
res = "default"
return res
You can also silence it in settings.json file if you think it's too strict rule which I think it is:
"python.linting.pylintArgs": [
"--disable=R0911"
],
def func():
res = default_res
if foo:
res = res_foo
elif bar:
res = res_bar
return res
I recommend doing it this way
Using some form of lookup is the way to handle this. A dictionary is a good general purpose idea. A list is useful when the lookup 'key' is an integer.
HOWEVER
When using a lookup technique you have to consider that your 'key' may not be available. If your dictionary (for example) has 7 integer keys (1->7 inclusive) and your function is passed a value of 8, what are you going to do? You could allow the exception and deal with that separately or you need to avoid an exception and return some default value, perhaps implicitly.
In general you can use the proposed solution by pylint documentation:
https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/too-many-return-statements.html
But IMHO in some case it's impossible to use.
I don't kwonw your specific case, but you can disable pylint in a specific line of code using a comment like this.
def func(): #pylint: disable=R0911
# do something1
ret1 = do_something1()
if ret1 != 0:
return ret1
# do something2
ret2 = do_something2()
if ret2 != 0:
return ret2
# ......
return 0

SyntaxError: cannot assign to list comprehension?

My code:
def function():
resources, bufferViews, accessors = parse_gltf(fname)
display(resources)
display(bufferViews)
display(accessors)
ds = []
idx_vertex = -1
idx_normals = -1
idx_textures = -1
idx_meshes = -1
for j in range(len(accessors)):
accessor = accessors[j]
if accessor.min:
idx_vertex = j
d = parse_accessor(accessor, resources, bufferViews)
ds.append(d)
if d.shape[1] == 3:
idx_normals = j
if d.shape[1] == 2:
idx_textures = j
if d.shape[1] == 1:
idx_meshes = j
return idx_vertex, idx_normals, idx_textures, idx_meshes, [e.shape for e in ds]
if __name__ == "main":
idx_vertex, idx_normals, idx_textures, idx_meshes, [e.shape for e in ds] = function()
display(ds[idx_vertex])
Basically, I want to be able to return the values idx_vertex, idx_normals, idx_textures, idx_meshes and be able to assign them in the ds array. However, I get "SyntaxError: cannot assign to list comprehension" when I try to achieve this. Does anyone know what I am doing wrong?
You need to store the list comprehension in a variable in your start routine:
if __name__ == "__main__":
idx_vertex, idx_normals, idx_textures, idx_meshes, shape_list = function()
display(ds[idx_vertex])
Your function function is already returning the list [e.shape for e in ds]
LE: Edited according to MattDMO's comment

Dispatch function in python, how does the data is saved?

I'm now learning about software engineering and as a part of my studies i had to implement a dispatch function for a mutable pair type.
Here is my implementation:
def make_mutable_pair(*args):
x = None
y = None
numargs = len(args)
if (numargs == 1):
x = args[0]
elif (numargs == 2):
x = args[0]
y = args[1]
elif (numargs >= 3):
raise Exception("Too many arguements!")
else:
pass
def dispatch(msg, i=None, v=None):
if(msg == 'get'):
return get_item(i)
elif(msg == 'set'):
return set_item(i,v)
def get_item(i):
if(i == 0):
return x
elif(i == 1):
return y
else:
raise Exception("Wrong index!")
def set_item(i,v):
nonlocal x,y
if(i == 0):
x = v
elif(i == 1):
y = v
else:
raise Exception("Wrong index!")
return dispatch
I understand everything pretty well but there is something that is against everything i know in software and coding, the 'make_mutable_pair' is basically a function, here is some test i did:
test = make_mutable_pair(5,10)
print('({},{})'.format(test('get',0),test('get',1)))
test('set',0,3)
test('set',1,6)
print('({},{})'.format(test('get',0),test('get',1)))
As expected, the output will be:
(5,10)
(3,6)
What i don't understand is how the x and y are saved...
I mean from what i know, when i'm done with a function all the data in the stack memory will be deleted, and in the next call to that function i'm starting fresh.
In this case i called the function with some data for x and y, and later i changed it, and called it again, and it's still saved...
I will love to hear some explanation about it... Thanks!

Python function returning many arguments

I know, it's a noob question..
I have these variables:
pgwdth = 30;
mrgn = 0;
fmt = True
And this function:
def Param(x,pgwdth,mrgn,fmt):
parametros = x.split(" ")
if parametros[0][1] == "p":
numerozinho = int(parametros[1])
print "Changing pgwdth"
pgwdth += numerozinho
print pgwdth
elif parametros[0][1] == "m":
numerozinho = int(parametros[1])
print "Changing mrgn"
mrgn += numerozinho
print mrgn
elif parametros[0][1] == "f":
numerozinho = parametros[1]
print "On/Off"
if numerozinho == "on\n":
fmt = True
elif numerozinho == "off\n":
fmt = False
else:
"Error"
print fmt
else:
print "Error"
I just want it to return the variables that it used as arguments after changing it.
return x,pgwdth,mrgn,fmt
Simple as that.
And where you call it:
val1,val2,val3,val = Param(x,pgwdth,mrgn,fmt)
A function returns exactly one result. The trick is to make that result a tuple containing the multiple values.
return (x, pgwdth, mrgn, fmt)
In Python syntax the braces around the tuple are optional so you'll more often see
return x, pgwdth, mrgn, fmt
Which looks like returning multiple values, but now it's clear there is really just one return value

In my code it says x is not defined?

def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
it says that x==1:
is not defined. How might I go about fixing that?
Tanks
Probably since you didn't use indentation correctly.
Indent every line except the first with 4 spaces.
However I do not have a compiler here so I cannot check it.
Btw but offtopic, your code can be rewritten as:
def randomcheetahs():
return 'present' if random.randint(1,2) == 1 else 'absent'
I guess maybe your code is indented like this
def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
You need to indent it like this instead. Be careful not to mix tabs and spaces. It's a good idea to just use spaces
def randomcheetahs():
x = random.randint(1,2)
if x == 1:
r = 'present'
elif x == 2:
r = 'absent'
return r
cheetahs = randomcheetahs()
As wim says, you can also just do this:
def randomcheetahs():
return random.choice(['present', 'absent'])
but it is important for beginners to understand how the indenting works in Python

Categories

Resources