Posts: 22
Threads: 10
Joined: Oct 2019
I am trying to code a list of 10 items whose values come from the equation y=a*(bx) and complete the rest of it with 0. e.g:
a=1
b=5
list=[]
x=0
while (x<=b):
x=x+1
y=a*(bx)
break
list.append(y)
list=[1,2,3,4,5,6,0,0,0,0,0]
Posts: 441
Threads: 1
Joined: Sep 2018
Oct112019, 03:00 AM
(This post was last modified: Oct112019, 03:00 AM by stullis.)
With your current code, you only need to remove "break" and fix the indenting to make it work. Then, we can use list.extend() to add the zeroes. On a related note, do not use reserved or implemented terms such as "list" as variable names. That has unintended consequences.
a=1
b=5
list_=[]
x=0
while (x<=b):
x=x+1
y=a*(bx)
list_.append(y)
list_.extend([0] * b)
That said, we can do better. As a general practice, avoid while loops. They have a tendency to become infinite loops when there's a bug. Instead, use for loops. A for loop is guaranteed to stop because it has a limited iteration. We can also implement x without a counter, cutting two lines out of the code, by implementing a for loop.
a=1
b=5
list_=[]
for x in range(1, 5):
y=a*(bx)
list_.append(y)
list_.extend([0] * b)
But we can do even better! This is a more advanced technique. We have list comprehensions at our disposal. They're more efficient and sleek.
a=1
b=5
list_=[a * b  x for x in range(1,5)]
list_.extend([0] * b)
Posts: 22
Threads: 10
Joined: Oct 2019
I understand but the problem is that list must always have 10 elements and "a" and "b" will be input by the user.
Posts: 65
Threads: 16
Joined: Aug 2019
Oct112019, 08:45 AM
(This post was last modified: Oct112019, 08:56 AM by adt.)
(Oct112019, 03:54 AM)doug2019 Wrote: the problem is that list must always have 10 elements and "a" and "b" will be input by the user
Will this meet your needs?
a = 1
b = 5
mlist= [0]*(a  1) + [a * (b  x) for x in range(a, b+1)] + [0]*(10  b)
print(mlist)
Output:
[4, 3, 2, 1, 0, 0, 0, 0, 0, 0]
If you need to have the calculated values in ascending order, you could try the following:
a = 1
b = 5
mlist= [0]*(a  1) + [a * (b  x) for x in range(b, a1, 1)] + [0]*(10  b)
print(mlist)
Output:
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
Posts: 65
Threads: 16
Joined: Aug 2019
If values of a & b are not restricted to within 10 (while their difference is so), and padding of zero values is only to be on the right side, you could try the following:
a = 12
b = 18
mlist= [a * (b  x) for x in range(b, a1, 1)] + [0]*(10  (b  a + 1))
print(mlist)
Output:
[0, 12, 24, 36, 48, 60, 72, 0, 0, 0]
Posts: 838
Threads: 1
Joined: May 2019
For the more general answer, how about
a = int(input("Enter a: "))
b = int(input("Enter b: "))
answer = [a * b  x for x in range(1,b+1)]
answer.extend([0] * (10b))
print(answer) Output: Enter a: 3
Enter b: 6
[17, 16, 15, 14, 13, 12, 0, 0, 0, 0]
That works for any positive value of b < 10
Posts: 22
Threads: 10
Joined: Oct 2019
