take two strings s1 and s2 from the user. write a program to check if two strings are balanced. for example strings s1 and s2 are balanced if all the characters in the s1 are present in s2. the character's position doesn't matter

Hi in this article let's try to solve the below program using python.

Take two strings s1 and s2 from the user. write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in the s1 are present in s2. The character’s position doesn’t matter.

The problem statement asks the user to enter two strings s1 and s2.  Then check if all the characters s1 is present in s2.  If all the characters of s1 are present in s2  then print it as a balanced string else  print it as not balanced.
 
 
write a program to check if two strings are balanced

 
 


Let's take two string variables s1 and s2 ask user to enter two string using input function call

s1 = input("Enter First String : ")
s2 = input("Enter Second String : ")


 
 
Take a Boolean variable balanced as a flag and set it to true. Now using the  for loop, iterate all the letters of string s1.  Using the if statement, check if the letter is not present in s2.

If letter of s1 is not present in s2 set the balanced flag to false and break the for loop. This will minimize the number of iterations and optimize our program.


balanced = True
for letter in s1:
   if letter not in s2:
       balanced = False
       break



Now using if statement check if balance is set to true then print it as balanced else not balanced.


if balanced:
   print("String s1 and s2 are balanced")
else:
   print("String s1 and s2 are not balanced")



Final program to Check if Two Strings Are Balanced.


s1 = input("Enter First String : ")
s2 = input("Enter Second String : ")

balanced = True
for letter in s1:
   if letter not in s2:
       balanced = False
       break

if balanced:
   print("String s1 and s2 are balanced")
else:
   print("String s1 and s2 are not balanced")




Output 1:

Enter First String : hey
Enter Second String : how are you ?
String s1 and s2 are balanced


Output 2:

Enter First String : hello
Enter Second String : how are you ?
String s1 and s2 are not balanced


Conclusion: Try to run the program by yourself by giving multiple string input and try to understand the problem by yourself. Comment down below if you have any queries  / suggestions.
 
 

Post a Comment

0 Comments