1
Data n and two positive integers i and j different from 0, print in ascending order the first natural n s which are multiples of i or of j and or both.
Example: For n = 6 , i = 2 and j = 3 the output should be : 0,2,3,4,6,8.
n = int(input("Digite n: "))
i = int(input("Digite i: "))
j = int(input("Digite j: "))
lista = []
for k in range(i,i+1):
for l in range(0,n):
print("{}*{} = {}".format(k,l,k*l))
lista.append(k*l)
for k in range(j,j+1):
for l in range(0,n):
print("{}*{} = {}".format(k,l,k*l))
lista.append(k*l)
print(lista)
The above program with n =6, i =2 and j=3 is giving as output:
[0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15]
For the output to be correct, I would need to order the above list in ascending order, clearing the duplicate values:
[0,2,3,4,6,8,9,10,12,15]
and then take the first 6 values, getting: [0,2,3,4,6,8], which is the expected output.
Any idea how to improve/correct the above program?
It looks great! Thank you!
– Ed S
your solution is excellent but only at the level of learning, how could I finish the solution the way I started, ie ordering [0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15] and excluding the repeated? It is possible?
– Ed S
@Eds, to exclude everyone from the element number, in your case it’s just
sorted(set(lista))[:n]
, https://ideone.com/HpqHGu, https://ideone.com/DTJnr7– Miguel
I tried: list= [0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15] and it didn’t work: list.Sort(key=int) came out [0, 2, 4, 6, 8, 10, 0, 3, 6, 9, 12, 15], ie not ordered... What happened?
– Ed S
@Eds, I put my best in the comment above,
key=int
was the problem, that is not doing anything– Miguel
Thank you very much! Although my algorithm is totally inefficient, I needed to understand how to fear it! Now yes! Do you suggest some list of exercises for me to train?
– Ed S
@Eds that doesn’t lack: https://www.google.pt/search?q=python+exercises&oq=python+exer&aqs=chrome.2.69i57j69i60j0l4.3141j0j4&sourceid=chrome&ie=UTF-8 , https://www.google.pt/search?ei=0uq0u0WsaiDYy5UY_5ggAE&q=exerc%C3%Adcios+de+python&oq=exerc%C3%Adc+de+python&gs_l=Psy-ab.3.. 0l2j0i22i30k1l8.18798.24184.0.24916.20.15.0.5.0.132.1079.10j2.12.0...... 0...1c.1.64.Psy-ab.. 3.17.1088...35i39k1j0i131k1j0i67k1.0.Oa7if72cazo
– Miguel