Question

In: Computer Science

Python: If I am given a string consisting only of parentheses - (, ), {, },...

Python: If I am given a string consisting only of parentheses - (, ), {, }, [, and ], how would I write a Boolean function that takes a string and decides if it consists of valid nested parenthesis? One of the hints given was to use stack. For example --> {()[{}]}' is valid.

Solutions

Expert Solution

screenshot

code

def isBalanced(str1):
  
stk = []
for char in str1:
if char == '(' or char == '{' or char == '[':
stk.append(char)
elif char == ')' or char == '}' or char == ']':
# if stk is empty means unbalanced
if len(stk) <= 0:
return False
elif char == ')':
if stk[len(stk)-1] != '(':
return False
stk.pop()
elif char == '}':
if stk[len(stk)-1] != '{':
return False
stk.pop()
elif char == ']':
if stk[len(stk)-1] != '[':
return False
stk.pop()
# all paranthesis are balanced then stk is empty
if len(stk) != 0:
return False
else:
return True
  

str1 = "{()[{}]}"
print(isBalanced(str1))


Related Solutions

Given a parentheses string s, compute the score of the string based on the following rule:...
Given a parentheses string s, compute the score of the string based on the following rule: • If s is not balanced, the score is 0. • () has score 1. • AB has score A + B, where A and B are balanced parentheses strings. • (A) has score 2 * A, where A is a balanced parentheses string. A balanced string satisfies the following requirements: • The number of ‘(’ equals the number of ‘)’ in the string....
Given a String variable address, write a String expression consisting of the string "http://" concatenated with...
Given a String variable address, write a String expression consisting of the string "http://" concatenated with the variable's String value. So, if the variable refers to "www.turingscraft.com", the value of the expression would be "http://www.turingscraft.com". in java
Write a method called isMatch that takes a string of parentheses and check if all parentheses...
Write a method called isMatch that takes a string of parentheses and check if all parentheses match correctly. The parameter string might consist of other characters. Ignore other characters, just check the () {} [] public static boolean isMatch(String expressionLine); Use a JCF ArrayDeque or LinkedList as a stack to store all open or left parentheses. Use following main method to check your method. public static void main(String[] args) { String[] expression = new String[]{"{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})", "({}((0))", "{([]})", "{}())",...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
In the given instruction, I am to use while loops only. The goal is to prompt...
In the given instruction, I am to use while loops only. The goal is to prompt the user to select an acceptable input. If the wrong input is given, the program forces the user to select an appropriate input. The program also keeps running until the user chooses to exist by selecting a very specific input which in my case is the upper or lower case "E". The problem is even after selecting upper or lower case "E", my program...
IN PYTHON Write a function capitalize_last(phrase) that takes in a string phrase consisting of arbitrarily capitalized...
IN PYTHON Write a function capitalize_last(phrase) that takes in a string phrase consisting of arbitrarily capitalized words separated by spaces, and returns a new string consisting of those words but with the only the last letter in each word uppercase. You can assume that the string contains only letters and spaces, no punctuation. Examples: >>> capitalize_last('tEst WiTH rANdoM capITaliZATioN') 'tesT witH randoM capitalizatioN' >>> capitalize_last('') '' >>> capitalize_last('i am the senate') 'I aM thE senatE'
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a...
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a list that only contains the duplicate characters. In other words, your new list should contain the characters which appear more than once. Suggested Approach Used two nested for loops. The first for loop iterates from 0 to range(len(input_str)). The second for loop iterates from first_loop_index + 1 to range(len(input_str)). The reason you want to start at first_loop_index + 1 in the nested inner loop...
I am given this starter code and I am suppose to debug it and all of...
I am given this starter code and I am suppose to debug it and all of that and it will not work after I change ">" to "<=" and then i'm not sure after that what else I have to do. Could someone help me solve this? // Start with a penny // double it every day // how much do you have in a 30-day month? public class DebugSix1 {    public static void main(String args[])    {      ...
***This is the only information I am given. **** Week 2 Date Transaction description 9 Purchased...
***This is the only information I am given. **** Week 2 Date Transaction description 9 Purchased 14 Specialist Tennis Raquets from Addax Sports for $232 each, terms net 30. 10 Mick's Sporting Goods paid the full amount owing on their account. Since Mick's Sporting Goods has been a loyal customer from the day the business commenced, a 10% discount was given for this early repayment. 11 Paid the full amount owing to Sports 'R Us, Check No. 873. Payment fell...
This is in Python I am getting an error when I run this program, also I...
This is in Python I am getting an error when I run this program, also I cannot get any output. Please help! #Input Section def main(): name=input("Please enter the customer's name:") age=int(input("Enter age of the customer: ")) number_of_traffic_violations=int(input("Enter the number of traffic violations: ")) if age <=15 and age >= 105: print('Invalid Entry') if number_of_traffic_violations <0: print('Invalid Entry') #Poccessing Section def Insurance(): if age < 25 and number_of_tickets >= 4 and riskCode == 1: insurancePrice = 480 elif age >=...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT