DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 17: Number Programs, Strings, Indexing and Slicing

1. Perfect Number

A Perfect Number is a positive number that is equal to the sum of its proper divisors.

Proper divisors are the divisors of a number, excluding the number itself.

Example 1:

Divisors of 6 (excluding 6):

1, 2, 3

Sum = 1 + 2 + 3 = 6

Therefore, 6 is a Perfect Number.

Example 2:

Divisors of 28 (excluding 28):

1, 2, 4, 7, 14

Sum = 1 + 2 + 4 + 7 + 14 = 28

Therefore, 28 is also a Perfect Number.


def perfect_number(no):
    div = 1
    total = 0

    while div <= no // 2:
        if no % div == 0:
            total += div

        div += 1

    if total == no and no > 1:
        print("Perfect Number")
    else:
        print("Not a Perfect Number")


perfect_number(6)
Enter fullscreen mode Exit fullscreen mode
Output:

Perfect Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Find the divisors of the given number.
  • Add all proper divisors.
  • Compare the sum with the original number.
  • If both are equal, it is a Perfect Number.

2. Neon Number

A Neon Number is a number where the sum of the digits of its square is equal to the original number.

Example:

Step 1: Find the square.

9 × 9 = 81

Step 2: Find the sum of digits.

8 + 1 = 9

Step 3: Compare.

9 == 9

Therefore, 9 is a Neon Number.


def neon_number(no):
    square = no ** 2
    total = 0

    while square > 0:
        digit = square % 10
        total += digit
        square = square // 10

    if total == no:
        print("Neon Number")
    else:
        print("Not a Neon Number")


neon_number(9)
Enter fullscreen mode Exit fullscreen mode
Output:

Neon Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Calculate the square of the number.
  • Extract each digit using % 10.
  • Add the digits.
  • Compare the sum with the original number.

3. Strong Number

A Strong Number is a number whose sum of the factorials of its digits is equal to the original number.

Example:

Split the digits:

1, 4, 5

Find the factorial of each digit:

  • 1! = 1
  • 4! = 4 × 3 × 2 × 1 = 24
  • 5! = 5 × 4 × 3 × 2 × 1 = 120

Add the factorials:

1 + 24 + 120 = 145

Therefore, 145 is a Strong Number.

What is Factorial?

Factorial means multiplying all positive integers from 1 up to the given number.

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

import math

def strong_number(no):
    original = no
    result = 0

    while no > 0:
        digit = no % 10
        no = no // 10

        fact = math.factorial(digit)
        result += fact

    if result == original:
        print("Strong Number")
    else:
        print("Not a Strong Number")


strong_number(145)
Enter fullscreen mode Exit fullscreen mode

Output:

Strong Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Extract each digit.
  • Find the factorial of each digit.
  • Add all factorial values.
  • Compare the result with the original number.

4. Automorphic Number

An Automorphic Number is a number whose square ends with the same digits as the original number.

For example:

5 × 5 = 25

The square of 5 ends with 5. Therefore, 5 is an Automorphic Number.

def automorphic_number(no):
    square = no ** 2
    digits = len(str(no))

    if square % (10 ** digits) == no:
        print("Automorphic Number")
    else:
        print("Not an Automorphic Number")


automorphic_number(5)
Enter fullscreen mode Exit fullscreen mode
Output:

Automorphic Number
Enter fullscreen mode Exit fullscreen mode

5. Duck Number

A Duck Number is a positive number that contains at least one zero in its digits.

Examples:

  • 3210
  • 8050896
  • 70709

Important: A number starting with zero is not considered a Duck Number in its usual integer representation.

def duck_number(no):
    original = no
    found = False

    while no > 0:
        digit = no % 10

        if digit == 0:
            found = True
            break

        no = no // 10

    if found:
        print("Duck Number")
    else:
        print("Not a Duck Number")


duck_number(3210)
Enter fullscreen mode Exit fullscreen mode

Output:

Duck Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Extract each digit using % 10.
  • Check whether any digit is zero.
  • If zero is found, it is a Duck Number.

6. Spy Number

A Spy Number is a number where the sum of its digits is equal to the product of its digits.

Example: 1412

Sum of digits:

1 + 4 + 1 + 2 = 8

Product of digits:

1 × 4 × 1 × 2 = 8

Both results are equal.

Therefore, 1412 is a Spy Number.

def spy_number(no):
    total = 0
    product = 1

    while no > 0:
        digit = no % 10

        total += digit
        product *= digit

        no = no // 10

    if total == product:
        print("Spy Number")
    else:
        print("Not a Spy Number")


spy_number(1412)
Enter fullscreen mode Exit fullscreen mode

Output:

Spy Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Extract each digit.
  • Calculate the sum of all digits.
  • Calculate the product of all digits.
  • Compare both values.

7. Amicable Numbers

Two numbers are called Amicable Numbers when the sum of the proper divisors of the first number equals the second number, and the sum of the proper divisors of the second number equals the first number.

Example: 220 and 284

Proper divisors of 220:

1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284

Proper divisors of 284:

1 + 2 + 4 + 71 + 142 = 220

Therefore, 220 and 284 are Amicable Numbers.

def sum_of_factors(no):
    div = 1
    total = 0

    while div <= no // 2:
        if no % div == 0:
            total += div

        div += 1

    return total


def amicable_number(no1, no2):
    sum1 = sum_of_factors(no1)
    sum2 = sum_of_factors(no2)

    if sum1 == no2 and sum2 == no1:
        print("Amicable Numbers")
    else:
        print("Not Amicable Numbers")


amicable_number(1184, 1210)
Enter fullscreen mode Exit fullscreen mode
output:
Amicable Numbers
Enter fullscreen mode Exit fullscreen mode

Logic:

  1. Find the proper divisors of the first number and calculate their sum.
  2. Find the proper divisors of the second number and calculate their sum.
  3. Check whether the first sum equals the second number and the second sum equals the first number.

8. Prime Number and Emirp Number

We already know that a Prime Number is a number greater than 1 that has exactly two factors: 1 and itself.

An Emirp Number is a prime number whose reverse is also a different prime number.

Example:

  • 17 is a prime number.
  • Reverse of 17 is 71.
  • 71 is also a prime number.
  • 17 and 71 are different.

Therefore, 17 is an Emirp Number.

def emirp_number(no):
    original = no
    reverse = 0

    while no > 0:
        digit = no % 10
        reverse = reverse * 10 + digit
        no = no // 10

    if original != reverse and find_prime(original) and find_prime(reverse):
        print("Emirp Number")
    else:
        print("Not an Emirp Number")


emirp_number(17)
Enter fullscreen mode Exit fullscreen mode
output:
Emirp Number
Enter fullscreen mode Exit fullscreen mode

Logic:

  1. Check whether the original number is prime.
  2. Reverse the number using % 10 and // 10.
  3. Check whether the reversed number is also prime.
  4. Make sure the reversed number is different from the original.

Introduction to Strings in Python

What is a String?

A String is a sequence of characters enclosed within quotes.

We can use:

  • Single quotes: ' '
  • Double quotes: " "
  • Triple quotes: ''' ''' or """ """

Examples

name = 'Saravanan'
name2 = "Prem"

print(name)
print(name2)

print(type(name))
print(type(name2))
Enter fullscreen mode Exit fullscreen mode

Output:


Saravanan
Prem
<class 'str'>
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

The str represents the string data type.

What is a Data Type?

A data type tells Python what kind of value an object represents.

Examples:

no = 15
amount = 10
height = 1.72

name = "Saravanan"

print(type(no))       # int
print(type(amount))   # int
print(type(height))   # float
print(type(name))     # str
Enter fullscreen mode Exit fullscreen mode

In Python, data types are represented by classes. For example, str, int, and float are built-in classes.

Multi-line Strings

We can use triple quotes to create a string that contains multiple lines.

address = """7, Vivekanandar Street,
West Tambaram,
Chennai"""

print(address)

Enter fullscreen mode Exit fullscreen mode

Triple quotes are useful when we want to store multiple lines of text.

String Indexing

Indexing means accessing an individual character from a string using its position.

Important rule: Python indexing starts from zero.

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[1])
print(word[5])
print(word[-1])
Enter fullscreen mode Exit fullscreen mode
Output:

b
f
z
Enter fullscreen mode Exit fullscreen mode
  • Positive indexing starts from the left side with index 0.
  • Negative indexing starts from the right side.
word = 'abcdefghijklmnopqrstuvwxyz'

print(word[-1])  # z
print(word[-2])  # y
print(word[-3])  # x
Enter fullscreen mode Exit fullscreen mode

String Slicing

Slicing means extracting a portion of a string.

Syntax:

string[start:end]
Enter fullscreen mode Exit fullscreen mode

The starting index is included, but the ending index is excluded.

Example:


word = 'abcdefghijklmnopqrstuvwxyz'

print(word[1:5])
Enter fullscreen mode Exit fullscreen mode
Output:

bcde

Enter fullscreen mode Exit fullscreen mode

Here, Python starts at index 1 and stops before index 5.

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[20:])   # uvwxyz
print(word[:5])    # abcde
print(word[:])     # Entire string
Enter fullscreen mode Exit fullscreen mode

If the ending index is not provided, Python continues until the end.

If the starting index is not provided, Python starts from the beginning.

Step Operator in Slicing

We can also specify how many positions Python should skip while extracting characters.


Syntax:

string[start:end:step]
Enter fullscreen mode Exit fullscreen mode

Example:

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[2:10:2])
Enter fullscreen mode Exit fullscreen mode
Output:

cegi
Enter fullscreen mode Exit fullscreen mode

Python starts at index 2, stops before index 10, and moves two positions at a time.

Negative Step

A negative step moves from right to left.

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[-1:-10:-2])
Enter fullscreen mode Exit fullscreen mode

Output:

zxvtr
Enter fullscreen mode Exit fullscreen mode

Here, Python starts at the last character and moves backwards by two positions.

Useful String Operations

Finding String Length

The len() function returns the number of characters in a string.

name = 'amma'

print(len(name))
Enter fullscreen mode Exit fullscreen mode

Output:

4

Enter fullscreen mode Exit fullscreen mode

Checking the First Character


player = 'dhoni'

if player[0] == 'd':
    print("Starts with d")
Enter fullscreen mode Exit fullscreen mode

Checking the Last Character

player = 'dhoni'

if player[-1] == 'i':
    print("Ends with i")
Enter fullscreen mode Exit fullscreen mode

Finding the Middle Character

We can use the length of the string and integer division (//) to find the middle character of a string with an odd number of characters.

player = 'dhoni'

length = len(player)

print(player[length // 2])
Enter fullscreen mode Exit fullscreen mode
Output:

o

Enter fullscreen mode Exit fullscreen mode

Here:

  • len(player) returns 5.
  • 5 // 2 returns 2.
  • player[2] returns 'o'.

For an even-length string, there are two middle characters, so we need to decide which one we want.

String Reversing and Palindrome

We can reverse a string in Python using slicing.

Reversing a String

We can use [::-1] to reverse a string.

name = 'python'

print(name)
print(name[-1::-1])
print(name[::-1])
Enter fullscreen mode Exit fullscreen mode

Output:

python
nohtyp
nohtyp
Enter fullscreen mode Exit fullscreen mode

Understanding [::-1]:

  • Start: Not specified (starts from the end because the step is negative).
  • End: Not specified (continues to the beginning).
  • Step: -1 (moves backwards one character at a time).

What is a Palindrome?

A Palindrome is a word that reads the same forwards and backwards.

Example: amma

Original string: amma

Reversed string: amma

Both are equal, so it is a Palindrome.

name = 'amma'

print(name)
print(name[::-1])

if name == name[::-1]:
    print('Palindrome')
else:
    print('Not Palindrome')
Enter fullscreen mode Exit fullscreen mode
Output:

amma
amma
Palindrome
Enter fullscreen mode Exit fullscreen mode

Logic:

  • Store the original string.
  • Reverse the string using [::-1].
  • Compare the original string with the reversed string.
  • If both are equal, it is a Palindrome; otherwise, it is not.

Top comments (0)