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
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        ...
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))", "{([]})", "{}())",...
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 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 >=...
Python: I am not sure where to begin with this question, and I hope I can...
Python: I am not sure where to begin with this question, and I hope I can get an input on it. This is in regards to Downey's program, and we are asked to make two changes. Downey prints time as they do in the Army: 17:30:00 hours. We want to print that as 5:30 PM. Downey lets you define the time 25:00:00 - we want to turn over at 23:59:59 to 00:00:00. (I am asked to identify my changes with...
***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...
Use Python Return a password string constructed with the following rules: (1) If there are only...
Use Python Return a password string constructed with the following rules: (1) If there are only 0 or 1 numeric among 3 parameters, concatenate the string form of all parameters directly. (2) If there are 2 numeric parameters, calculate the sum of 2 numeric values if they are both int, or calculate the product of them and round to 2 decimal places if any of them is float. Finally, append this sum/product to the string parameter. You may assume that...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT