Reputation: 400
I am making a simple program where there is a simple for
loop. There are two inputs in my program, n and k. k is used to skip numbers over iteration and n is the number of numbers that is to be printed.
This is my code:
nk = input().split()
n = int(nk[0])
k = int(nk[1])
store_1 = []
for x in range(1,n+n,k):
store_1.append(x)
print(store_1)
The only pairs that seems to work is when k is set to 2 and the starting of the range remains 1. But when k is set to any other number and the starting of the range is above 1, it doesn't provide the correct output. For example:
#6 and 3, starting range 1
[1,4,7,10]
#Correct output: [1,4,7,10,13,16]
#4 and 2, starting range 2
[2,4,6]
#Correct output: [2,4,6,8]
#4 and 2, starting range 1
[1,3,5,7]
Only this sort of pair and starting range provides the correct output.
How can I fix my Code and get the right output. Note: I can set the starting of the range to any number, Ex: 2,3,4 etc.
EDIT: More samples:
#5 and 3, starting range 3
Correct output: [3,6,9,12,15]
#7 and 7, starting range 1
Correct output: [1, 8, 15, 22, 29, 36, 43]
#6 and 8, starting range 5
Correct output: [5,13,21,29,37,45]
Upvotes: 2
Views: 244
Reputation: 1982
A smart approach would be:
n, k, s = list(map(int, input().split())) # s is the start_range
store_1 = list(range(s,s+(n*k),k))
print(store_1)
Sample Input:
5 3 3
Output:
[3,6,9,12,15]
Upvotes: 2
Reputation: 26039
Increment value by k
starting from start value in a loop that iterates n
times:
n, k = list(map(int, input().split()))
store_1, x = [], 1 # x is the starting range.
for _ in range(n):
store_1.append(x)
x += k
print(store_1)
Note that x
is the starting value. You can either set it within your code or read from user.
Upvotes: 2
Reputation: 477
Another solution derived from yours, with usage of while loop:
nk = input().split() #Example of entry 2 6
n = int(nk[0])
k = int(nk[1])
store1=[]
stored_num = 1
count_of_printed_nums = 0
while(count_of_printed_nums<n):
store1.append(stored_num)
stored_num+=k
count_of_printed_nums+=1
print(store1)
Upvotes: 1