Open In App

Python – Frequency of x follow y in Number

Last Updated : 30 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Numbers in Python, we can have a problem in which we need to get the number of time one number follows other. This can have application in many domains such as day-day programming and other domains. Let us discuss certain ways in which this task can be performed. 

Method #1: Using loop

This is the brute force way in which we perform this task. 

In this, we traverse list and keep checking for previous and current number for result and keep incrementing the counter. 

Python3




# Python3 code to demonstrate working of
# Frequency of x follow y in Number
# using loop
 
 
def count_occ(num, next, prev):
    num = str(num)
    prev_chr = ""
    count = 0
    for chr in num:
        if chr == next and prev_chr == prev:
            count += 1
        prev_chr = chr
    return count
 
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number
# using loop
res = count_occ(test_num, j, i)
 
# printing result
print("The count of x preceding y : " + str(res))


Output

The original number : 12457454
The count of x preceding y : 2

Method #2: Using loop + isinstance() + regex

This is yet another way in which this task can be performed. In this, we use the regex function to check the preceding term rather than brute approach. 

Python3




# Python3 code to demonstrate working of
# Frequency of x follow y in Number
# using loop + isinstance() + regex
import re
 
 
def count_occ(num, next, prev):
    if not isinstance(num, str):
        num = str(num)
    return len(re.findall(prev + next, num))
 
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number
# using loop + isinstance() + regex
res = count_occ(test_num, j, i)
 
# printing result
print("The count of x preceding y : " + str(res))


Output

The original number : 12457454
The count of x preceding y : 2

Method #3: Using filter() + lambda

This is yet another way in which this task can be performed. In this, we use the filter() and lambda function to perform the task.

Python3




# Python3 code to demonstrate working of
# Frequency of x follow y in Number
# using filter() + lambda
   
def count_occ(num, next, prev):
    num = str(num)
    return len(list(filter(lambda i: num[i] == prev and num[i+1] == next, range(len(num)-1))))
   
# initialize Number
test_num = 12457454
   
# printing original number
print("The original number : " + str(test_num))
   
# initialize i, j
i, j = '4', '5'
   
# Frequency of x follow y in Number
# using filter() + lambda
res = count_occ(test_num, j, i)
   
# printing result
print("The count of x preceding y : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original number : 12457454
The count of x preceding y : 2

Time complexity: O(n)
Auxiliary space: O(1)

Method #4 : Using str() and count() methods

Python3




# Python3 code to demonstrate working of
# Frequency of x follow y in Number
# using loop
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number
# using loop
x = str(test_num)
y = i+j
res = x.count(y)
 
# printing result
print("The count of x preceding y : " + str(res))


Output

The original number : 12457454
The count of x preceding y : 2

Time complexity: O(n)
Auxiliary space: O(1)

Method #5: Using Regular Expression

  1. Define a function count_occ that takes in three arguments num, next, and prev.
  2. Convert num to a string using str() method.
  3. Create a regular expression pattern by concatenating prev and next variables.
  4. Find all matches of the pattern in the string representation of num using re.findall() method.
  5. Return the length of the matches found.
  6. Initialize variables test_num, i, and j.
  7. Call the count_occ() function with arguments test_num, j, and i.
  8. Print the result.

Python3




import re
 
 
def count_occ(num, next, prev):
    pattern = prev + next
    matches = re.findall(pattern, str(num))
    return len(matches)
 
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number
# using regex
res = count_occ(test_num, j, i)
 
# printing result
print("The count of x preceding y : " + str(res))


Output

The original number : 12457454
The count of x preceding y : 2

Time Complexity: O(n) where n is the length of the string representation of num.
Auxiliary Space: O(m) where m is the number of matches found by the regular expression pattern.

METHOD 6:digit-wise iteration

APPROACH:

In this approach we first check if the last digit of the number is equal to y. If it is, we then check each subsequent digit until we encounter a digit that is not equal to x. We keep track of the number of times we encounter x in this sequence. If the last digit of the number is not equal to y, we simply discard it and move on to the next digit. 

ALGORITHM:

1..Initialize a variable ‘count’ to 0.
2.While the number is greater than 0, check if the last digit of the number is equal to y.
3.If the last digit is y, then keep checking each subsequent digit until you encounter a digit that is not equal to x. Increment the count variable for each x encountered in this sequence.
4.If the last digit is not y, discard it and move on to the next digit.
5.Repeat steps 2-4 until all digits in the number have been checked.
6.Return the count variable.

Python3




def count_xy_frequency(num, x, y):
    count = 0
    while num > 0:
        if num % 10 == y:
            num //= 10
            while num % 10 == x:
                count += 1
                num //= 10
        else:
            num //= 10
    return count
 
# Example Usage
num = 12457454
x = 4
y = 5
print(count_xy_frequency(num, x, y))  # Output: 2


Output

2

This method has a time complexity of O(n), where n is the number of digits in the number, and an auxiliary space of O(1).

Method #7 : Using replace() and len() methods

Approach

  1. Convert test_num to string using str() and store in x variable
  2. Concatenate i and j ,store in y
  3. Replace y in x and store in z
  4. Compute len(x)-len(z)// len(y) where len() is used for finding length and store in res
  5. Display res which gives count of x preceding y

Python3




# Python3 code to demonstrate working of
# Frequency of x follow y in Number
# using loop
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number
# using loop
x=str(test_num)
y=i+j
z=x.replace(y,"")
res=(len(x)-len(z))//len(y)
 
# printing result
print("The count of x preceding y : " + str(res))


Output

The original number : 12457454
The count of x preceding y : 2

Time Complexity : O(N) N – length of test_num
Auxiliary Space: O(1) because we are using single output variable res

Method #8 : Using  heapq:

  1. Convert test_num to a list x by first converting it to a string and then converting each digit to an integer.
  2. Create a list y by concatenating the integers of i and j.
  3. Initialize a counter variable res to 0.
  4. Iterate over all pairs of adjacent elements in x, and if a pair is equal to y, increment res and remove the second element of the pair using heapq.heappop.
  5. Print the resulting count.

Python3




import heapq
 
# initialize Number
test_num = 12457454
 
# printing original number
print("The original number : " + str(test_num))
 
# initialize i, j
i, j = '4', '5'
 
# Frequency of x follow y in Number using heapq
x = [int(d) for d in str(test_num)]
y = [int(d) for d in i+j]
res = 0
for i in range(len(x)-1):
    if x[i:i+2] == y:
        res += 1
        heapq.heapify(x)
        heapq.heappop(x)
 
# printing result
print("The count of x preceding y : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original number : 12457454
The count of x preceding y : 2

Time complexity: O(n log n), where n is the number of digits in test_num. The heapq.heappop operation has a time complexity of O(log n), and it is called at most n times in this algorithm.

Space complexity: O(n), for the lists x and y. The heapq.heappop operation is performed in-place, so it does not add to the space complexity.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads