In this lesson, I propose an exercise that still uses the method Python insert.

Python Insert – First exercise

Insert 20 random numbers from 50 to 150 at the top of the list, with the method Python insert. Display the elements with another cycle. Next, modify each element, subtracting the sum of its digits from each number. Finally, display the modified list with another cycle.

That is, if for example I have the following list: random [50,55,80,90….]

So I calculate the sum of the digits for each number:

50: the sum of the digits is 5;

55: the sum of the digits is 10;

80: the sum of the digits is 8;

90: the sum of the digits is 9;

etc…

So the new list at the end of the modification will contain the following elements: random [45,45,72,81,….].

Solution to the exercise on Python insert method

First, I populate the list with random numbers included in the range [50.150] using the Python insert method.

Then I see the elements entered and find the sum of the digits of each number. To do this, ultimately, I have to create an algorithm that, one by one, is able to find the digits of each number and add them to a sum variable.

One procedure could be to divide the number by 10 and then add the remainders.

Let’s take some examples:

sum = 0

50 ÷ 10 = 5 remainder 0, sum = 0 + 0 = 0

5-10 = 0 remainder 5, sum = 0 + 5 = 5

So the total sum of the digits is 5.

sum = 0

55 ÷ 10 = 5 remainder 5, sum = 0 + 5 = 5

5-10 = 0 remainder 5, sum = 5 + 5 = 10

The total sum of the digits is 10.

sum = 0

80 ÷ 10 = 8 remainder 0, sum = 0 + 0 = 0

8-10 = 0 remainder 8, sum = 0 + 8 = 8

etc…

As you can see, the sum variable must be initialized to zero for each number to be evaluated.

Each total must then be subtracted from the initial number, of which a temporary copy must be made, as at the end of the operation its value will be changed.

Here is therefore a possible implementation of the proposed algorithm that uses the Python insert method:


from random import randint

n = 2
random_numbers = []

for i in range(n):
    number= randint(100,1000)
    random_numbers.insert(0,number)

for i in range(n):
    print('Item in position: ', i, 'is ',  random_numbers[i])

for i in range(n):
    s = 0
    temp = random_numbers[i]    #I make a copy of the number
    while random_numbers[i]>0:
        s += random_numbers[i] % 10
        random_numbers[i] //= 10    
    random_numbers[i] = temp-s

for i in range(n):
    print('Item in position: ', i, 'is ', random_numbers[i])

Try it in the editor:

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot