Find Frequency of Each Character in String and their Indices and Finding Duplicate Characters in a String

Find Frequency of Each Character in String and their Indices and Finding Duplicate Characters in a String

String:

A string is a group of alphabets, words, or other characters. It is a primitive data structure that serves as the foundation for data manipulation. Python has a string class called str. Strings in Python are “immutable,” which means they can’t be modified once they’re formed. Because of the immutability of strings, we generate new strings as we go to represent computed values.

Given a string, the task is to find frequency of each character in a string .

Examples:

Input:

string = "hello this is btech geeks online learning platform for underguate students"

Output:

Frequency of each character of the string is :
The frequency of character h is = 3
The frequency of character e is = 9
The frequency of character l is = 5
The frequency of character o is = 4
The frequency of character   is = 10
The frequency of character t is = 6
The frequency of character i is = 4
The frequency of character s is = 5
The frequency of character b is = 1
The frequency of character c is = 1
The frequency of character g is = 3
The frequency of character k is = 1
The frequency of character n is = 6
The frequency of character a is = 3
The frequency of character r is = 4
The frequency of character p is = 1
The frequency of character f is = 2
The frequency of character m is = 1
The frequency of character u is = 3
The frequency of character d is = 2

Finding count of Each Character in a String and their Indices and Finding Duplicate Characters in a given String

There are several ways to find frequency of each character in a string some of them are:

1)Using Counter() function  to print frequency of each character in given string

Counter is a subclass of dict and a set. Counter() takes an iterable object as an argument and stores its elements as keys and their frequencies as values. As a result, if we transfer a string in collections. Counter() will then return a Counter class object with all characters in the string as keys and their frequency in the string as values.

Below is the implementation:

# importing Counter function from collections
from collections import Counter
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# Using counter() function to calculate frequency of each character of the string
freq = Counter(string)
print("Frequency of each character of the string is :")
# Traverse the freq dictionary and print their respective count
for key in freq:
    print("The frequency of character", key, "is =", freq[key])

Output:

Frequency of each character of the string is :
The frequency of character h is = 3
The frequency of character e is = 9
The frequency of character l is = 5
The frequency of character o is = 4
The frequency of character   is = 10
The frequency of character t is = 6
The frequency of character i is = 4
The frequency of character s is = 5
The frequency of character b is = 1
The frequency of character c is = 1
The frequency of character g is = 3
The frequency of character k is = 1
The frequency of character n is = 6
The frequency of character a is = 3
The frequency of character r is = 4
The frequency of character p is = 1
The frequency of character f is = 2
The frequency of character m is = 1
The frequency of character u is = 3
The frequency of character d is = 2

2)Using regex to find frequency and indices of all characters in a string

We will construct a regex pattern to fit all of the alphanumeric characters in the string,

Make a Regex pattern that matches alphanumeric characters.

regex_Pattern = re.compile('[a-zA-Z0-9]')

Iterate over all of the above-mentioned pattern matches in the string using pattern.

finditer() and generate dictionaries of each character’s frequency count and index position in the string.

Below is the implementation:

import re
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# regex pattern
regex_Pattern = re.compile('[a-zA-Z0-9]')
# Iterate through the string's alphanumeric characters which matches the regex pattern
# While iterating, keep the frequency count of each character in a dictionary updated.
matchiterator = regex_Pattern.finditer(string)
charfrequency = {}
indices = {}
for matchchar in matchiterator:
    charfrequency[matchchar.group()] = charfrequency.get(
        matchchar.group(), 0) + 1
    indices[matchchar.group()] = indices.get(
        matchchar.group(), []) + [matchchar.start()]
print("Frequency and indices of each character in the string is :")
# Traverse the charfrquency dictionary and print their respective count and indices
for key in charfrequency:
    print("The frequency of character", key, "is =",
          charfrequency[key], " ; Indices of occurrence = ", indices[key])

Output:

Frequency and indices of each character in the string is :
The frequency of character h is = 3  ; Indices of occurrence =  [0, 7, 18]
The frequency of character e is = 9  ; Indices of occurrence =  [1, 16, 21, 22, 31, 34, 58, 64, 70]
The frequency of character l is = 5  ; Indices of occurrence =  [2, 3, 28, 33, 43]
The frequency of character o is = 4  ; Indices of occurrence =  [4, 26, 47, 52]
The frequency of character t is = 6  ; Indices of occurrence =  [6, 15, 45, 63, 67, 72]
The frequency of character i is = 4  ; Indices of occurrence =  [8, 11, 29, 38]
The frequency of character s is = 5  ; Indices of occurrence =  [9, 12, 24, 66, 73]
The frequency of character b is = 1  ; Indices of occurrence =  [14]
The frequency of character c is = 1  ; Indices of occurrence =  [17]
The frequency of character g is = 3  ; Indices of occurrence =  [20, 40, 60]
The frequency of character k is = 1  ; Indices of occurrence =  [23]
The frequency of character n is = 6  ; Indices of occurrence =  [27, 30, 37, 39, 56, 71]
The frequency of character a is = 3  ; Indices of occurrence =  [35, 44, 62]
The frequency of character r is = 4  ; Indices of occurrence =  [36, 48, 53, 59]
The frequency of character p is = 1  ; Indices of occurrence =  [42]
The frequency of character f is = 2  ; Indices of occurrence =  [46, 51]
The frequency of character m is = 1  ; Indices of occurrence =  [49]
The frequency of character u is = 3  ; Indices of occurrence =  [55, 61, 68]
The frequency of character d is = 2  ; Indices of occurrence =  [57, 69]

3)Using Counter to find Duplicate characters in the given string

Now, use collections to find all of the duplicate characters in this string. Counter() is used to determine the frequency of of character in a string, and characters with a frequency greater than 1 are considered duplicates.

Below is the implementation:

# importing Counter function from collections
from collections import Counter
# Given string
string = "hello this is btech geeks online learning platform for underguate students"
# Using counter() function to calculate frequency of each character of the string
freq = Counter(string)
print("Printing duplicate characters in the given string :")
# Traverse the freq dictionary and print the duplicate characters
for key in freq:
    # if the freq of character is greater than 1 then it is duplicate character so we print it
    if(freq[key] > 1):
        print(key)

Output:

Printing duplicate characters in the given string :
h
e
l
o
 
t
i
s
g
n
a
r
f
u
d

Related Programs:

Python : How to Check if a Directory is Empty ?

How to Check if a Directory is Empty

One of Python’s many features is the ability to determine whether or not a directory is empty. The os module can be used to accomplish this. In Python, the OS module has functions for communicating with the operating system. Python’s basic utility modules include OS. This module allows you to use operating system-dependent features on the go. Many functions to communicate with the file system are included in the os and os.path modules.

A directory, also known as a folder, is a grouping of files and subdirectories. The os module in Python contains many useful methods for working with directories (and files as well).

Given a directory the task is to check whether the given _directory is empty or not

Check if a Directory is Empty

The os module in Python has a feature that returns a list of files or folders in a directory.

os.listdir(path='.')

It gives you a list of all the files and subdirectories in the direction you specified.

There are several ways to check whether the directory is empty or not some of them are:

Method #1:Using len() function

The directory is empty if the returned list is empty or has a size of 0.

We can find size using len() function.

If the given then it will print given_directory is empty else given_directory is not empty

Below is the implementation:

# checking if the given directory is empty or not
if len(os.listdir('/home/btechgeeks/posts')) == 0:
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

Method #2:Using not operator

If not of given path is true then it will print given_directory is empty

else given_directory is not empty.

Below is the implementation:

# checking if the given directory is empty or not
if not os.listdir('/home/btechgeeks/posts'):
    print("given_directory is empty")
else:
    print("given_directory is not empty")

Output:

given_directory is empty

In exceptional cases, check to see if a directory is empty

There may be times when os.listdir() throws an exception. As an example,

  • If the specified path does not exist.
  • If the given path exists, but it is not a directory.

In both cases, os.listdir() will return an error, so we must check this first before calling os.listdir().

Below is the implementation:

# checking if the given directory is empty or not
# given  directory
given_directory = '/home/btechgeeks/posts'
if os.path.exists(given_directory) and os.path.isdir(given_directory):
    if not os.listdir():
        print("given_directory is empty")
    else:
        print("given_directory is not empty")
else:
    print("given_directory doesn't exists')

Output:

given_directory is empty

Related Programs:

Designing Code for Fibonacci Sequence without Recursion

Designing Code for Fibonacci Sequence without Recursion

Fibonacci sequence:

The Fibonacci sequence is a sequence type in which the sum of the previous two numbers is each consecutive number.

First few Fibonacci numbers are 0 1 1 2 3 5 8 …..etc.

Fibonacci sequence without recursion:

Let us now write code to display this sequence without recursion. Because recursion is simple, i.e. just use the concept,

Fib(i) = Fib(i-1) + Fib(i-2)

However, because of the repeated calculations in recursion, large numbers take a long time.

So, without recursion, let’s do it.

Approach:

  • Create two variables to hold the values of the previous and second previous numbers.
  • Set both variables to 0 to begin.
  • Begin a loop until N is reached, and for each i-th index
    • Print the sum of the previous and second most previous i.e sum= previous + second previous
    • Assign previous to second previous i.e. second previous= previous
    • Assign sum to previous i.e previous=sum

Below is the implementation:

1)C++ implementation of above approach.

#include <iostream>
using namespace std;
int main()
{ // given number
    int n = 10;
    // initializing previous and second previous to 0
    int previous = 0;
    int secondprevious = 0;
    int i;
    // loop till n
    for (i = 0; i < n; i++) {
        // initializing sum to previous + second previous
        int sum = previous + secondprevious;
        cout << sum << " ";
        if (!sum)
            previous = 1;
        secondprevious = previous;
        previous = sum;
    }
    return 0;
}

2)Python implementation of above approach.

# given number
n = 10
# initializing previous and second previous to 0
previous = 0
secondprevious = 0
# loop till n
for i in range(n):
    sum = previous + secondprevious
    print(sum, end=" ")
    if (not sum):
        previous = 1
    # initializing value to previous to second previous
    secondprevious = previous
    previous = sum

Output:

0 1 1 2 3 5 8 13 21 34

Related Programs:

Python: Break keyword – Explained with Examples

Break keyword – Explained with Examples

Break Keyword:

The break statement ends the loop that contains it. Control of the programme is transferred to the statement immediately following the body of the loop.

If the break statement is within a nested loop (a loop within another loop), it will terminate the innermost loop.

Break keyword in Python

We can use break keyword in loops such as while loop and for loop as given below.

1)While loop with break keyword

It can cause a while loop to stop in the middle, even if the condition in the “while statement” remains True.

When the interpreter encounters a break statement, it stops the current loop execution and jumps directly to the code following the loop block.

Example:

Let us use break keyword in while loop .

Let us print all even elements from 1 to n till the number is not divisible by 5.

Below is the implementation:

# given n
n = 100
x = 1
# Using while to iterate till n
while(x <= n):
    # if the x is divisible by 5 then break the loop
    if(x % 5 == 0):
        break
    else:
        print(x)
        # increment the x
        x += 1
print("Break keyword is succesfully executed")

Output:

1
2
3
4
Break keyword is succesfully executed

Explanation:

In the preceding example, the condition in a while statement is True. Because the condition in the ‘while statement’ is always True, this type of loop will iterate over a set of statements indefinitely. We used a break statement to end this loop.

We are printing the value of x and then incrementing it by one in the loop block. Then it determines whether or not x is divisible by 5. When x is divisible by 5, the break statement is invoked. This ends the loop, and control is returned at the end of the while loop.

2)For loop with break Keyword

Example:

Let us use break keyword in for loop .

Given a list and print elements of list till the element of list is not divisible by 2.

Below is the implementation:

# given list
given_list = [4, 2, 8, 4, 1, 3, 7]
# Traverse the list using for loop
for i in range(len(given_list)):
    # if the element is not divisible by 2 then break the loop
    if(given_list[i] % 2 != 0):
        break
    else:
        print(given_list[i])
print("Break keyword executed successfully")

Output:

4
2
8
4
Break keyword executed successfully

Python Program to Calculate the Length of a String Without Using a Library Function

Program to Calculate the Length of a String Without Using a Library Function

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

sample_string='BTechGeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is btechgeeks online

Output:

The length of given string { hello this is btechgeeks online } = 31

Example2:

Input:

given string = for file operations upload files using 23199 -@33hello

Output:

The length of given string { for file operations upload files using 23199 -@33hello } = 54

Program to Calculate the Length of a String Without Using a Library Function in Python

Below is the full approach to calculate the length of the given string without using built-in library len() in Python.

1)Using Count variable(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'HelloThisisBTechGeeks'
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

The length of given string { HelloThisisBTechGeeks } = 21

Explanation:

  • A string must be entered by the user as static input and saved in a variable.
  • The count variable is set to zero.
  • The for loop is used to go over the characters in a string.
  • When a character is encountered, the count is increased.
  • The total number of characters in the string, which is the string’s length, is printed.

2)Using Count variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
given_string = input('Enter some random string = ')
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

Enter some random string = btechgeeksonlineplatformforgeeks and coding platform
The length of given string { btechgeeksonlineplatformforgeeksa nd coding platform } = 52

The total number of characters in the string, which is the string’s length, is printed.
Related Programs:

What is a Dictionary in Python and why do we need it

What is a Dictionary in Python and why do we need it

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Dictionary in Python and why do we need it

1)Dictionary in Python

This is a dictionary example that contains cricket names as keys and the highest score as values. Elements are stored as key-value pairs in the dictionary, where each value is mapped to one key. It is also called a hash table or an associative array.

dictionary

There are four elements in the above dictionary, i.e. four key-value pairs.

  1. Devilliers & 176
  2. Virat Kohli & 183
  3. Dhoni & 183
  4. Gayle & 237

2)Use of Dictionary

As a dictionary, it holds the elements in key-value mapping format and uses hashing internally; as a result, we can easily retrieve a value from the dictionary by its key. In the best-case scenario, its complexity is O(1), while in the worst-case scenario, it can be O(n).

3)Creating a new Dictionary

We can create dictionary by two ways i.e two types of syntaxes.

  1. dict()
  2. {}

It will generate an empty dictionary.
Transfer the key-value pairs in curly braces to build a dictionary of objects. A colon will also be used to divide the key and value in each pair (:).

Let us create a sample dictionary and print the key value pairs in it

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 100, 'is': 200, 'BTechGeeks': 300}

4)The most important things to know about keys in the dictionary

Keys in the dictionary are always unique, and they must be of an immutable data type, such as strings, numbers, or tuples.
This means that once a key-value pair is added to the dictionary, we cannot change the key itself, but we can change the value associated with it.

For example, suppose we make a dictionary with duplicate keys and print its contents.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 300, 'is': 200}

5)The most important things to know about values in the dictionary

A dictionary’s values can be of any type.

Let’s make a dictionary where the key is an integer and the value is a list of strings.

Below is the implementation:

# given dictionary
dictionary = {1: ["HELLO", "THIS", 453], 
              2: ["BTECHGEEKS", 345, 87, 4.5], 
              3: ["PYTHON", True, 3.2, 100]}
# printing the dictionary
print(dictionary)

Output:

{1: ['HELLO', 'THIS', 453], 2: ['BTECHGEEKS', 345, 87, 4.5], 3: ['PYTHON', True, 3.2, 100]}

6)Accessing an element in dictionary

Using the [] operator on the dictionary object, we can access a specific item/pair in a dictionary. If we use the dictionary object’s operator [] and pass a key, it will return its value as shown below.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the element value in dictionary
print(dictionary['is'])

Output:

200

Now when we pass a key which does not exist in the dictionary, a KeyError is returned

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the element value in dictionary
print(dictionary['python'])

Output:

Traceback (most recent call last):
  File "/home/eb2788937138651d15b1bf1915ff16a5.py", line 4, in <module>
    print(dictionary['python'])
KeyError: 'python'

Related Programs: