Thursday, July 20, 2017

Python - Problem 1

Question:
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).The numbers obtained should be printed in a comma-separated sequence on a single line.Below is the solution code with the explanation.

Code:
l=[]

#starting with loop which will iterate from i1 to i2.Here we are using the Range function available in Python.
for i in range(2000,3201):
    #always becareful with the indent spaces.now we are in the loop.
    ##variable 'i' will be iterated every time and will contain value from 2000 to 3200for every iteration.
    if(i%7==0) and (i%5 != 0):
        #we are appending the satisifed value to the list 'l', but before appending we are converting the value to str for the next usage.
        l.append(str(i))
    #Here we are printing the list.join is used for combining the str values in a list with the specified seperator.
    #in our case the seperator is ',' 
print(','.join(l))
print("total numbers:",len(l))

Output:
     The above code is having hard coded values with a range from 2000 to 3200.Below is the output of the above code.
output of python code
Let us make some changes to above code so that it will accept different inputs and also with a check that the lower limit value does not exceed higher limit value.
Below is the modified code,

Modified Code:


import time
i1=int(input())
i2=int(input())

start_time = time.time()
l=[]

#starting with loop which will iterate from i1 to i2.Here we are using the Range function available in Python.
if(i1<i2):
    for i in range(i1 ,i2 ):

        #always be careful with the indent spaces.now we are in the loop.
        #variable 'i' will be iterated every time and will contain a value from i1 to i2 for every iteration.

        if(i%7==0) and (i%5 != 0):
            #we are appending the satisifed value to the list 'l', but before appending we are converting the value to str for the next usage.
            l.append(str(i))

    #Here we are printing the list.join is used for combining the str values in a list with the specified seperator.
    #in our case the seperator is ',' 
    print(','.join(l))
    print("total numbers:",len(l))

else:
    print("value 1 should be less than value 2")
print("---seconds---", (time.time() - start_time))

Output:
       The above code will produce the following output.
Python modified code problem 1 output