Python range with Uneven gap

Viewed 2078

Today I had a python exam where following question was asked:

Given the following code extract, Complete the code so the output is: 10 7 5.

nums = list (range (?,?,?))

print(nums)

How is it possible to get such output in python using range function?

5 Answers

not sure if this answer the question, provided we can fill in any syntax to the ? as long it produce the result.

  • 1st ? = 10
  • 2nd ? = 4
  • 3rd ? = -3))+(([5]
# nums = list(range(   ?  ,  ?  ,      ?       ))
nums   = list(range(  10  ,  4  ,  -3))+(([5]  ))
print(nums)
# nums = [10,7,5]

There is no sane way to get the result required. The meat of the problem is that the built in range is strict about its inputs and its definition. It only accepts integers. The only way to get the required answer is to override one of the built ins. But you could override any of them.

range = lambda x, y, z: [10, 7, 5]
list = lambda x: [10, 7, 5]
print = lambda x: sys.stdout.write([10, 7, 5])

On a scale of C# minor what's your favorite color? Mine's triangle.

I don't know how that works! But you can get that output with the advanced range function in NumPy, since it allows the use of floats:

import numpy as np

nums = np.arange(10, 3, -2.6)
print(np.rint(nums))

Out: [10. 7. 5.]

in the list we get 10, 7.4 and 4.8, and the rint function rounds them up to 10, 7 and 5. Maybe there is a way to use range with floats as well?

I know this isn't what the OP wants but maybe you could try using list comprehensions. You could use this trick. For example,

num = list(x for x in range(11,3,-1) if x==10 or x==7 or x==5)
print(num)

This outputs [10,7,5].

nums = list(range(10, 2, -3)[:2]) + ([5] )    
print(nums)
[10, 7, 5]
  • 10
  • 2
  • -3)[:2]) + ([5]
Related