Q:

Write a python program to check if two strings are balanced.

belongs to collection: Python String Exercises

0

String characters balance Test

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.

Given:

Case 1:

s1 = "Yn"
s2 = "PYnative"

Expected Output:

True

Case 2:

s1 = "Ynf"
s2 = "PYnative"

Expected Output:

False

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

Iterate each character from a string s1 and check if the current character is present in the string s2.

Solution:

def string_balance_test(s1, s2):
    flag = True
    for char in s1:
        if char in s2:
            continue
        else:
            flag = False
    return flag


s1 = "Yn"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)

s1 = "Ynf"
s2 = "PYnative"
flag = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", flag)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a python program to find all occurrences of ... >>
<< Create a mixed String using the following rules us...