Use Case
I am trying to use multiple list comprehensions to create a list that includes elements and satisfies the following criteria.
Step 1: All elements are integers between 1 and 30 (inclusive). All elements are not divisible by 2 or by 5. Print out the list and move to the next step.
Step 2: Convert all elements that are divisible by 3 to their opposites (e.g. 3 to -3) and print out the new list (step-2 list).
Step 3: Sum up the value of all positive elements in the step-2 list and print out the result
My Code
Step 1: Create a list expression for all integers between 1 and 30 that are not divisible by 2 or 5. Print out the list
list1 = [a for a in range(1, 31) if a%2 == 1 & a%5 == 1]
print(f"My initial list is: {list1}")
Step 2: Convert all integers divisible by 3 to their opposites
list2 = [-abs(b), c for b in list1 if b%3 == 0 else ]
print(f"My step-2 list is: {list2}")
This is where I am stuck. How do I print all integers from list1 where any integers divisible by 3 become negative (e.g., 3 becomes -3) and all remaining integers not divisible by 3 as positive? This is the logic that I am trying to achieve.
If I use the following code below, it returns a list of [-3, -21] which is correct. However, I don't see the remaining positive integers not divisible by 3 in the list.
list2 = [-abs(b) for b in list1 if b%3 == 0]
print(f"My step-2 list is: {list2}")
Step 3: Sum all positive values in the second list and print out the result
list3 = [sum(c) for c in list2 if c > 0]
print(f"The sum of positive elements in my step-2 list is: {list3}")
I believe the code for list3 should work once I fix the code for list2. Any help is appreciated. Thank you.