Given two integer variables, limit and diff, write a Python program to create a list that is centered on zero, using limit, which specifies limit of the list and diff that specifies the common difference between integers.
Examples:
Input : limit = 1, diff = 0.5 Output : [-1, -0.5, 0.0, 0.5, 1] Input : limit = 25, diff = 5 Output : [-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25]
Approach #1: Naive Approach
This is a naive approach to the above problem. First, create an empty list 'lst', and then we use a while loop to append the next integer with a difference equal to 'diff'.
# Python3 program to Convert a
# list to dictionary
def create(limit, diff):
lst = [-limit]
while lst[-1] < limit:
lst.append(lst[-1] + diff)
lst[-1] = limit
return lst
# Driver code
limit = 1
diff = 0.5
print(create(limit, diff))
[-1, -0.5, 0.0, 0.5, 1]
Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list
Approach #2: Using Python Numpy
Using Numpy module makes the solution a lot easier. In this method, we use np.arange which return evenly spaced values within a given interval 'diff'.
# Python3 program to Convert a
# list to dictionary
import numpy as np
def create(limit, diff):
lst = np.arange(diff, limit, diff)
if (lst[-1] != limit):
lst = np.r_[lst, limit]
return np.r_[-lst[::-1], 0, lst].tolist()
# Driver code
limit = 1
diff = 0.5
print(create(limit, diff))
[-1.0, -0.5, 0.0, 0.5, 1.0]
Approach #3: list comprehension
# Python3 program to create a list centered on zero
def create(limit, diff):
length = int(((limit/diff)*2)+1)
list = [-limit+i*diff for i in range(length)]
return list
# Driver code
limit = 1
diff = 0.5
print(create(limit, diff))
[-1.0, -0.5, 0.0, 0.5, 1.0]
Approach #4: Using recursion
This approach uses recursion to generate the list of integers. It has a base case when limit is 0, and in that case it returns an list with 0. Otherwise, it generates the list by appending -limit to the result of a recursive call to the function with limit set to limit-diff, and then appending limit to the result.
# This function generates a list that is centered on zero, using limit and diff as inputs.
# limit specifies the limit of the list, and diff specifies the common difference between the integers in the list.
# The list is generated using recursion.
def create(limit, diff):
# Base case: if limit is 0, return a list with just 0
if limit == 0:
return [0]
# Recursive case: generate the list by appending -limit, then calling the function with limit-diff, then appending limit
else:
return [-limit] + create(limit-diff, diff) + [limit]
# Test the function with limit = 25 and diff = 5
limit = 25
diff = 5
print(create(limit, diff))
#This code is contributed by Edula Vinay Kumar Reddy
Output
[-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25]
Time complexity: O(n), where n is the length of the list
Auxiliary Space: O(n)