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

PythonPandasServer Side ProgrammingProgramming

The result for appending magic numbers from 1 to 100 is,

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

To solve this, we will follow the below approaches −

Solution 1

  • Create list comprehension to append 1 to 100 values to list ls.

ls = [i for i in range(1,101)]
  • Apply lambda filter function to store the values divisible by 9 results is 1.

l = list(filter(lambda i:i%9==1,ls))
  • Create a series from the list l.

pd.Series(l)

Example

Let’s see the below code to get a better understanding,

import pandas as pd
ls = [i for i in range(1,101)]
l = list(filter(lambda i:i%9==1,ls))
print("magic number series:\n",pd.Series(l))

Output

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

Solution 2

  • Create an empty list

  • Set for loop range from 1 to 101 and set digit_sum as 0

for i in range(1,101):
   digit_sum = 0
  • Assign i values to temporary value so that i value can’t be changed.

  • Set while loop condition as temp>0

  • Calculate remainder and digit_sum as follows,

while(temp>0):
   rem = temp % 10
   digit_sum = digit_sum + rem
   temp = temp // 10
  • Finally set if condition to check the digit_sum value either 1 or 10. If it is true then append the values to the list

if(digit_sum==1 or digit_sum==10):
   l.append(i)
  • Finally, generate a series from the list.

Example

Let’s check the following code to get a better understanding −

import pandas as pd
l = []
for i in range(1,101):
   digit_sum = 0
   temp = i
   while(temp>0):
      rem = temp % 10
      digit_sum = digit_sum + rem
      temp = temp // 10
   if(digit_sum==1 or digit_sum==10):
      l.append(i)
print("magic number series:\n",pd.Series(l))

Output

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
raja
Published on 12-Feb-2021 11:03:27
Advertisements