
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Frequency of Characters in Recaman Series in Python
Suppose we have a lowercase string s. We have to check whether the occurrences of alphabets in s, after rearranging in any possible manner, generates the Recaman’s Sequence (ignoring the first term).
The Recaman’s sequence is as follows −
$$a_{n}=\begin{cases}\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:0(if\:n=0) & \a_{n-1}-n(if\:a_{n}-n>0\wedge not\:present\in sequence) & \\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:\:a_{n-1}+n(otherwise)\end{cases}$$
Some of the items of Recaman's Sequence are [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24,...] (The first term is ignored as this is 0)
So, if the input is like s = "pppuvuuqquuu", then the output will be True as the characters and frequencies are (p, 3), (u, 6), (v, 1) and (q, 2). So the frequencies are forming first few terms of Recaman's Sequence [1, 3, 6, 2].
To solve this, we will follow these steps −
- freq := a map holding all characters in s and their frequencies
- n := size of freq
- array := first n Recaman's sequence terms
- f := 1
- for each char in freq, do
- is_found := 0
- for j in range 1 to n, do
- if freq[keys] is same as array[j], then
- is_found := 1
- come out from the loop
- if freq[keys] is same as array[j], then
- if is_found is false, then
- f := 0
- come out from the loop
- return True when f is set otherwise False
Example
Let us see the following implementation to get better understanding −
from collections import defaultdict def recaman(array, n) : array[0] = 0 for i in range(1, n + 1): temp = array[i - 1] - i for j in range(i): if array[j] == temp or temp < 0: temp = array[i - 1] + i break array[i] = temp def solve(s) : freq = defaultdict(int) for i in range(len(s)) : freq[s[i]] += 1 n = len(freq) array = [0] * (n + 1) recaman(array, n) f = 1 for keys in freq.keys() : is_found = 0 for j in range(1, n + 1) : if freq[keys] == array[j]: is_found = 1 break; if not is_found: f = 0 break return True if f else False s = "pppuvuuqquuu" print(solve(s))
Input
"pppuvuuqquuu"
Output
True