Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have tried the following function:
def item_order(order):
salads = order.count("salad")
hamburgers = order.count("hamburger")
waters = order.count("water")
return "salad:{} hamburger:{} water:{}".format(salads, hamburgers, waters)
taken from ( https://stackoverflow.com/questions/34906570/counting-and-grouping-with-python ),
with these two orders:
1st order = "salad water hamburger salad hamburger"
- then the function should returns "salad:2 hamburger:2 water:1"
2nd order = "hamburger water hamburger"
then the function should returns "salad:0 hamburger:2 water:1",
in http://www.pythontutor.com/visualize.html#mode=edit
But it seems it doesn't work.
Maintaining this structure, what am I doing wrong?
Many thanks for any help!!
You have a function definition, and then in your script you define the order:
def item_order(order):
# your function here
order = 'salad water hamburger salad hamburger'
When you call the function, you need to either assign the result to a variable or otherwise display the return from the function. So:
print item_order(order)
or:
x = item_order(order)
print x
Your code works as intended.
Variable order needs to be assigned some value and then function item_order can be called with variable order as the argument.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Assume two functions, where you do it by default value of function,
def foo_def(name = "Default Name" , age = 10) :
print (f"my name is {name} and I am {age}.")
and just take kwargs, but maybe check it later
def foo_kwargs(**kwargs) :
name = kwargs.get('name') if kwargs.get('name') != None else "Default Name"
age = kwargs.get('age') if kwargs.get('age') != None else 10
print (f"my name is {name} and I am {age}.")
Now in my "opinion" for sure the first code has higher readability, and for usage of typing it's probably much favored way of coding, although this probably falls in "opinion" category.
Now my question is :
Are there actual behavior difference? for example, if I'm basically 'for sure' that this code will not be maintained by anyone else and will be kept short, is it fine to code like foo_kwargs? Is there any risk of unexpected behavior by using **kwargs instead of having it has an actual argument?
Is **kwarg basically only meant for exceptional case such as decorators?
What's the main purpose of having **kwargs in normal cases? is there any practical difference in having actual dict object passed as option argument vs using **kwargs?
Some of this question may look quite opinion based, but I'm curious if it's actually "opinion" based (please let me know, if so), or there's some hidden risk / behavior difference so one method is probably strictly better/recommended than the other.
There is a very big behavioral difference, and that's how they handle positional and extra arguments. Consider:
def f_normal(a, b):
return (a, b)
def f_kwargs(**kwargs):
return (kwargs["a"], kwargs["b"])
f_normal(1, 2) # can use positional arguments as well
f_normal(name = 1, age = 2, extra = 3) # unexpected keyword argument
f_kwargs(1, 2) # this doesn't work
f_kwargs(name = 1, age = 2, extra = 3) # extra parameter ignored
In addition, having the accepted parameter names in the parameter list directly gives more power to language analysis features, such as VSCode displaying function signatures when hovering over a function call. The main purpose of **kwargs is for when you want to accept any keyword argument, and you don't know the names beforehand, such as the dict constructor:
dict(a=1, b=2) # {"a": 1, "b": 2}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
if(input == "Karma Score"):
print("Your Karma score is {}.format(charKarma) + ".")
This may be an odd question, and I am new to python so I'm stumped.
I set myself a goal of finishing a text-based adventure game that features a 'Karma" system. It's basically a watered-down version of the Fallout series' Karma system.
I need help figuring out how to callback to a variable value when requested from the console.
A simplified version of my spaghetti code is:
if(Input == "Print Variable")
print("variable")
Thanks a bunch for your time.
Notwithstanding that it might be bad design as #juanpa.arrivillaga noted in the comments, it can be done quite easily in Python.
Python conceptually holds variables and their values in dictionaries, which you can retrieve using the built-in functions globals() or locals(). In your case globals() is probably what you want. So, you could print out the value of a variable karma like this:
print( globals()["karma"] )
Or, if I understand your intentions correctly, here is how it might look in context:
user_input = input("command$ ")
words = user_input.split()
if words[0] == "print":
var_name = words[1]
value = globals()[var_name]
print(value)
Just to be complete here: if the variable is defined in another module, either use getattr(module, var_name) or module.__dict__[var_name]. So, the following works, too:
import math
print( getattr(math, "pi") )
pritn( math.__dict__["pi"] )
The __dict__ here is basically what globals() returns for the current module.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
class Pract:
p1 = Pract() #creating an instance of Pract
p1.age=45 #creating a field-variable
print(p1.age)
I checked this Youtube, in the video its shows as working, but I couldn't run it.
# First declare a class (empty, in this case)
class Pract:
pass
# Then instantiate it
p1 = Pract()
# Then set the attribute
p1.age = 45
# Then print the attribute
print(p1.age)
You cannot instantiate a class before you finish declaring it. Everything you put inside class is part of the class definition. You have to de-indent your code in order to mark the end of the class definition.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was recently asked this in an interview for junior dev position. I was asked to create a calculator program that can add,subtract, multiply and divide without using the built in +,-,*,/ operators. Essentially to build it from the ground up.
I had no idea how to solve this. Does anyone have any guidance on how to implement at least one of the operations? I can figure out the rest from there but really need some guidance.
I code in both python and ruby.
This is an example of addition.
class Integer
def add(int) # int is 5 in the demo
res = self # 7 in the demo
int.times{res = res.succ} # succ just adds 1
return res
end
end
# demo
p 7.add(5) # => 12
Apart from succ, the Integer class has a pred method, which subtracts 1. Really useful for building a subtract method. Multiplying is just adding multiple times, and integer division is just subtracting multiple times.
Study how Ruby's "operators" are implemented; They're methods and send can be used as an alternate way of calling them.
From the documentation:
Invokes the method identified by symbol, passing it any arguments specified....
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
From that:
1.send(:+, 1) # => 2
Learning more about that is left as an exercise for the reader.
If you really want to dive in, you could create base methods like:
class Fixnum
def add(value)
val = self
value.times do
val = val.succ
end
val
end
end
1.add(1) # => 2
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am trying to improve my program so that it conforms to good programming
practices. So I am looking for suggestions on whether the way I have programmed
something is a good way of doing it.
I have a module called dbfunctions.py in which I have defined:
dbparams = {
'dbname': 'qualitysimparams',
'tablename': 'qualityparams',
'tablecols': ('numpeople', 'numreviews', 'prophunters',
'utility_funcform', 'goods'
)
and a function:
def obtainid_ifrecord(dbname, tablename, tablecols, values):
'''Checks if there already exists a record with given <values>.
If so, returns the id of that record, otherwise returns zero.'''
con, c = connecttodb()
q1 = "use {0}".format(dbname)
c.execute(q1)
q2p1 = "select id from {0} ".format(tablename)
q2p2 = "where " + " = %s and ".join(tablecols) + " = %s"
q2 = q2p1 + q2p2
c.execute(q2, values)
res = c.fetchall()
c.close()
con.close()
if res:
return res[-1][0]
else:
return 0
There are other functions and variables in addition to the above two, but
they are not relevant for this post.
In another file I have a function:
def checkif_paramcomboexists(numpeople, numreviews, prophunters,
utility_funcform, goods):
'''Check in the database if the simulation has been run with the
specified parameters. If so return the id of that run.
'''
goodsjson = sjson.dumps(goods)
# paramvalues: in same order as listed in dbf.dbparams['tablecols']
paramvalues = (numpeople, numreviews, prophunters,
utility_funcform, goodsjson)
id = dbf.obtainid_ifrecord(dbf.dbparams['dbname'],
dbf.dbparams['tablename'],
dbf.dbparams['tablecols'],
paramvalues)
return id
It seems to me that the fact that hardcoding the variable names in the
paramvalues variable in function checkif_paramcomboexists is not a good practice.
If later I change the order of variables in dbfunctions.dbparams['tablecols'] for any
reason, checkif_paramcomboexists function will fail (and can fail silently depending
on the data types). One way to get around this is to define:
paramvalues = [eval(x) for x in dbf.dbparams['tablecols']]
But I have heard that generally it is a bad practice to use eval (although I do not know
why and when it is okay to use it). My questions are:
(i) Is it okay the way I have coded this in regards to the concern I have? I think the answer
is 'No', but just want to check with the experts here.
(ii) Is use of eval as I have indicated an acceptable solution?
(iii) If answer to (ii) is 'no', what is the alternative?
Thank you for reading through this.
You're right about the hardcoding not being great, and definitely stay away from eval. If you don't want to use *args or **kwargs (which are really better options, by the way), you can use the inspect module to do what you're trying to do.
import inspect, collections
def checkif_paramcomboexists(numpeople, numreviews, prophunters,
utility_funcform, goods):
...
temp = inspect.getargvalues(inspect.currentframe())
args = temp[0]
valuedict = temp[-1]
ordered_args_dict = collections.OrderedDict(sorted(valuedict.items(), key=lambda x: args.index(x[0])))
paramvalues = ordered_args_dict.values()
...
Basically, what's going on here is that inspect.getargvalues(inspect.currentframe()) gets you an object where the first item is a properly ordered list of the argument names and the last item is a dictionary of the argument names and values. We then create an ordered dictionary by grabbing the argument name/value mapping from the dictionary, and ordering it based on the list order.
What you end up with is an OrderedDict that has all of the arguments with their values, but also has them in the right order. That way, you can still choose to refer to them by name (e.g., ordered_args_dict['numpeople']), but if you can still get all the values in order as you wanted with ordered_args_dict.values(), which will give you the output you're looking for for paramvalues: a properly ordered list of the arguments, no matter what the name is.
This situation really calls for an object. You are duplicating what is essentially instance information about a specific database table in 2 places, so it would make sense to make both these functions in to methods of some sort of database table interface object that has a tablecols attribute, then use self.tablecols in both methods.