add_digits2(1)(3)(5)(6)(0) should add up all the numbers and stop when it reaches 0.
The output should be 15
The below code works but uses a global variable.
total = 0
def add_digits2(num):
global total
if num == 0:
print(total)
else:
total += num
return add_digits2
The result is correct but needs to do the same thing without using the global variable.
One thing you could do is use partial:
from functools import partial
def add_digits2(num, total=0):
if num == 0:
print(total)
return
else:
total += num
return partial(add_digits2, total=total)
add_digits2(2)(4)(0)
You can just pass in *args as a parameter and return the sum
def add_digits2(*args):
return sum(args)
add_digits2(1, 3, 5 ,6)
You could also use a class, using the __call__ method to obtain this behavior:
class Add_digits:
def __init__(self):
self.total = 0
def __call__(self, val):
if val != 0:
self.total += val
return self
else:
print(self.total)
self.total = 0
add_digits = Add_digits()
add_digits(4)(4)(0)
# 8
add_digits(4)(6)(0)
# 10
though I still don't get why you would want to do this...
Really hard to say what they are after when asking questions like that but the total could be stored in a function attribute. Something like this
>>> def f():
... f.a = 3
>>> f()
>>> f.a
3
Related
I didn't understand why. And It will raise an error 'int' object has no attribute 'v', but I want to access the self.v. When I print only self it will print some numbers. I couldn't understand what was going on. Here is my code.
class Candidate:
def __init__(self,val,pscore,nscore):
self.v = val
self.p = pscore
self.n = nscore
def __str__(self):
return f"{self.v} ({self.p},{self.n})"
def check_plus_pos(self, guessval):
count = 0
b = self.v
a = str(b)
guessval = str(guessval)
for i in range(0,len(a)):
if a[i] == guessval[i]:
count += 1
return count
def check_neg_pos(self, guessval):
count = 0
b = self.v
a = str(b)
guessval = str(guessval)
for i in range(0,len(a)):
for j in range(0,len(guessval)):
if a[i] == guessval[j] and a[i] != guessval[i]:
count += 1
return count
def consistent(self, guess):
if Candidate.check_plus_pos(self,guess.v) == guess.p and Candidate.check_neg_pos(self,guess.v) == guess.n:
return True
else:
return False
The problem occurs at b == self.v I wanted to assign the self.v value to a variable.
To be honest it's pretty hard to understand what that code/class is supposed to do, imho it needs some serious refactoring.
My guess is you should:
instantiate your class somewhere
use the method as an instance method, so invoke it with self and not the class name
do NOT pass self explicitly at all
do NOT use abbreviations which are not commonly known
do NOT use single letter variables a means literally nothing
use docstrings for non-trivial functions (or as a rule of thumb to most of functions/methods)
use type hints, which will help you catch this kind of errors automatically (if you configure your IDE that is)
get rid of the assignment to b at all, it's not reused and doesn't seem do anything. This will do the same a = str(self.v)
... # all the class related code above
def check_neg_pos(self, guessval):
count = 0
a = str(self.v)
guessval = str(guessval)
for i in range(0,len(a)):
for j in range(0,len(guessval)):
if a[i] == guessval[j] and a[i] != guessval[i]:
count += 1
return count
def is_consistent(self, guess: Candidate)->bool:
return bool(self.check_plus_pos(guess.v) == guess.p and self.check_neg_pos(guess.v) == guess.n)
# Example usage
candidate_1 = Candidate(1,2,3)
candidate_2 = Candidate(4,5,6)
candidates_consistent = candidate_1.is_consistent(guess=candidate_2)
print(candidates_consistent)
I have a helping function:
def incr(x):
return x+1
I want to create a function named "repeated" that use "incr" function n times on a certain parameter
In the end I want to use the "repeated" function in this matter only :
repeated (incr, 4)(2)
That for example will output 6.
So far I tried to do this:
def repeated(f, n):
func, x = f
for i in range(n):
func(x)
But it gave me an error saying I can't unpack a non Tuple function.
It doesn't seem like I don't have access in the function to the "(2)"
I do not recommend to use such a syntax construct, for such a task:
repeated(incr, 4)(2)
Your repeated function must return another function, that will be called by (2).
This should work in your requested manner:
def incr(x):
return x+1
def repeated(f, x):
# function foo will be returned by repeated and called by (2)
def foo(n):
res = x
for i in range(n):
res = f(res)
return res
return foo
print(repeated(incr, 4)(2))
I think you may want to do something like functional programming.
Add args to deal with for different kind of function you want to repeat.
I can't confirm if there is a position argument what kind of results you want, so I didn't deal with it.
code:
import functools
def incr(x):
return x + 1
def incx(x,y = 0):
return x + y + 1
def repeated_inner(func,args,times):
head, *rest = args
for _ in range(times):
head = func(head, *rest)
return args[0]
def repeated(func, *args ):
return functools.partial(repeated_inner, func, args)
print(repeated(incr, 4)(2))
print(repeated(incx, 4)(2))
print(repeated(incx, 4 ,3)(2))
result
6
6
12
the repeatedfunction must return a function
def repeated(func, n):
def repeatedfunc(x):
rsl = x
for i in range(n):
rsl = func(rsl)
return rsl
return repeatedfunc
def incr(x):
return x+1
rslt = repeated(incr, 4)(2)
print(rslt)
output
6
You should write something like this:
def repeated(f, arg_0, n):
arg = arg_0
for i in range(n):
arg = f(arg)
return arg
In a more general situation:
def repeated(f, arg):
def n_f(n):
result = 0
for i in range(n):
result =f(arg)
return result
return n_f
Define a class for a type called CounterType. An object of this type is used to count
things, so it records a count that is a nonnegative whole number.
a. Private data member: count.
b. Include a mutator function that sets the counter to a count given as an argument.
c. Include member functions to increase the count by one and to decrease the count
by one.
d. Include a member function that returns the current count value and one that outputs
the count.
e. Include default constructor that set the count to 0.
f. Include one argument constructor that set count to given argument.
Be sure that no member function allows the value of the counter to become negative.
Embed your class definition in a test program.
An output example would be:
a = CounterType(10)
a.display()
a.increase()
a.display()
a.setCounter(100)
a.display
Will display the following:
Counter: 10
Counter: 11
Counter: 100
I have written the code but I just want to make sure that it is following what the question asked and if there could be an easier way to write this code.
class CounterType:
def __init__(self, counter=0):
self.counter = counter
def increase(self):
self.counter += 1
def decrease(self):
if self.counter == 0:
print("Error, counter cannot be negative")
else:
self.counter -= 1
def setCounter(self, x):
if x < 0:
print("Error, counter cannot be negative")
else:
self.counter = x
def setCount0(self):
self.counter = 0
def display(self):
print("Counter:", self.counter)
def getCounter(self):
return self.counter
This is a homework assignment so it would help if you could just give some tips
You forgot "Be sure that no member function allows the value of the counter to become negative."
The naïve way to do this is to add an if condition in every function. A smarter way would be to add that check the setCounter function and use this function from all other functions.
class CounterType:
def __init__(self, counter=0): # (e, f) counter = 0: default argument value so x = CounterType() works and has a counter of 0
self.counter = 0 # (a)
self.setCounter(counter)
def increase(self): # (c)
self.setCounter(self.counter + 1)
def decrease(self): # (c)
self.setCounter(self.counter - 1)
def setCounter(self, x): # (b)
if x < 0:
print("Error, counter cannot be negative")
else:
self.counter = x
def setCount0(self): # This is not needed
self.counter = 0
def display(self): # (d)
print("Counter:", self.counter)
def getCounter(self): # (d)
return self.counter
I have a class called newInteger, and a variable called num, but I would like num to be a newInteger() instead of an int(). Code below.
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
I want the line num = 10 to act as if it is num = newInteger(10). Thanks to anyone who can help me with this.
You can run a small thread parallel to your main program that replaces all created integers to newInteger:
import threading
import time
class newInteger(int):
def __init__(self, value):
self.value = value
def __str__(self):
return "newInteger " + str(self.value)
def replace_int():
while True:
g = list(globals().items())
for n, v in g:
if type(v) == int:
globals()[n] = newInteger(v)
threading.Thread(target=replace_int, daemon=True).start()
num = 10
time.sleep(1)
print(num)
But this is unpythonic and will be realy hard to debug. You should just use a explicit conversion like #johnashu proposed
I am not sure if this is what you mean but if youassign the class to a variabl. then it will be an instance of that class..
example:
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
if num == 10:
num = newInteger(10)
prints:
hello
Approach 1 (global var):
id_constant = 1000
id_cnt = 1
def give_id():
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
Approach 2 (fuc var instead of global var):
id_cnt = 1
def give_id():
id_constant = 1000
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
Approach 3 (pass in global vars):
id_cnt = 1
id_constant = 1000
def give_id(constant, cnt):
return constant * cnt
global id_cnt
id_cnt +=1
id = give_id(id_constant, id_cnt)
im not sure if there are any general rule of thumb but is is widely accepted for a function to access a global variable inside a function? or if the variable is only used for a function, then should it be part of a function variable instead?
The method often depends a little on the situation.
You seem to need unique ids, why not use a generator:
def create_id_generator():
"""Returns an id generator."""
i = 0
while True:
yield i
i += 1
Used with the next() function:
>>> ID_GENERATOR = create_id_generator() # Global variable
>>> my_id = next(ID_GENERATOR)
>>> my_id2 = next(ID_GENERATOR)
>>> my_id3 = next(ID_GENERATOR)
>>> print(my_id, my_id2, my_id3, next(ID_GENERATOR))
0 1 2 3
If you want the ids to be multiples of 1000, you can pass the constant to the generator via parameters:
def create_id_generator(multiplier=1000):
"""Returns an id generator."""
i = 0
while True:
yield i * multiplier
i += 1
You can even add a starting value if you don't want to start from index 0:
def create_id_generator(multiplier=1000, start_index=0):
"""Returns an id generator."""
while True:
yield start_index * multiplier
start_index += 1
If id_constant is actually constant, I would have done:
ID_CONSTANT = 1000
def give_id(id_count):
return ID_CONSTANT * id_count
id_count = 1
id = give_id(id_count)
But it looks like you also have some state (id_count) that needs to be kept up-to-date with the issuing of id, suggesting a generator function:
def give_id(id_count):
while True:
yield ID_CONSTANT * id_count
id_count += 1
or even a class:
class IdCreator(object):
ID_CONSTANT = 1000
def __init__(self, start_count=1):
self.id_count = start_count
def give_id(self):
new_id = self.ID_CONSTANT * self.id_count
self.id_count += 1
return new_id
You could go further and implement iteration for the class.
Global variable is generally something you should avoid.
If you want to have constants, for let's say, configuration purposes I would take more a module approach like:
conf.py
MYCONST = 1000
app.py
import conf
print conf.MYCONST
Or take an OO approach such as:
class Test(object):
def __init__(self):
self._constant = 1000
def give_id(self, cnt):
return self._constant * cnt
From the Zen of Python (i.e. import this)
Namespaces are one honking great idea -- let's do more of those!
In general, if you don't need to put something in the global namespace, it is better to encapsulate it in the local namespace of the function, so I would consider option 2 to be more "pythonic" unless id_constant is going to be used by multiple functions.
You might also try the following using a keyword argument with a default value:
id_cnt = 1
def give_id(id_constant=1000):
global id_cnt
id_cnt += 1
return id_constant * id_cnt
id = give_id()
Then if you ever needed id_constant to be something different, you could call the function as id = give_id(id_constant=500).
A little bit of tricky stuff:
def get_id_func(constant):
class c(object):
def __init__(self, constant):
self.constant = constant
self.id = 0
def func(self):
self.id += 1
return self.id * self.constant
o = c(constant)
return o.func
# create function
f = get_id_func(1000)
# call and test it
assert f() == 1000
assert f() == 2000
assert f() == 3000
Probably you need generator function?
def give_id(id_constant):
delta = 0
while True:
delta += 1
yield id_constant + delta
for i in range(100):
print(give_id(1000)) # prints numbers from 1001 to 1100