well I am learning on Udemy and I couldn't figure out why the result of this lines of code:
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = [num + 3 for num in numbers if num % 2 == 0]
print(result)
are [5, 11, 37] and not [4, 4, 6, 8, 16, 24, 58]?
thank you for helping.
if num % 2 == 0
means that you only want to execute the code if num is even.
That way only the 2,8 and 34 are added to the list and incremented by 3.
The answer you expect (only the odd numbers incremented by 3) is when the last bit is like this:
if num % 2 != 0
for num in numbers iterates over elements of the list.
if num % 2 == 0 restricts to even numbers.
So you end up by adding 3 to : 2, 8 and 34 which gives the expected result.
A more explicit loop would be :
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = []
for num in numbers:
if num%2 == 0: # if it's even
result.append(num+3)
print(result)
Related
I have list a = [1,2,3,6,8,12,13,18,33,23] and list b=[] that is empty. I need each value in list a compare with all the values in the list b by taking the difference of the new value from list a with all the contents of the list b. If the difference is grater than to the value of the threshold, it must insert to list b rather than skip to the next value in a, how can do that?
a =[1,2,3,6,8,12,13,18,33,23]
b=[]
b.append(a[0])
for index in range(len(a)):
for i in range(len(b)):
x = a[index] - b[i]
if x > 1:
b.append(a[index])
print("\nOutput list is")
for v in range(len(b)):
print(b[v])
The desired output is:
output = [1,6,8,12,18,33,23]
To further clarify, in first time the list b have the first item from list a. I need to check if the a[0]-b[0]>1, then insert the value of a[0] in b list, and next if a[1] - b[0]>1 then insert the a[1] in b list , and if [[a[2] -b[0] >1] and [a[2]-b[1] > 1]] then insert a[2] in b list and so on
Here is the probable solution to the stated problem though the output is not matching with your desired outcome. But sharing on the basis of how I understood the problem.
a = [1, 2, 3, 6, 8, 12, 13, 18, 33, 23]
b = []
b.append(a[0])
threshold = 1 # Set Threshold value
for index in range(len(a)):
difference = 0
for i in range(len(b)):
difference = abs(a[index] - b[i])
if difference > threshold:
continue # Keep comparing other values in list b
else:
break # No need for further comparison
if difference > threshold:
b.append(a[index])
print("\nOutput list is")
print(b)
Output is:
Output list is
[1, 3, 6, 8, 12, 18, 33]
Also, I notice that after swapping the last two elements (33 <-> 23 ) of the list a as below:
a = [1, 2, 3, 6, 8, 12, 13, 18, 23, 33]
and running the same code. the output was near to your desired output:
Output list is
[1, 3, 6, 8, 12, 18, 23, 33]
This problem is very interesting now as I put myself into more investigation. And I found it a very interesting. Let me explain. First consider the list a as a list of integer numbers starting from 1 to N. For example:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
and set the threshold to 1
threshold = 1 # Set Threshold value
Now, run the programme with threshold = 1 and you will get the output:
Output list is
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
and if you rerun with threshold = 2, you will get the following output:
threshold = 2
Output list is
[1, 4, 7, 10, 13, 16, 19]
Basically, this programme is basically generating a hopping series of integer numbers where hopping is set to the threshold value.
Interesting!!! Isn't it???
I expected this print statement to print each element lesser than 5 one at a time but got the address returned instead.
Any idea what to do if I want to print each element lesser than 5 one at a time within 1 line of code
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print(num for num in a if num < 5)
[out]:
<generator object <genexpr> at 0x7efd6ce74cf0>
# This is the correct solution if I want to print it in a list
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print([i for i in a if i<5])
[out]:
[1,1,2,3]
I am new to python but as far as I know this is the best way to do what you are asking.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print("\n".join([str(num) for num in a if num < 5]))
this is just the same code as the one you use above but I have also added the .join() method to separate out each element of the list and print it on a separate line. I used the "\n" to print everything on separate lines though if this is not what you wanted you could simply change that to an empty string: "" or a space: " ".
not sure if this is exactly what you are asking but I hoped it helped.
Doing the for loop inside [] brackets is a List Comprehension
You can instead re-factor your code to for loop through each item in the list then print if one is less than 5 doing the following:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for x in a: print(x) if x < 5 else 0
The output for the following code is:
1
1
2
3
The above code is the same as doing:
for x in a:
if x < 5:
print(x)
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
list(map(print, (num for num in a if num < 5)))
I have a list of numbers [7, 9, 11, 13, 15, 20, 23] and I need to create a list of Prime numbers from given list.
I have written below code but this results 9 & 15 as prime too. I am not getting what I am missing here.
a = [7, 9, 11, 13, 15, 20, 23]
x = []
for i in range (0, len(a)):
num = a[i]
for m in range (2,num):
if (num % m)==0:
break
else:
print('This is prime', num)
x.insert(i, num)
break
I Expect the output list x as [7, 11, 13, 23].
If num % m != 0 doesn't mean that num is prime, it must be true for all possible m values (which can be reduced by going up to num // 2, and can even be reduced to go up to just sqrt(num)), for that, you can use a for ... else block (the else block will execute only when the for exits normally, without a break, which only happens with prime numbers):
a = [7, 9, 11, 13, 15, 20, 23]
x = []
for num in a: # iterate with the value when you don't need the index
for m in range(2, (num // 2) + 1):
if num % m == 0:
break
else:
print('This is prime', num)
x.append(num) # use `append` to insert at the tail of the list
print(x)
Output:
This is prime 7
This is prime 11
This is prime 13
This is prime 23
[7, 11, 13, 23]
I am trying to get possible numbers from 1 to n, given 4 numbers. by adding or subbtracting 2 or more of the 4 numbers.
e.g. it goes into loop for numlist(1,2,3,16). Below is the code:
def numlist(a,b,c,d):
#user input of 4 numbers a,b,c,d
# assigning variables value of -1. This will be used to provide -1 or +1 or 0
p=-1
q=-1
r=-1
s=-1
count=0
myarray=[]
mysum=a+b+c+d #sum of given 4 numbers
for x in range(mysum):
while count<mysum:
if p<=1:
if q<=1:
if r <=1:
if s<=1:
n1=p*a+q*b+r*c+s*d #number to be generated by adding/subtracting
s=s+1
#print(n1)
if n1>0 and (n1 in myarray)==False:
#print(n1)
myarray.append(n1) #add to myarray if number is positive and not already present
myarray.sort() #sort myarray
count=count+1
if count==mysum:
break
else:
s=-1
r=r+1
else:
r=-1
q=q+1
else:
q=-1
p=p+1
else:
p=-1
print(len(myarray),'total')
print(myarray)
numlist(1,3,4,14)
outputs
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
but if numlist(1,3,4,19)
it keeps running without ending in output of array. only shows total.
where am I going wrong ?
I think you should rethink your algorithm. Consider this:
from itertools import combinations
def numlist(lst):
lst = lst + [-i for i in lst]
result = set()
for i in range(2, 5):
result.update(sum(k) for k in combinations(lst, i))
return sorted(i for i in result if i > 0)
numlist([1, 3, 4, 19])
# [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
I did a little patch-up work, and found the high-level problem with your logic.
Your code goes into an infinite loop when the current value of count cannot be formed with the input values. Your logic fails to increment count until it finds a way to create that value. You spin through one combination after another of coefficients.
for x in range(mysum):
print ("top of loop; x =", x)
while count<mysum:
print("count", count, "\tmysum", mysum, "\tcoeffs", p, q, r, s)
if p<=1:
...
I'm doing some practice problems and one program is asking me to change numbers in the list to 99, only if the number previously is even. I'm running into the trouble that when I change the number to 99, when it moves on the the next number, it checks to see if 99 is even, which I don't want, I want it to check the original value I had there, not what I changed it to .
d = [9, 8, 2, 15, 6, 33, 10, 4]
i = 1
while i < len(d) - 1 :
if d[i-1]%2 == 0 :
d[i] = 99
i = i + 1
print d
returns [9, 8, 99, 15, 6, 99, 10, 4]
I want it to return [9,8,99,99,6,99,10,99]
How would I add 99 into the original list without changing its original value if that makes any sense? List methods like pop or insert can not be used.
Try this.
d = [9, 8, 2, 15, 6, 33, 10, 4]
for i in reversed(xrange(1, len(d))):
d[i] = 99 if d[i - 1] % 2 == 0 else d[i]
I would advice to iterate descending:
d = [9, 8, 2, 15, 6, 33, 10, 4]
for x in xrange(len(d)-1, 0, -1):
if d[x - 1] % 2 == 0:
d[x] = 99
print d
In this case next iteration will operate not changed values.
Or You can create new list
or You can add variable for previous value and use it in if statement
d = [9, 8, 2, 15, 6, 33, 10, 4]
previous = d[0]
for i, x in enumerate(d[1:]):
if previous % 2 == 0 :
previous = d[i]
d[i] = 99
else:
previous = d[i]
print d
search the list backwards
see last and before last value (n-1, n-2)
change the last value if needed
move to previous values (n-2,n-3)
repeat until whole list is updated
Try this:
d = [9, 8, 2, 15, 6, 33, 10, 4]
prev=d[0]
for i,j in enumerate(d):
if prev%2==0:
prev=j
d[i]=99
else:
prev=j
print d