Write a program to append Magic Numbers from 1 to 100 in a Pandas series

A magic number is a number whose digits sum up to 1 or 10. In this tutorial, we'll create a Pandas series containing all magic numbers from 1 to 100. We'll explore two different approaches to solve this problem.

What are Magic Numbers?

Magic numbers are numbers where the sum of digits equals 1 or 10. For example:

  • 1 ? sum = 1 (magic number)

  • 10 ? sum = 1 + 0 = 1 (magic number)

  • 19 ? sum = 1 + 9 = 10 (magic number)

  • 28 ? sum = 2 + 8 = 10 (magic number)

Using Modulo Operation

The first approach uses the mathematical property that numbers with digit sum 1 give remainder 1 when divided by 9 ?

import pandas as pd

# Create list of numbers from 1 to 100
numbers = [i for i in range(1, 101)]

# Filter numbers where remainder is 1 when divided by 9
magic_numbers = list(filter(lambda i: i % 9 == 1, numbers))

# Create Pandas series
series = pd.Series(magic_numbers)
print("Magic number series:")
print(series)
Magic number series:
0      1
1     10
2     19
3     28
4     37
5     46
6     55
7     64
8     73
9     82
10    91
11   100
dtype: int64

Using Digit Sum Calculation

The second approach manually calculates the sum of digits for each number and checks if it equals 1 or 10 ?

import pandas as pd

magic_numbers = []

for i in range(1, 101):
    digit_sum = 0
    temp = i
    
    # Calculate sum of digits
    while temp > 0:
        remainder = temp % 10
        digit_sum = digit_sum + remainder
        temp = temp // 10
    
    # Check if digit sum is 1 or 10
    if digit_sum == 1 or digit_sum == 10:
        magic_numbers.append(i)

# Create Pandas series
series = pd.Series(magic_numbers)
print("Magic number series:")
print(series)
Magic number series:
0      1
1     10
2     19
3     28
4     37
5     46
6     55
7     64
8     73
9     82
10    91
11   100
dtype: int64

Comparison

Method Time Complexity Best For
Modulo Operation O(n) Faster execution
Digit Sum Calculation O(n × log n) Understanding the logic

Conclusion

Both methods successfully create a Pandas series of magic numbers from 1 to 100. The modulo approach is more efficient, while the digit sum method provides better understanding of the magic number concept.

Updated on: 2026-03-25T16:33:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements