Showing posts with label Python programs. Show all posts
Showing posts with label Python programs. Show all posts

Thursday, January 4, 2024

Bubble Sort Program in Python

In this post we’ll see how to write Bubble sort program in Python. Bubble sort is considered the simplest sorting algorithm out of the three simpler sorting algorithms bubble sort, insertion sort and selection sort. Bubble sort is considered the slowest too because of a proportionally large number of swaps along with the comparisons.

How does Bubble sort work

In Bubble sort adjacent elements are compared and swapped if element at left is greater than element at right. For example if n[0] and n[1] are compared and n[0] > n[1] then n[0] and n[1] are swapped. Then you move by one index and compare the adjacent elements i.e. n[1] and n[2].

By the end of first pass you should have the maximum element in the list at the rightmost position. Since the maximum element bubbles up to the top thus the name Bubble sort.

To sum up the steps for bubble sort-

  1. Compare the adjacent elements.
  2. If element at the left is greater than the element at the right then swap the elements.
  3. Move one position right. Start from point 1.

In the next pass again you start from the two leftmost elements and compare the elements and swap if required. Since the rightmost element is already in its sorted position so this pass runs till (N-1) elements.

For example if you have an array [5, 3, 8, 2] then in the first pass-

Iteration 1- Initially 5 is compared with 3, since 5 (element at left) is greater than 3 (element at right), elements are swapped making the array [3, 5, 8, 2].

Iteration 2- Move to next position and compare element at index 1 and index 2 (5 and 8), since 5 is not greater than 8 so swapping is not done and array remains [3, 5, 8, 2].

Iteration 3- Again move over one position and compare 8 and 2. Since 8 is greater than 2, elements are swapped giving us the array as [3, 5, 2, 8].

As you can see by the end of first pass the maximum element is at the rightmost position. In the next pass last element is not included in the comparison as it is already at its final position so the array that is considered for comparison and swapping effectively becomes [3, 5, 2].

Bubble Sort Python program

def bubble_sort(nlist):
  list_length = len(nlist)
  # reduce length by 1 in each pass
  for i in range(list_length-1, 0, -1):
    for j in range(i):
      # compare
      if nlist[j] > nlist[j+1]:
        # swap elements
        nlist[j+1], nlist[j] = nlist[j], nlist[j+1]

nlist = [47, 85, 62, 34, 7, 10, 92, 106, 2, 54]
print('Original List-', nlist)
bubble_sort(nlist)
print('Sorted List-', nlist)

Output

Original List- [47, 85, 62, 34, 7, 10, 92, 106, 2, 54]
Sorted List- [2, 7, 10, 34, 47, 54, 62, 85, 92, 106]

Time and Space complexity of Bubble sort

In Bubble sort (N-1) comparisons are required in the first pass, (N-2) comparisons in the second pass, (N-3) comparisons in the third pass and so on.

So the total number of comparisons is- N(N-1)/2

Thus the time complexity of Bubble sort is O(n2).

Bubble sort is an in-place sorting algorithm and doesn’t require any auxiliary space so the space complexity of Bubble sort is O(1).

That's all for this topic Bubble Sort Program in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check if Strings Anagram or Not
  3. Python break Statement With Examples
  4. List in Python With Examples
  5. String Slicing in Python

You may also like-

  1. User-defined Exceptions in Python
  2. Functions in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Python count() method - Counting Substrings
  5. Difference Between HashMap And Hashtable in Java
  6. Binary Search Program in Java
  7. String Pool in Java
  8. Spring Boot Spring Initializr

Friday, December 30, 2022

Python Program to Check if Strings Anagram or Not

In this post we'll see a Python program to check if two strings are anagrams or not.

Anagram Strings

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "silent" and "listen", "School Master" and "The Classroom".

Strings Anagram or not Python program

Python program to check whether the given strings are anagrams or not can be written by using one of the following options.

  1. Sorting both the strings
  2. By iterating one of the string character by character and verifying that the second string has the same characters present.

1. By sorting string

If you are using sorting logic to find whether strings are anagram or not in Python, just sort both the strings and compare if content is equal that means strings are anagram.

You can use sorted() in built function in Python to sort which returns a new sorted list from the items in iterable. Before sorting the string you can also change the case of the strings and remove spaces from the string.

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)

  if sorted(temp1) == sorted(temp2):
    print(s1, 'and', s2, 'are anagrams')
  else:
    print(s1, 'and', s2, 'are not anagrams')
        
is_anagram('silent', 'listen')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- silent
s2 in lower case and no spaces- listen
silent and listen are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

2. By Iteration

If you are using loop to find whether strings are anagram or not in Python, then iterate one string char by char and check whether that character exists in another string or not, for that you can use find() method.

If character exists in the second string then delete that occurrence of the character from the string too so that same character is not found again (if char occurs more than once).

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)
  # if both strings are not of same length then not anagrams
  if len(temp1) != len(temp2):
    print(s1, 'and', s2, 'are not anagrams')

  for c in temp1:
    index = temp2.find(c);
    if index == -1:
      print(s1, 'and', s2, 'are not anagrams')
      break
    else:
      # delete the found character so that same character is
      # not found again
      temp2.replace(c, "", 1)
  else:
    print(s1, 'and', s2, 'are anagrams')

is_anagram('Hello', 'OHell')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- hello
s2 in lower case and no spaces- ohell
Hello and OHell are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

That's all for this topic Python Program to Check if Strings Anagram or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check Whether String is Palindrome or Not
  3. Python Program to Check Prime Number
  4. Removing Spaces From String in Python
  5. Accessing Characters in Python String

You may also like-

  1. Python continue Statement With Examples
  2. Polymorphism in Python
  3. Functions in Python
  4. Constructor in Python - __init__() function
  5. Switch Case Statement in Java
  6. HashMap in Java With Examples
  7. Convert Numbers to Words Java Program
  8. Configuring DataSource in Spring Framework

Thursday, December 22, 2022

Python Program to Check Whether String is Palindrome or Not

This post is about writing a Python program to find whether a given string is a palindrome or not.

A String is a palindrome if reverse of the string is same as the original string. For example "madam" is a palindrome as reverse of the madam is again madam another example is "malayalam".

Logic for the palindrome program

  1. One way to find whether a given string is a palindrome or not is to reverse the given string. If reverse of the string and original string are equal that means string is a palindrome.
  2. Another way is to iterate string and compare characters at both ends (start and end) for equality. Any time if a character is found that is not equal before start > end then it is not a palindrome.

1. Reversing string and comparing

For reversing a string in Python best way is to use string slicing with a negative increment number to get the string backward. Once you have the reversed string compare it with original string to check if both are equal or not.

import re
def reverse_string(string):
  rstring = string[::-1]
  return rstring

def is_palindrome(s):
  rstring = reverse_string(s)
  return True if (rstring == s) else False

s = "madam"
# if more than one word remove spaces
# s = re.sub("^\\s+|\\s+$|\\s+", "", s)
# print(s)
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

madam is a palindrome

Note that if string has more than one word like “nurses run” then remove the spaces from the string before checking for palindrome string. You can uncomment the commented lines for that.

2. Comparing characters from start and end of the string

You can also compare characters from both ends of the string, if any time a character is found which is not equal then the passed string is not a palindrome. Python program to find whether given string is a palindrome or not using this logic can be written both as a recursive function and iterative function.

Recursive function is given first.

def is_palindrome(s):
  print(s)
  if len(s) == 0:
    return True
  else:
    if s[0] == s[-1]:
      # remove start and end characters
      return is_palindrome(s[1:len(s)-1])
    else:
      return False

s = "radar"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

radar
ada
d

radar is a palindrome

As an iterative function.

def is_palindrome(s):
  # last index
  end = len(s) - 1;
  for start in range(len(s)):
    # all the characters are compared and are equal
    if start > end:
      return True
    else:
      # compare characters at both ends
      if s[start] == s[end]:
        # move towards left
        end -= 1
      else:
        return False

s = "malayalam"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

malayalam is a palindrome

That's all for this topic Python Program to Check Whether String is Palindrome or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Reverse a String
  2. Python Program to Display Armstrong Numbers
  3. Getting Substring in Python String
  4. Python String isnumeric() Method
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Ternary Operator in Python
  2. Operator Overloading in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Java CountDownLatch With Examples
  6. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  7. How to Write Excel File in Java Using Apache POI
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

Wednesday, December 21, 2022

Python Program to Display Armstrong Numbers

In this post we'll see a Python program to display Armstrong numbers with in the given range.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Display Armstrong numbers Python program

In the program user is prompted to input lower and upper range for displaying Armstrong numbers. Then run a for loop for that range, checking in each iteration whether the number is an Armstrong number or not.

def display_armstrong(lower, upper):
  for num in range(lower, upper + 1):
    digitsum = 0
    temp = num
    # getting length of number
    no_of_digits = len(str(num))
    while temp != 0:
      digit = temp % 10
      # sum digit raise to the power of no of digits
      digitsum += (digit ** no_of_digits)
      temp = temp // 10
    # if sum and original number equal then Armstrong number
    if digitsum == num:
      print(num, end=' ')

def get_input():
  """Function to take user input for display range"""
  start = int(input('Enter start number for displaying Armstrong numbers:'))
  end = int(input('Enter end number for displaying Armstrong numbers:'))
  # call function to display Armstrong numbers
  display_armstrong(start, end)

# start program
get_input()

Output

Enter start number for displaying Armstrong numbers:10
Enter end number for displaying Armstrong numbers:10000
153 370 371 407 1634 8208 9474 

That's all for this topic Python Program to Display Armstrong Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Prime Numbers
  2. Convert String to float in Python
  3. Python Program to Count Number of Words in a String
  4. Check String Empty or Not in Python
  5. Comparing Two Strings in Python

You may also like-

  1. Ternary Operator in Python
  2. Polymorphism in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Difference Between Comparable and Comparator in Java
  6. Java Semaphore With Examples
  7. Converting Enum to String in Java
  8. Sending Email Using Spring Framework Example

Friday, December 9, 2022

Python Program to Check Prime Number

In this post we'll see a Python program to check whether the passed number is a prime number or not. This program also shows a use case where for loop with else in Python can be used.

A number is a prime number if it can only be divided either by 1 or by the number itself. So the passed number has to be divided in a loop from 2 till number/2 to check if number is a prime number or not.

You need to start loop from 2 as every number will be divisible by 1.

You only need to run your loop till number/2, as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

Check prime number or not Python program

def check_prime(num):
  for i in range(2, num//2+1):
    # if number is completely divisible then it
    # it is not a prime number so break out of loop
    if num % i == 0:
      print(num, 'is not a prime number')
      break
  # if loop runs completely that means a prime number
  else:
    print(num, 'is a prime number')

check_prime(13)
check_prime(12)
check_prime(405)
check_prime(101)

Output

13 is a prime number
12 is not a prime number
405 is not a prime number
101 is a prime number

That's all for this topic Python Program to Check Prime Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Python Program to Display Fibonacci Series
  3. Python Program to Display Prime Numbers
  4. Python break Statement With Examples
  5. Changing String Case in Python

You may also like-

  1. Python Exception Handling - try,except,finally
  2. Getting Substring in Python String
  3. Constructor in Python - __init__() function
  4. Name Mangling in Python
  5. Java Stream API Tutorial
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Selection Sort Program in Java
  8. Spring Bean Life Cycle

Thursday, December 8, 2022

Python Program to Check Armstrong Number

In this post we'll see a Python program to check if a given number is an Armstrong number or not.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so-

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Check Armstrong number or not Python program

In the program user is prompted to input a number. Number of digits in that number is calculated using len() function that takes string as input that is why number is cast to str.

In the loop add each digit of the input number raised to the power of number of digits. After the control comes out of loop if sum and the input number are equal then it is an Armstrong number otherwise not.

def check_armstrong(num):
  digitsum = 0
  temp = num
  # getting length of number
  no_of_digits = len(str(num))
  while temp != 0:
    digit = temp % 10
    # sum digit raise to the power of no of digits
    digitsum += (digit ** no_of_digits)
    temp = temp // 10
  print('Sum of digits is',  digitsum)
  # if sum and original number equal then Armstrong number
  return True if (digitsum == num) else False

num = int(input('Enter a number: '))
flag = check_armstrong(num)
if flag:
  print(num, 'is an Armstrong number')
else:
  print(num, 'is not an Armstrong number')

Output

Enter a number: 371
Sum of digits is 371
371 is an Armstrong number

Enter a number: 12345
Sum of digits is 4425
12345 is not an Armstrong number

Enter a number: 54748
Sum of digits is 54748
54748 is an Armstrong number

That's all for this topic Python Program to Check Armstrong Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Prime Number
  2. Python Program to Display Fibonacci Series
  3. Python Program to Count Occurrences of Each Character in a String
  4. Python continue Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Name Mangling in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Constructor in Python - __init__() function
  4. Multiple Inheritance in Python
  5. ArrayList in Java With Examples
  6. Callable And Future in Java Concurrency
  7. Nested Class And Inner Class in Java
  8. Spring MessageSource Internationalization (i18n) Support

Tuesday, November 29, 2022

Python Program to Reverse a String

In this post we'll see how to write a Python program to reverse a string, there are several options to do that, the options given in this post are listed below-

  1. Using a loop to reverse a string.
  2. Using a recursive function.
  3. Using string slicing
  4. Using reversed() function and join() method

Using loop to reverse a string Python program

If you are asked to write Python program to reverse a string without using any inbuilt function or string method you can use a loop to add characters of a string in a reverse order in each iteration to form a new String.

def reverse_string(string):
  rstring = ''
  for char in string:
    rstring = char + rstring
  return rstring

s = 'Python Programming'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

Using recursive function to reverse a string

In recursive function, in each recursive call to the function you pass the sliced string where start index is 1 (i.e. exclude first char (index 0) in each call) and add the first char of the passed String at the end.

def reverse_string(string):
  if len(string) == 1:
    return string
  else:
    return reverse_string(string[1:]) + string[0]

s = 'Hello World'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

Using string slicing

One of the best way to reverse a string in Python is to use String slicing. In string in Python you can also use negative indexing. When negative number is used as index, String is accessed backward so -1 refers to the last character, -2 second last and so on. Thus, by providing increment_step as -1 in string slicing you can reverse a string.

def reverse_string(string):
  reversed = s[::-1]
  return reversed

s = 'Hello World'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Hello World Reversed String- dlroW olleH

Using reversed() function and join() method

In built function reversed() in Python returns a reverse iterator. Python String join() method returns a string which is created by concatenating all the elements in an iterable. By combining both of these you can get a reversed string in Python.

def reverse_string(string):
  rstring = "".join(reversed(string))
  return rstring

s = 'Python Programming'
rstring = reverse_string(s)
print('Original String-', s, 'Reversed String-', rstring)

Output

Original String- Python Programming Reversed String- gnimmargorP nohtyP

That's all for this topic Python Program to Reverse a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Program to Display Armstrong Numbers
  4. Check String Empty or Not in Python
  5. Python Functions : Returning Multiple Values

You may also like-

  1. Python assert Statement
  2. Operator Overloading in Python
  3. Nonlocal Keyword in Python With Examples
  4. User-defined Exceptions in Python
  5. How ArrayList Works Internally in Java
  6. Type Erasure in Java Generics
  7. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  8. Spring Object XML Mapping (OXM) Castor Example

Tuesday, November 15, 2022

Convert String to float in Python

In this post we’ll see how to convert String to float in Python.

If you have a float represented as String literal then you need to convert it to float value if you have to use it in any arithmetic operation.

For example-

num1 = "50.56"
num2 = 20.45
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 14, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "float") to str

As you can see num1 variable is of type string so Python tries to concatenate num2 to num1 rather than adding them. In such scenario you need to convert string to float.

Python program - convert String to float

To convert a Python String to a float pass that String to float() function which returns a float object constructed from the passed string.

num1 = "50.56"
num2 = 20.45
result = float(num1) + num2
print("Sum is-", result)

Output

Sum is- 71.01

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to float, ValueError is raised. If you are not sure about the passed number it is better to use try and except for exception handling.

For example in the following Python function string ‘abc’ is passed as one of the argument value which results in ValueErorr being raised while converting it.

def add(num1, num2):
  try:
    result = float(num1) + float(num2)
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add('abc', 10)

Output

Error while conversion: could not convert string to float: 'abc'

Getting integer part of the decimal number

If there is a decimal number stored as a string and you want only the integer part then directly using int() function results in error. You have to first convert string to float and then to int.

num = "50.56"
# Causes error
int_num = int(num) 
print("Integer part is-", int_num)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    int_num = int(num)
ValueError: invalid literal for int() with base 10: '50.56'

Correct way

num = "50.56"
int_num = int(float(num))
print("Integer part is-", int_num)

Output

Integer part is- 50

That's all for this topic Convert String to float in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Number of Words in a String
  3. Python String isnumeric() Method
  4. Operator Overloading in Python
  5. Check String Empty or Not in Python

You may also like-

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Convert String to float in Java
  6. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  7. intern() Method in Java String
  8. Java Exception Handling Tutorial

Sunday, September 11, 2022

Python Program to Count Occurrences of Each Character in a String

In this post we’ll see how to write a Python program to count occurrences of each character or to count frequency of character in a String.

1. If you have to write the Python program to count frequency of each character without using any String method then you can write it using an outer and inner for loop. In the outer loop take the character at index 0 and in the inner loop check if such character is found again in the string, if yes then increment count.

replace() method of the str class is used to remove all the occurrences of the character for which count is done so that same character is not picked again.

def count_char(text):
  for i in range(len(text)):
    if len(text) == 0:
      break;
    ch = text[0]
    # don't count frequency of spaces
    if ch == ' ' or ch == '\t':
        continue
    count = 1
    for j in range(1, len(text)):
      if ch == text[j]:
        count += 1
    # replace all other occurrences of the character
    # whose count is done, strip() is required for 
    # scenario where first char is replaced and there is 
    # space after that
    text = text.replace(ch, '').strip()
    print(ch + " - ", count)

count_char('netjs blog for Python')

Output

n -  2
e -  1
t -  2
j -  1
s -  1
b -  1
l -  1
o -  3
g -  1
f -  1
r -  1
P -  1
y -  1
h -  1

2. You can use count() method in Python which is used to count the number of occurrences of a specific substring.

def count_char(text):
  for i in range(len(text)):
    if len(text) == 0:
      break;
    ch = text[0]
    if ch == ' ' or ch == '\t':
      continue
    print(ch + " - ", text.count(ch))
    text = text.replace(ch, '').strip()

count_char('netjs java spring python')

Output

n -  3
e -  1
t -  2
j -  2
s -  2
a -  2
v -  1
p -  2
r -  1
i -  1
g -  1
y -  1
h -  1
o -  1

3. You can also use Dictionary to count occurrences of each character in the String. Character is stored as a key in dictionary and for each character it is checked if that character already exists as a key in dictionary or not. If it exists then increment the value associated with that key by 1, if such a key doesn’t exist then add it to the dictionary with value as 1.

def count_char(text):
  count = {}
  for ch in text:
    # don't count frequency of spaces
    if ch == ' ' or ch == '\t':
      continue
    # If char already in dictionary increment count
    # otherwise add char as key and 1 as value
    if ch in count:
      count[ch] += 1
    else:
      count[ch] = 1
    for k, v in count.items():
      print('Charcater {} occurs {} times'.format(k,v))

count_char('netjs java spring python')

Output

Charcater n occurs 3 times
Charcater e occurs 1 times
Charcater t occurs 2 times
Charcater j occurs 2 times
Charcater s occurs 2 times
Charcater a occurs 2 times
Charcater v occurs 1 times
Charcater p occurs 2 times
Charcater r occurs 1 times
Charcater i occurs 1 times
Charcater g occurs 1 times
Charcater y occurs 1 times
Charcater h occurs 1 times
Charcater o occurs 1 times

That's all for this topic Python Program to Count Occurrences of Each Character in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Number of Words in a String
  2. Removing Spaces From String in Python
  3. Check String Empty or Not in Python
  4. Python String isdigit() Method
  5. pass Statement in Python

You may also like-

  1. raise Statement in Python Exception Handling
  2. Magic Methods in Python With Examples
  3. self in Python
  4. Check if Given String or Number is a Palindrome Java Program
  5. instanceof Operator in Java With Examples
  6. Optional Class in Java With Examples
  7. Spring depends-on Attribute and @DependsOn With Examples
  8. @Import Annotation in Spring JavaConfig

Friday, September 2, 2022

Convert String to int in Python

In this post we’ll see how to convert String to int in Python.

If you have an integer represented as String literal then you need to convert it to integer value if you have to use it in any arithmetic operation.

For example-

num1 = "50"
num2 = 20
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "int") to str

As you can see since the first operand is string so Python tries to concatenate the second operand to the first rather than adding them. In such scenario you need to convert string to int.

Python program - convert String to int

To convert a Python String to an int pass that String to int() function which returns an integer object constructed from the passed string.

num1 = "50"
num2 = 20
# converting num1 to int
result = int(num1) + num2
print("Sum is-", result)

Output

Sum is- 70

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to int, ValueError is raised. While doing such conversions it is better to use try and except for exception handling.

def add():
  try:
    num1 = "abc"
    num2 = 20
    # converting num1 to int
    result = int(num1) + num2
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add()

Output

Error while conversion: invalid literal for int() with base 10: 'abc'

Converting String with commas to int

If String variable is storing a number with commas (as example str_num="6,00,000") then one of the option is to use replace() method of the str class to remove commas before converting string to int.

def add():
  try:
    num1 = "6,45,234"
    num2 = 230000
    # converting num1 to int
    result = int(num1.replace(',', '')) + num2
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add()

Output

Sum is- 875234

That's all for this topic Convert String to int in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to float in Python
  2. Python Program to Display Fibonacci Series
  3. Python String isdigit() Method
  4. Operator Overloading in Python
  5. Removing Spaces From String in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Python Functions : Returning Multiple Values
  3. Python Exception Handling Tutorial
  4. Local, Nonlocal And Global Variables in Python
  5. Converting String to int in Java
  6. ArrayList in Java With Examples
  7. Lambda Expressions in Java 8
  8. Interface Default Methods in Java 8

Friday, August 26, 2022

Python Program to Find Factorial of a Number

In this post we’ll see how to write a Python program to find factorial of a number.

Factorial of a non-negative integer n is product of all positive integers from 1 to n. For example factorial of 4 can be calculated as-

4! = 4 X 3 X 2 X 1 = 24

Factorial program is one of the first program you'll write to understand recursive function so naturally in this post you'll see python program for factorial using recursion apart from writing using its iterative counterpart.

There is also an inbuilt function in Python for calculating factorial.

1. Recursive program to find factorial. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of factorial program that base case is when num is 1.

def factorial(num):
  # base case(exit recursion)
  if num == 0 or num == 1:
    return 1
  else:
    return num * factorial(num - 1);

num = int(input('Enter a number- '))
print(factorial(num))

Output

Enter a number- 6
720

2. Iterative program to find factorial. Here for loop is used to iterate the passed number until it becomes 1, decrementing by 1 in each pass.

def factorial(num):
  fact = 1
  if num < 0:
    print('Please enter non-negative number')
  else:
    for i in range(num, 1, -1):
      fact = fact * i
    print('Factorial is- ', fact)

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- -4
Please enter non-negative number

Enter a number- 0
Factorial is-  1

Enter a number- 4
Factorial is-  24

3. Using factorial function of the math module in Python. Import math module and use math.factorial() function to find factorial of a number.

import math

def factorial(num):
  print('Factorial is- ', math.factorial(num))

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- 7
Factorial is-  5040

That's all for this topic Python Program to Find Factorial of a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Fibonacci Series
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Python return Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Class And Object in Python
  3. Removing Spaces From String in Python
  4. Fibonacci Series Program in Java
  5. Buffered Streams in Java IO
  6. DatabaseMetaData Interface in Java-JDBC
  7. Array in Java With Examples
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Wednesday, August 17, 2022

Python Program to Display Prime Numbers

In this post we'll see a Python program to display prime numbers in the given range. This program helps in understanding usage of nested loops and it also shows a use case where for loop with else in Python can be used.

A number is a prime number if it can be divided either by 1 or by the number itself. So every number with in the given range has to be divided in a loop from 2 till number/2 to check if number is a prime number or not. You only need to run your loop from 2 to N/2, rather than from 2 to N (where N is the current number in the passed range), as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

Displaying prime numbers Python program

def display_prime(lower, upper):
  for num in range(lower, upper+1):
    # instead of int(num/2), num//2 (floor division) can also be used
    for i in range(2, int(num/2)+1):
      # if number is completely divisible then it
      # it is not a prime number so break out of loop
      if num % i == 0:
        break
    # if loop runs completely that means a prime number
    else:
      print(num)


def get_input():
  """Function to take user input for display range"""
  start = int(input('Enter start number for displaying prime numbers:'))
  end = int(input('Enter end number for displaying prime numbers:'))
  # prime numbers start from 2
  if start <= 1:
    start = 2
  # call function to display prime numbers
  display_prime(start, end)

# start program
get_input()

Output

Enter start number for displaying prime numbers:40
Enter end number for displaying prime numbers:100
41
43
47
53
59
61
67
71
73
79
83
89
97 

That's all for this topic Python Program to Display Prime Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Python Program to Find Factorial of a Number
  3. Keyword Arguments in Python
  4. Name Mangling in Python
  5. Python continue Statement With Examples

You may also like-

  1. Python Exception Handling Tutorial
  2. Method Overriding in Python
  3. Abstract Class in Python
  4. Python String split() Method
  5. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  6. Java Program to Detect And Remove Loop in a Linked List
  7. Is String Thread Safe in Java
  8. Spring MVC File Upload (Multipart Request) Example

Monday, August 1, 2022

Python Program to Display Fibonacci Series

In this post we’ll see how to write a Python program to display Fibonacci series.

Fibonacci series is a series of natural numbers where next number is equivalent to the sum of previous two numbers. Equation for the same can be written as follows-

fn = fn-1 + fn-2

The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, and each subsequent number is the sum of the previous two numbers. Python programs in this post we'll display the Fibonacci series as- 0 1 1 2 3 5 8 ...

Python program for Fibonacci series can be written using recursion apart from writing using its iterative counterpart.

1. Fibonacci series using recursion. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of Fibonacci series program that base case is when num is 0 and 1.

def fibonacci(num):
  if num < 0:
    print('Please enter non-negative integer')
  # For first two numbers
  if num == 0:
    return 0
  if num == 1:
    return 1
  return fibonacci(num - 1) + fibonacci(num - 2)
 
# running function after taking user input
num = int(input('Enter how many numbers needed in Fibonacci series- '))
for i in range(num):
  print(fibonacci(i), end=' ')

Output

Enter how many numbers needed in Fibonacci series- 10
0 1 1 2 3 5 8 13 21 34 

2. Fibonacci series program using iteration. Here for loop is used to iterate the passed number and in each iteration two previous numbers are added to get a new number in the series.

def fibonacci(num):
  num1 = 0
  num2 = 1
  series = 0
  for i in range(num):
    print(series, end=' ');
    num1 = num2;
    num2 = series;
    series = num1 + num2;

# running function after takking user input
num = int(input('Enter how many numbers needed in Fibonacci series- '))
fibonacci(num)

Output

Enter how many numbers needed in Fibonacci series- 8
0 1 1 2 3 5 8 13

That's all for this topic Python Program to Display Fibonacci Series. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Find Factorial of a Number
  2. Python Program to Count Number of Words in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Getting Substring in Python String
  5. Python String isnumeric() Method

You may also like-

  1. Python Exception Handling - try,except,finally
  2. Encapsulation in Python
  3. Python Installation on Windows
  4. Factorial Program in Java
  5. Array in Java With Examples
  6. StringJoiner Class in Java With Examples
  7. Covariant Return Type in Java
  8. Spring MVC Form Example With Bean Validation

Sunday, May 1, 2022

Python Program to Count Number of Words in a String

In this post we’ll see how to write a Python program to count number of words in a String. This program can be written in various ways and this post shows some of the ways.

1. If you can’t use any of the methods of the String class then Python program for counting number of words can be written by iterating each character of the string using for loop and check if the character is space (' '), tab('\t') or linefeed ('\n'). If such a character is found that means a new word is starting so the count is incremented by 1.

def number_words(text):
  print('String-', text)
  no_of_words = 1
  for ch in text:
    if (ch == ' ' or ch == '\t' or ch == '\n'):
      no_of_words += 1
  print('Total number of words in String', no_of_words)

number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

String- This is a test string
Total number of words in String 5
String- This Python program counts number of words in a String.
Total number of words in String 10

2. Using split() method in Python you can count words in a String. Whitespaces are used as a separator by default in split() method and the method returns a list of the words in the string. By using len() function you can get the length of that list which gives the number of words in a String.

def number_words(text):
  print('Total number of words in String', len(text.split()))
    
number_words('This is a test string')
s = 'This Python program counts\tnumber of words in a String.'
number_words(s)

Output

Total number of words in String 5
Total number of words in String 10

3. You can also write Python program to count number of words in a String using regular expressions in Python. In the program two methods split() and findall() are used.

The split() method splits the string as per the passed regular expression and the split words are returned as a list.

The findall() method returns all occurrences of the matching string as a list.

\s sequence character represents white space, \s+ means 1 or more white spaces.

\W sequence character represents non-alphanumeric, \W+ means 1 or more non-alphanumeric characters.

import re

def number_words(text):
  print('Total number of words in String', len(re.findall(r'\W+', text)))
  print('Total number of words in String', len(re.split(r'\s+', text)))

number_words('This is a Python program')
s = 'This Python program\'s job is to find number of words in a String'
number_words(s)

Output

Total number of words in String 4
Total number of words in String 5
Total number of words in String 13
Total number of words in String 13

That's all for this topic Python Program to Count Number of Words in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Changing String Case in Python
  3. Python String split() Method
  4. Python count() method - Counting Substrings
  5. Python while Loop With Examples

You may also like-

  1. User-defined Exceptions in Python
  2. Namespace And Variable Scope in Python
  3. Multiple Inheritance in Python
  4. ListIterator in Java
  5. TreeMap in Java With Examples
  6. Count Number of Words in a String Java Program
  7. Spring Component Scan Example
  8. Benefits, Disadvantages And Limitations of Autowiring in Spring