- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of strings we can make using grammar rules in Python
Suppose we have a number n, we have to find the number of strings of length n can be generated using the following rules −
Each character is a lower case vowel [a, e, i, o, u]
"a" may only be followed by one "e"
"e" may only be followed by any of "a" and "i"
"i" may not be followed by another "i"
"o" may only be followed by any of "i" and "u"
"u" may only be followed by one "a"
If the result is very large, mod the result by 10^9 + 7.
So, if the input is like n = 2, then the output will be 10, as we can generate the following two letter strings: ["ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou", "ua"]
To solve this, we will follow these steps −
m = 10^9 + 7
if n is same as 0, then
return 0
define five variables a, e, i, o, u, all are 1 initially
for _ in range 0 to n-1, do
a := e+i+u
e := a+i
i := e+o
o := i
u := i+o
return (a + e + i + o + u) mod m
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): m = (10 ** 9 + 7) if n == 0: return 0 a = e = i = o = u = 1 for _ in range(n-1): a, e, i, o, u = e+i+u, a+i, e+o, i, i+o return (a + e + i + o + u) % m ob = Solution() print(ob.solve(3))
Input
3
Output
19
- Related Articles
- Program to count number of unique palindromes we can make using string characters in Python
- C++ program to count number of dodecagons we can make of size d
- Program to count maximum number of strings we can generate from list of words and letter counts in python
- Program to count number of ways we can make a list of values by splitting numeric string in Python
- Program to count the number of consistent strings in Python
- Program to find maximum number of people we can make happy in Python
- Program to count number of ways we can throw n dices in Python
- Program to count number of ways we can distribute coins to workers in Python
- Program to find number of ways we can concatenate words to make palindromes in Python
- Program to count number of words we can generate from matrix of letters in Python
- Program to find possible number of palindromes we can make by trimming string in Python
- Python Program to Count number of binary strings without consecutive 1’
- Program to split two strings to make palindrome using Python
- Program to find maximum number of coins we can get using Python
- Program to check whether one string swap can make strings equal or not using Python
