How can I: Write a program to input 2 numbers, first and diff. The program will then create a one-dimensional array of 16 elements in an arithmetic sequence which is printed out. For example, if first is 21 and diff = 5, the arithmetic sequence will be: 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
first = input("First: ") diff = input("Diff: ") for i in range(16): n = first + i * diff print n,
There's actually a formula that will do this with the range function on a single line: range(x, ((z * y) + x), y) x = first number y = difference z = length of array. This should not only work for any x or y but for any z as well.
Well actually, I just realized mine won't work if y = 0, unlike dmancine's. It would have to be: if y == 0: [x, ] * z else: range(x, ((z * y) + x), y)
I talk a lot about style. But, just as a style point, I tend to make my for loops just loop from 0 to some number, with an increment of 1. If I need to calculate something fancier for each iteration I write an explicit expression inside the loop, using the loop variable. That makes the for loop a little easier to follow, and makes the computation more explicit. Of course there are some exceptions. True, it's not the most concise way to do it, but I find it usually a bit clearer. But, of course, a good one-liner is always pretty cool.
Join our real-time social learning platform and learn together with your friends!