This question already has answers here:
How do I call a method from another method?
(3 answers)
Closed 2 years ago.
I am new python programmer and trying to write Python class with 2 functions and calling one from another.
below is my code, can someone please help me in fixing the code.
class Solution:
def repeat_check(string):
for i in range(1, len(string)//2+1):
if not len(string)%len(string[0:i]) and string[0:i]*(len(string)//len(string[0:i])) == string:
return string[0:i]
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
fraction = str(numerator/denominator)
decimal_pos = fraction.index('.')
repeat_string = str(fraction[decimal_pos+1:])
if numerator%denominator==0:
return fraction
elif numerator%denominator!=0 and repeat_check(repeat_string) is None:
return repeat_string
elif numerator%denominator!=0 and repeat_check(repeat_string).isdigit():
return fraction+'.('+repeat_string+')'
I got error message name "repeat_check is not defined"
input
numerator = 2 denominator = 3
output
0.(6)
You are missing "self" in the repeat_check method:
class Solution:
def repeat_check(self, string):
for i in range(1, len(string) // 2 + 1):
if not len(string) % len(string[0:i]) and string[0:i] * (len(string) // len(string[0:i])) == string:
return string[0:i]
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
fraction = str(numerator / denominator)
decimal_pos = fraction.index('.')
repeat_string = str(fraction[decimal_pos + 1:])
if numerator % denominator == 0:
return fraction
elif numerator % denominator != 0 and self.repeat_check(repeat_string) is None:
return repeat_string
elif numerator % denominator != 0 and self.repeat_check(repeat_string).isdigit():
return fraction + '.(' + repeat_string + ')'
First of all I reccomend you to make indents. Therefore the Function will be a field of the class.
Scond: Every Function of the class gets the "self" argument. and then you can refer it with self.repeat_check().
Best regards
Related
def one(*args):
if len(args) == 0:
return 1
return args
def plus(*args):
first_number = args[1]
second_number = args[0]
sum = first_number + second_number
return sum
def two(*args):
if len(args) == 0:
return 2
return args
print(one(plus(two())))
the question is to do calculations by using functions and it contains 3 parts first number, operation, and the second number and the goal is to do the operation (second part) on those two numbers (first part and third part) for example one(plus(two())) should return 3
now here is the part I don't know how to do, plus() function is called with one argument two() one(plus(two())) I want to add a second argument the initial number (first number) to the function so plus() function is now called with two args like this plus(two(), 1).
Now plus(two()) is args[0] inside one() function how can I append 1 to that args[0] so that the function be called like this plus(two(), 1) to access it inside plus() and first_number = args[1] becomes valid
The code below implements a similar syntax to the example, but with slightly different argument structure. I think this way the logic is clearer.
The point is that I define plus as a partial function so that it "absorb" two to form a function that works as "add_two".
def plus(number):
def _plus(x):
return x + number
return _plus
def one(op=None):
if op is None:
return 1
return op(1)
def two(op=None):
if op is None:
return 2
return op(2)
one(plus(two()))
# 3
One idea is to have plus return a function that will be called afterward by one or two:
def one(*args):
if len(args) == 0:
return 1
elif len(args) == 1:
fn = args[0]
return fn(1)
else:
raise ValueError("Invalid number of arguments")
def two(*args):
if len(args) == 0:
return 2
elif len(args) == 1:
fn = args[0]
return fn(2)
else:
raise ValueError("Invalid number of arguments")
def plus(second_number):
def adder(first_number):
return first_number + second_number
return adder
Now:
>>> one(plus(two()))
3
>>> one(plus(one()))
2
>>> two(plus(one()))
3
>>> two(plus(two()))
4
And to simplify and DRY it:
def make_number(n):
def number_fn(fn=None):
if fn:
return fn(n)
else:
return n
return number_fn
def make_operator(operator):
def operator_wrapper(second_number):
def partial(first_number):
return operator(first_number, second_number)
return partial
return operator_wrapper
one = make_number(1)
two = make_number(2)
plus = make_operator(lambda a, b: a + b)
minus = make_operator(lambda a, b: a - b)
>>> two(minus(one()))
1
I am doing a task where I have a class Fractions which contains functions as to how I can add, subtract, multiply and divide the fractions. I am having trouble creating the add function which will be adding 2 fractions and this function must use the staticmethod. This is the code that I have written so far:
class Fraction:
def __init__(self,num1=0,num2=0):
self.num1=num1
self.num2=num2
def __str__(self):
while self.num1>self.num2:
a = self.num1//self.num2
b = self.num1 % self.num2
if self.num2==1:
return "%s"%(self.num1)
elif self.num1 % self.num2==0:
return "%s"%(self.num1/self.num2)
else:
return "%s+%s|%s"%(a,b,self.num2)
if self.num1==0:
return "0"
elif self.num1 or self.num2 < 0 and self.num1==self.num2:
return "-1"
elif self.num2==1:
return "%s"%(self.num1)
elif self.num1==self.num2:
return "1"
else:
return "%s|%s"%(self.num1,self.num2)
#staticmethod
def add(a,b):
a=Fraction(n,d)
b=Fraction(num,den)
if a.d == b.den and a.n<a.d or b.num<b.den:
return "%s|%s"%(a.n+b.num,a.d)
elif a.d != b.den:
return "%s|%s"%((a.n*b.den)+(a.d*b.num),(a.d*b.den))
I am facing trouble in trouble in the add function and I do not know how to make the function work.
For example:
Fraction.add(Fraction(1,4),Fraction(2,4))
>>> 3|4
Fraction.add(Fraction(1,5),Fraction(6,7))
>>> 1 + 2|35
This is what the output should look like. Could anyone guide me through the add function and how I can improve it using the staticmethod
If the arguments a and b are already Fraction objects, then you would use the attributes from them directly in your method:
#staticmethod
def add(a,b):
if a.num2 == b.num2 and (a.num1 < a.num2 or b.num1 < b.num2):
return "%s|%s"%(a.num1 + b.num1, a.num2)
elif a.num2 != b.num2:
return "%s|%s"%((a.num1 * b.num2) + (a.num2 * b.num1), (a.num2 * b.num2))
There were also a missing parenthesis in the first if clause.
This question already has answers here:
How can I call a function within a class?
(2 answers)
function name is undefined in python class [duplicate]
(2 answers)
Closed 2 years ago.
Hello Hope you guys are doing well.
I have a class which has several methods and I have a runner which randomly executes a function out of the several class methods. I have tried using First Class Function methodology in runner function but runner does not recognizes the function names. Can anybody tell my why?
My code:
import random
class A:
def delete_random_character(self, s):
"""Returns s with a random character deleted"""
if s == "":
return s
pos = random.randint(0, len(s) - 1)
# print("Deleting", repr(s[pos]), "at", pos)
return s[:pos] + s[pos + 1:]
def insert_random_character(self, s):
"""Returns s with a random character inserted"""
pos = random.randint(0, len(s))
random_character = chr(random.randrange(32, 127))
# print("Inserting", repr(random_character), "at", pos)
return s[:pos] + random_character + s[pos:]
def flip_random_character(self, s):
"""Returns s with a random bit flipped in a random position"""
if s == "":
return s
pos = random.randint(0, len(s) - 1)
c = s[pos]
bit = 1 << random.randint(0, 6)
new_c = chr(ord(c) ^ bit)
# print("Flipping", bit, "in", repr(c) + ", giving", repr(new_c))
return s[:pos] + new_c + s[pos + 1:]
def runner(self, s):
"""Return s with a random mutation applied"""
mutators = [
delete_random_character, ################ Cant recognizes the function why????
insert_random_character,
flip_random_character
]
mutator = random.choice(mutators)
# print(mutator)
return mutator(s)
You are not using references to your class functions initializing mutators; you should
mutators=[
self.delete_random_character,
self.insert_random_character,
self.flip_random_character
]
I've searched similar questions about converting classes but none have really helped me.
I have a Fraction class and want to simplify it to an int if possible.
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.simplify()
if self.denominator == 1:
# convert self to int of value numerator
I have a function within the Fraction class which will simplify the fraction when it is created (2/6 becomes 1/3, etc.)
def simplify(self):
div = gcd(self.numerator, self.denominator)
self.numerator //= div
self.denominator //= div
My current solution to this problem is as follows:
def convert(fraction):
if fraction.denominator == 1:
return fraction.numerator # int
else:
return fraction # Fraction
f = Fraction(3, 1)
f = convert(f)
I'm using these fractions in various algebraic expressions so I would like them to be as simple as possible. eg. 1/2 + 1/2 = 1 (instead of 1/1)
Is there any way I can convert the Fraction object into an int without having to pass it through this external function every time?
Thanks
There are a couple of things you can do:
It is not optimal to have a function which returns two different types, so you could handle the conversion with a class method.
It would help if the conversion was supported in the print() func as well
With that in mind, I just moved convert inside the class, and added a str method as well.
from fractions import gcd
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
self.simplify()
def __str__(self):
if self.denominator == 1:
return str(self.numerator)
return '{}/{}'.format(self.numerator,self.denominator)
def simplify(self):
div = gcd(self.numerator, self.denominator)
self.numerator //= div
self.denominator //= div
def convert(fraction):
if fraction.denominator == 1:
return fraction.numerator # int
return fraction # Fraction
if __name__ == '__main__':
f = Fraction(6, 2)
c = Fraction.convert(f)
print(f)
print(c)
f2 = Fraction(3, 4)
print(f2)
See if it can help you.
How do I create the divide method in Python?
This is my code:
# Rational numbers
def gcd(bigger, smaller):
'''compute the greatest common divisor of two positive integers'''
#print(' in gcd ')
if not bigger > smaller :
bigger, smaller = smaller, bigger
while smaller != 0:
remainder = bigger % smaller
#print('gcd calc, big:{}, small:{}, rem:{}'.format(bigger, smaller, remainder))
bigger, smaller = smaller, remainder
return bigger
def lcm(a, b):
'''calculate the least common multiple of two positive integers'''
#print(' in lcm ')
return (a*b)//gcd(a,b)
class Rational(object):
'''Rational with numerator and denominator. Denominator defaults to 1'''
def __init__(self, numer, denom = 1):
#print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
'''String representation for printing'''
#print(' in str ')
return str(self.numer) + '/' + str(self.denom)
def __repr__(self):
''' Used in the interpreter. Call __str__ for now'''
print(' in repr ')
return self.__str__()
def __add__(self, param_Rational):
'''Add two Rationals'''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom + \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
else:
print("Wrong type in addition method.")
raise(TypeError)
def __sub__(self, param_Rational):
'''Subtract two Rationals'''
#print(' in add ')
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom - \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
def reduce_rational(self):
'''Return the reduced fraction value as a Rational'''
# find the gcd and divide numerator and denominator by it
the_gcd = gcd(self.numer, self.denom)
return Rational( self.numer//the_gcd, self.denom//the_gcd)
def __eq__(self, param_Rational):
'''Compare two Rationals for equalit and return a Boolean'''
reduced_self = self.reduce_rational()
reduced_param = param_Rational.reduce_rational()
return reduced_self.numer == reduced_param.numer and\
reduced_self.denom == reduced_param.denom
def __mul__(self, param_Rational):
''' Multiply two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.numer
denom_mul = self.denom*param_Rational.denom
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
else:
print("Wrong type in subtraction method")
raise(TypeError)
""" """
def __truediv__(self): # <-------- Here is where TypeError occurs #
''' Divide two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.denom
denom_mul = self.denom*param_Rational.numer
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
And I'm getting the error (location marked above):
TypeError: __truediv__() takes 1 positional argument but 2 were given
How do I fix this? I got the multiplication down but not the divide, should I use div or truediv? And do I need to use / in the actual div method?
How can __truediv__ only take one argument? You need two, self and the divisor. The same way your __mul__ __add__, and __sub__ needed a second argument.
def __truediv__(self, param_Rational):
# rest of your code
Instead of first printing an error message and then raising the error, you can use:
raise TypeError("Wrong type in addition method.")
Also, it might be usefull to check wether the demnominator is 0 or not in init(), and raise ZeroDivisionError if it is.
PS: 2/3 / 6/9 should equal 1/1 as 2/3=6/9=0.666...