How to fix "None" answer and Take inputs as arguments? - python-3.x

I'm giving mettl exam and the question was for solving the parenthesis are matching or not.But all I'm getting as result is NONE.
I'm not sure how to take the input as argument, please help out:
I've tried changing, it is taking the input if I provide a hard coded one.
'''
# these are the metll instructions
class UserMainCode(object):
#classmethod
def areParenthesisBalanced(cls, input1):
'''
input1 : string
Expected return type : string
'''
# Read only region end
# Write code here
pass
'''
# this is the code I tried
class Stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
def show_me(self):
return self.items
def peek(self):
if not self.is_empty():
return self.items[-1]
input1=[]
def areParenthesisBalanced(input1):
s=Stack()
is_balanced=True
index=0
def is_match(p1,p2):
if p1=="(" and p2==")":
return True
elif p1=="[" and p2=="]":
return True
elif p1=="{" and p2=="}":
return True
else:
return False
while index< len(input1) and is_balanced:
paren=input1[index]
if paren in"({[":
s.push(paren)
else:
if s.is_empty():
is_balanced=False
else:
top = s.pop()
if not is_match(top,paren):
is_balanced=False
index+=1
if s.is_empty() and is_balanced:
return True
else:
return False
print (areParenthesisBalanced(input1))
I was hoping to atleast get a normal True. I'm not sure how to proceed

Related

Nested function in Python class

i have a little "basic understanding" Python problem.
So let me explain my problem.
At first a very simple code snippet.
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
return self.__sentence[::-1]
if __name__ == '__main__':
print(Revert("Stackoverflow").get_sentence())
print(Revert("Stackoverflow").revert_sentence())
So this show normal function calling of python functions.
But how can i transform this code so i can call the revert function like this:
print(Revert("Stackoverflow").get_sentence().revert_sentence())
Maybe I'm miss the forest through the trees. But I didn't get it how to do this.
I already tried to solve the problem with innermethods but this didn't work for me
...
def get_sentence(self):
def revert_sentence():
self.revert_sentence()
return self.__sentence
...
Many thanks in advance
Implement __str__ to return the actual string. Then in the existing methods, return the object. This way you can chain. But when print is applied to it, that __str__ method will kick in:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self
def revert_sentence(self):
return Revert(self.__sentence[::-1])
# Some more such methods ...
def upper(self):
return Revert(self.__sentence.upper())
def first(self, count):
return Revert(self.__sentence[:count])
def dotted(self):
return Revert(".".join(self.__sentence))
# For getting a string
def __str__(self):
return self.__sentence
print(Revert("Stackoverflow").get_sentence().revert_sentence())
print(Revert("Stackoverflow")
.revert_sentence()
.first(8)
.upper()
.revert_sentence()
.first(4)
.dotted()) # "O.V.E.R"
Note that now the .get_sentence() method is not really doing much, and you can always strip it from a chain.
Here You go:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
# It's important to know that you are making changes in the same instance of the object
self.__sentence = self.__sentence[::-1]
return self
def pseudo_revert(self):
# Return a new object with reverted string, but this instance still has original string intact.
return Revert(self.__sentence[::-1])
if __name__ == '__main__':
r1 = Revert("Stackoverflow")
r2 = Revert("Stackoverflow")
print(r1.get_sentence()) # Stackoverflow
print(r1.revert_sentence().get_sentence()) # wolfrevokcatS
print(r1.get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
print(r2.pseudo_revert().get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
Hope this helps you understand the object, instance of an object, and method of object distinctly.

Python : How to return two values from function which is called from elif?

The elif someother_function(): here check if it is true and also need to print the returned value.
Can anyone help me with this?
def some_function():
if correct:
return True
else:
return False
def someother_function():
if correct:
return True,f
else:
return False,None
if some_function():
print("something")
elif someother_function():
print(f)
else:
print("nothing")
Here, how to return f from someother_function to where it called at elif?
You can try:
def some_function(correct):
if correct:
return False
else:
return False
def someother_function():
if correct:
return True, f
else:
return False, None
if some_function():
print("something")
elif [x := someother_function()] and x[0]:
print(x[1])
else:
print("nothing")
If you want you can write a class with your functions and set a class variable with your output:
import random
class foo:
def __init__(self):
self.f=None
def some_function(self):
correct= random.choice([True, False])
if correct:
return True
else:
return False
def someother_function(self):
self.f = "something 2"
correct= random.choice([True, False])
if correct:
return True,
else:
return False,None
if __name__=="__main__":
temp = foo()
if temp.some_function():
print("something")
elif temp.someother_function():
print(temp.f)
else:
print("nothing")
I think you need to specify a sort of event. Check this code and try it if you want:
import random
event = random.choice([True, False])
def some_function(correct):
if correct:
return True
else:
return False
def someother_function(correct):
if correct:
return True, f
else:
return False, None
if event == True:
some_function()
print("something")
elif event == False:
someother_function():
print(f)
else:
print("nothing")
Maybe not exactly what you want but you can turn your function into generator.
def some_function():
return correct
def someother_function():
if correct:
yield True
yield "A"
else:
yield False
yield None
someother_function_gen = someother_function()
if some_function():
print("something")
elif next(someother_function_gen):
print(next(someother_function_gen))
else:
print("nothing")

Write a Python program to generate tickets for online bus booking, based on the class diagram given below

Initialize static variable counter to 0
validate_source_destination(): Validate source and destination. source must always be Delhi and destination can be either Mumbai, Chennai, Pune or Kolkata. If both are valid, return true. Else return false
generate_ticket():Validate source and destination. If valid, generate ticket id and assign it to attribute ticket_id. Ticket id should be generated with the first letter of source followed by first letter of destination and an auto-generated value starting from 01 (Ex: DM01, DP02,.. ,DK10,DC11). Else, set ticket_id as None.
Note: Perform case insensitive string comparison
For testing:
Create objects of Ticket class
Invoke generate_ticket() method on Ticket object
Display ticket id, passenger name, source, destination
In case of error/invalid data, display appropriate error message
class Ticket:
counter=0
def __init__(self,passenger_name,source,destination):
self.__passenger_name=passenger_name
self.__source=source
self.__destination=destination
self.Counter=Ticket.counter
Ticket.counter+=1
def validate_source_destination(self):
if (self.__source=="Delhi" and (self.__destination=="Pune" or self.__destination=="Mumbai" or self.__destination=="Chennai" or self.__destination=="Kolkata")):
return True
else:
return False
def generate_ticket(self ):
if True:
__ticket_id=self.__source[0]+self.__destination[0]+"0"+str(self.Counter)
print( "Ticket id will be:",__ticket_id)
else:
return False
def get_ticket_id(self):
return self.ticket_id
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
if self.__source=="Delhi":
return self.__source
else:
print("you have written invalid soure option")
return None
def get_destination(self):
if self.__destination=="Pune":
return self.__destination
elif self.__destination=="Mumbai":
return self.__destination
elif self.__destination=="Chennai":
return self.__destination
elif self.__destination=="Kolkata":
return self.__destination
else:
return None
when generate_ticket() method will give false condition I don't want to print ticket_id but in my code after the false statement the ticket id does print output.
class Ticket:
counter=0
def init(self, passenger_name, source, destination):
self.__passenger_name=passenger_name
self.__source=source.lower()
self.__destination=destination.lower()
self.__ticket_id=None
Ticket.counter+=1
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
return self.__source
def get_destination(self):
return self.__destination
def get_ticket_id(self):
return self.__ticket_id
def validate_source_destination(self):
if self.__source== "delhi" and (self.__destination=="mumbai" or self.__destination=="chennai" or self.__destination=="pune" or self.__destination=="kolkata"):
return True
else:
return False
def generate_ticket(self):
if self.validate_source_destination() == True:
srcchar=self.__source[0].upper()
destchar=self.__destination[0].upper()
if(Ticket.counter<10):
self.__ticket_id=srcchar+destchar+"0"+str(Ticket.counter)
else:
self.__ticket_id=srcchar+destchar+str(Ticket.counter)
else:
self.__ticket_id=None
return self.__ticket_id
try this thing:
class Ticket:
def __init__(self, passenger_name, source, destination):
self.counter = 0
self.__passenger_name = passenger_name
self.__source = source
self.__destination = destination
self.Counter = self.counter
self.counter += 1
def validate_source_destination(self):
all_destinations = ["Pune", "Mumbai", "Chennai", "Kolkata"]
if self.__source == "Delhi" and self.__destination in all_destinations:
return True
else:
return False
def generate_ticket(self):
if self.validate_source_destination() == True:
self.ticket_id=self.__source[0]+self.__destination[0]+"0"+str(self.Counter)
print("Ticket id will be: " + self.ticket_id)
else:
return False
def get_ticket_id(self):
return self.ticket_id
def get_passenger_name(self):
return self.__passenger_name
def get_source(self):
if self.__source == "Delhi":
return self.__source
else:
print("You have written invalid soure option")
return None
def get_destination(self):
all_destinations = ["Pune", "Mumbai", "Chennai", "Kolkata"]
if self.__destination in all_destinations:
return self.__destination
else:
return None

syntax in if statement is correct but code stops running after that(figured through printing)

I get my problem in if statement in forward cargo function, I will also paste the question, I am using eclipse
forward_cargo():
Validate from_customer.customer_id, recipient_customer.customer_id, distance and weight of the freight
If valid,
auto-generate freight_id starting from 200 and initialize it. freight_id should be even
calculate freight_charge based on weight (Rs.150/kg) and distance (Rs.60/km)
Else, set freight_charge to 0
#USM2-Assgn-5
class Customer:
def __init__(self,customer_id,customer_name,address):
self.__customer_id=customer_id
self.__customer_name=customer_name
self.__adress=address
def validate_customer_id(self):
cusID=str(self.__customer_id)
if cusID[0]=="1" and len(cusID)==6: return True
else: return False
def get_customer_id(self):
return self.__customer_id
def get_customer_name(self):
return self.__customer_name
def get_address(self):
return self.__address
class Freight:
counter=198
def __init__(self,recipient_customer, from_customer, weight, distance):
self.__recipient_customer=recipient_customer
self.__from_customer=from_customer
self.__weight=weight
self.__distance=distance
self.__freight_charge=None
self.__freight_id=None
def get_recipient_customer(self):
return self.__recipient_customer
def get_from_customer(self):
return self.__from_customer
def get_weight(self):
return self.__weight
def get_distance(self):
return self.__distance
def get_freight_charge(self):
return self.__freight_charge
def get_freight_id(self):
return self.__freight_id
def validate_weight(self):
if self.__weight%5==0: return True
else: return False
def validate_distance(self):
if self.__distance>=500 and self.__distance<=5000: return True
else: return False
def forward_cargo(self):
print(self.get_from_customer().validate_customer_id())
if self.get_from_customer().validate_customer_id()== True and self.get_recipient_customer().validate_customer_id()== True and self.validate_distance()==True and self.validate_weight()==True:
print(self.get_from_customer().validate_customer_id())
print(self.get_recipient_customer().validate_customer_id())
self.__freight_charge=(self.__distance*60)+(self.__weight*150)
Freight.counter+=2
print(Freight.counter)
self.__freight_id=Freight.counter
print("hi")
else: self.__freight_charge=0
kreta= Customer(123456,"nl","1230 jamaica")
bikreta= Customer(287397,"sad","1230 jamaica")
print(kreta.get_customer_id())
print(bikreta.get_customer_id())
ataki=Freight(bikreta,kreta,30, 500)
print(ataki.get_from_customer().get_customer_id(), ataki.get_recipient_customer().get_customer_id(),ataki.get_distance(), ataki.get_weight())
ataki.forward_cargo()
print(ataki.get_freight_id())
print( ataki.get_freight_charge())

what does this <bound method Stack.pop of <__main__.Stack object at 0x03C74AB0>> mean?

class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return (self.items ==[])
def __str__(self):
return str(self.items)
def postfixEval(postfixExpres):
operandStack = Stack()
tokenlist = postfixExpres.split()
for token in tokenlist:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop
operand1 = operandStack.pop
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop
def doMath(op,op1,op2):
if op == "*":
return op1*op2
elif op == "/":
return op1/op2
elif op =="+":
return op1 + op2
elif op == "-":
return op1 - op2
print(postfixEval('12+'))
I believe it means you returned a function object of the pop method instead of a value at the end of postfixEval. Change operandStack.pop to operandStack.pop() (add the parentheses to apply the pop method instead of returning it).
Additionally, if I'm not mistaken, '12+'.split() will return '123' in python, since split uses whitespaces as the default delimiter. If you want to turn the string into a list of single characters, you can cast the string to a list instead list('12+') will return ['1', '2', '+'].
class stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def pop(self):`
self.items.pop()
def get_stack(self):
return self.items
def emp(self):
return self.items==[]
def peek(self):
if not self.emp():
return self.items[-1]
s=stack()
print("stack is empty: ",s.emp())
s.push('a')
s.push('b')
print(s.get_stack())
s.push(12)
print(s.get_stack())
s.pop()
print(s.get_stack())
s.push('c')
print(s.get_stack())
print('peek value is: ',s.peek())
print("stack is empty: ",s.emp())
In this case it means you're using the method object instead of calling it. In the doMath method you should use both variables like this: op1()*op2().

Resources