As title says, I'm new to Python (started using Python3 about 4 days ago). I'm having a hard time understanding why these two seemingly equivalent pieces of code give a different result.
I've been recommended to try my hand at some of the problems on projecteuler, to me these two look like they should output the same number. I assume it's something small that i'm not noticing. Thanks in advance.
My code outputs: 266333 Other code outputs: 233168
#my code
sum3 = sum({*range(3, 1000, 3)})
sum5 = sum({*range(5, 1000, 5)})
print(sum3 sum5)
#someone else's solution
print(sum({*range(3, 1000, 3)} | {*range(5, 1000, 5)}))
CodePudding user response:
The second approach will eliminate duplicates while merging, but the first one will not. Hence the difference in the sum.
CodePudding user response:
Lets thake 15 as an example. If you use the first approach 15(3*5) will appear both in the summation of the first array and the second array. In the second approach 15 will appear just one time! enche the difference in the sum.
CodePudding user response:
In your code part you get a sum of two different sets and then you summarize them. sum3 - sum of first set, sum5 - sum of second set and then you have a print of sum this two sums.
In someone else's solution at first you got two sets and then they are merged and then you have a sum of set of two merged sets.
CodePudding user response:
range(3, 1000, 3) give you all multiple of 3, and range(5, 1000, 5) the multiple of 5, I hope that is clear at least, and notice that a number can be both like 15.
so when you sum them separately you get a bigger number
sum3 = sum({*range(3, 1000, 3)}) # 15 something1
sum5 = sum({*range(5, 1000, 5)}) # 15 something2
sum3 sum5 == 15 15 something1 something2
in the second one, you are combining the two set of numbers, so
this {*range(3, 1000, 3)} | {*range(5, 1000, 5)}
will only contain one copy of 15 and any other multiple of both numbers
sum({*range(3, 1000, 3)} | {*range(5, 1000, 5)}) == 15 somthing_else
CodePudding user response:
As @mkrieger1 points out, the other answer has the |
operator in it, which is the logical OR operator.
If we look at the problem you want to solve, it says 3 OR 5, so you want to eliminate the common multiples (like 15), which is why the other person included it.