Python Uniform Strings program Codechef solution
Python Uniform Strings program Codechef solution
Problem
You are given a string of length 8 consisting solely of '0's and '1's. Assume that the characters of the string are written in a circular fashion. You need to find the number of 0-1 or 1-0 transitions that one has to make while making a single traversal over the string. i.e., start from any character and go circularly until you get back to the same character, and find the number of transitions that you made. The string is said to be uniform if there are at most two such transitions. Otherwise, it is called non-uniform.
Given the string s, tell whether the string is uniform or not.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T-test cases follows.
The only line of input contains the string s.
Output
For each test case, output "uniform" if the given string is uniform and "non-uniform" otherwise.
Constraints
- 1 ≤ T ≤ 256
- The length of s is 8.
Sample Input
4
00000000
10101010
10000001
10010011
Sample Output
uniform
non-uniform
uniform
non-uniform
Explanation
The number of transitions is 0, 8, 2, and 4 for the respective cases. So, the first and third ones are uniform, while the second and fourth ones are non-uniform.
Solution:
def is_uniform(s): transitions=0 for i in range(len(s)): if s[i]!=s[(i+1)%len(s)]: transitions+=1 if transitions<=2: return "uniform" else: return "non-uniform" T=int(input(“Enter the number of terms: “)) for i in range(T): s=input(“Enter string in 0’s and 1’s format: “) result=is_uniform(s) print(result) |
Steps to solve this problem:
- Ask the user to enter the number of terms.
- In the loop, ask the user to enter a string in 0’s and 1’s format and store it in s.
- Call the function is_uniform, pass s as an actual argument, and store the result in the result variable.
- Print the value of the result.
- Define a function with the name is_uniform that accepts an argument.
- Initialise a variable transition with 0.
- In the loop, check if the value at index s[i] is not equal to the value at index s[(i+1)%len(s)]. then increase the value of the transition by 1.
- Check if the transition is less than equal to 2 and return "uniform", otherwise return "non-uniform."