Python - Make avarage variables without 0 - python

A = 0
B = 10
C = 20
N = [(A, B, C)]
Avarage = (A + B + C) / sum(1 for i in N if i != 0)
Avarage = 30??
Need Avarage = 15.
Any idea?

You need to remove ( and ) from your list N
a = 0
b = 10
c = 20
n = [a, b, c]
list_avg = sum(n) / sum(1 for i in n if i != 0)
Output:
>>> list_avg
15

N is list containing tupple. So sum(1 for i in N if i != 0) returns 1 as there is only 1 element (a tupple) in list N.
Try:
A = 0
B = 10
C = 20
N = [(A, B, C)]
Avarage = (A + B + C) / sum(1 for i in N[0] if i != 0)
print Avarage
15
OR:
A = 0
B = 10
C = 20
N = [A, B, C]
Avarage = (A + B + C) / sum(1 for i in N if i != 0)
print Avarage
15

As stated by depperm, N is a list of one tuple, so you have in your sum only one element (which is different than 0 because it is a tuple and not an int). Otherwise you can use numpy
import numpy as np
average = np.mean([A, B, C])

Make a new list of values without the zeros, then average that:
non_zero = [v for v in (A, B, C) if v != 0]
avg = sum(non_zero)/len(non_zero)

Related

projecteuler problem 8 - unsure on what is wrong with my code

A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c =
1000. Find the product abc.
above is the question. when i run my code it works and runs how i expect it to, but the programme always finishes without finding an answer. any advice on how to improve my code would be appreciated.
for k in range (1,1000):
c = 1000 - k
for i in range (1,c):
b = c - i
c_sqr = c ** 2
b_sqr = b ** 2
a = c - b
a_sqr = a ** 2
if a_sqr + b_sqr == c_sqr:
if a + b + c == 1000:
product = a * b * c
print(f"{product} is the answer")
exit()
else:
print("Pythagorean triplet!")
else:
josephmama = 11
print("not a pythagorean triplet")
In your code c < 1000 and a + b == c are invariants. The sum (a + b + c) == 2 * c requires that the longest side(hypotenuse) of the right triangle to be as long as the sum of the other sides, and there's no such numbers that satisfy it and so the if body never executes.
for a in range(1, 1000):
for b in range(1, 1000):
c = 1000 - (a + b)
if (a ** 2 + b ** 2 == c ** 2):
print(a * b * c)
exit()
a is not always equal to c - b
by deriving b from c and a from c and b you are unnecessarily limiting the options of what b and a could be. Just loop through all combinations of a, b and c, add the constrains you have and you'll eventually get your triplet.
for a in range(1, 1000):
for b in range(1, 1000):
for c in range(1, 1000):
if a+b+c == 1000:
if a**2+b**2 == c**2:
if a < b:
if b < c:
print(f"My Triplet: a: {a}, b: {b}, c:{c}")

Solving problems in Python

I currently have the following, both of which must hold true:
A B C D + A E F = E F G H and
I C J * E = A B C D
Each letter represents a unique digit from 0 to 9 and both equations must hold true.
I need to write a Python solution which outputs the correct answer, here is my code:
import numpy as np
def solve():
for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
for e in range(0,10):
for f in range(0,10):
for g in range(0,10):
for h in range(0,10):
for i in range(0,10):
for j in range(0,10):
if len(set([a, b, c, d, e, f, g, h, i, j])) == 10:
icj = 100*i + 10*c + j
e = e
abcd = 1000*a + 100*b + 10*c + d
aef = 100*a + 10*e + f
efgh = 1000*e + 100*f + 10*g + h
if icj * e == abcd and abcd + aef == efgh:
print(icj, e, abcd, aef, efgh)
print(solve())
However, when I run this, not only does it take a while to run, it outputs "None". Any ideas as to where I am going wrong?
You should try for x in range(0, 10) instead of for x in range(0,9) because you were looping from 0 to 8
If you want to loop in a more efficient way, you can use permutations:
from itertools import permutations
for a, b, c, d, e, f, g, h, i, j in permutations(range(0, 10), 10):
print(a, b, c, d, e, f, g, h, i, j)
Result :
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 9 8
...
9 8 7 6 5 4 3 2 0 1
9 8 7 6 5 4 3 2 1 0
Here is the final code :
import numpy as np
from itertools import permutations
def solve():
for a, b, c, d, e, f, g, h, i, j in permutations(range(0, 10), 10):
icj = 100*i + 10*c + j
e = e
abcd = 1000*a + 100*b + 10*c + d
aef = 100*a + 10*e + f
efgh = 1000*e + 100*f + 10*g + h
if icj * e == abcd and abcd + aef == efgh:
print(icj, e, abcd, aef, efgh)
print(a, b, c, d, e, f, g, h, i, j)
solve()
Output :
934 7 6538 672 7210
6 5 3 8 7 2 1 0 9 4
Apart from the typos, if you only test in the very inner loop whether all 10 digits are different, this inner loop is executed 1010 = 10,000,000,000 times. If you test at every pass, you "only" need 10! = 3,628,800 passes to this inner loop.
You still can do better changing the order of variables, so the equation abc * d == hibj can be tested without needing the other 3 variables, and only go deeper when it holds. For these 7 digits, you enter 604,800 times in that loop, and only 45 times you need to go deeper to reach the most inner loop only 270 times.
def solve():
for a in range(0, 10):
for b in range(0, 10):
if a != b:
for c in range(0, 10):
if not c in [a, b]:
for d in range(0, 10):
if not d in [a, b, c]:
for h in range(0, 10):
if not h in [a, b, c, d]:
for i in range(0, 10):
if not i in [a, b, c, d, h]:
for j in range(0, 10):
if not j in [a, b, c, d, h, i]:
abc = 100 * a + 10 * b + c
hibj = 1000 * h + 100 * i + 10 * b + j
if abc * d == hibj:
print(abc, '*', d, '=', hibj)
for e in range(0, 10):
if not e in [a, b, c, d, h, i, j]:
for f in range(0, 10):
if not f in [a, b, c, d, h, i, j, e]:
for g in range(0, 10):
if not g in [a, b, c, d, h, i, j, e, f]:
hde = 100 * h + 10 * d + e
defg = 1000 * d + 100 * e + 10 * f + g
if hibj + hde == defg:
print(abc, d, hibj, hde, defg)
solve()
print('done')
Although it now runs fast enough, still more specific optimizations can be thought of:
Change the order to a,b,c and h,i,j then calculate whether hibj is a multiple of abc. Only in case it is, this defines d which should be between 0 and 9, and different from the rest.
Or, the reverse: generate a,b,c,d and then try all the multiples first whether they fit b and then whether the corresponding h,i,j are different from each other and different from a,b,c,d.
h should be smaller than a, otherwise d will be larger than 9. This makes a at least 1.
Usually in this kind of problems, the first digit of every number is supposed to be non-zero, which can further reduce the number of checks.
An alternative approach, is to use an SMT/SAT solver such as Z3. With such a solver, all the conditions are formulated, and via all kind of heuristics a solution is searched for. Example codes: here and here.
This is how the code could look like:
from z3 import Int, And, Or, Distinct, Solver, sat
D = [Int(f'{c}') for c in "abcdefghij"]
a, b, c, d, e, f, g, h, i, j = D
vals_0_to_9 = [And(Di >= 0, Di <= 9) for Di in D]
all_different = [Distinct(D)]
abc = 100 * a + 10 * b + c
hibj = 1000 * h + 100 * i + 10 * b + j
hde = 100 * h + 10 * d + e
defg = 1000 * d + 100 * e + 10 * f + g
equations = [abc * d == hibj, hibj + hde == defg]
s = Solver()
s.add(vals_0_to_9 + all_different + equations)
while s.check() == sat:
m = s.model()
print(", ".join([f'{Di}={m[Di]}' for Di in D]))
s.add(Or([Di != m[Di] for Di in D]))
This prints out a=9, b=3, c=4, d=7, e=2, f=1, g=0, h=6, i=5, j=8 as unique solution.

How can i get sum of all the numbers that this program prints?

B = 1
A = 3
C = 1
while C < 1000:
B = B + 1
C = A * B
print (C)
This is the code and i want to get the sum of the numbers that it prints
Here is a possibility,
B = 1
A = 3
C = 1
D = 0
while C < 1000:
B = B + 1
C = A * B
D += C
print (C)
# sum of all printed numbers
print(D)
B runs over all the integers from 2 to 334; you only need the sum of all integers from 2 to 334 (which is well known: average * number of elements) and then multiply it by A:
A = 3
B_max = 334 # ~ (1000 // A) + ...
res = A * (B_max + 2) * (B_max - 1) // 2
# 167832
you just need to make sure you get B_max right...
there is no reason for a loop at all if that is all you need to do.
define a list outside while:
dataList = []
then add C in that list:
while C < 1000:
B = B + 1
C = A * B
dataList.append(C)
then find sum:
print(sum(dataList))
for me, your goal is not clear. can you explain it more for me to be able to help you?
PS. your B = B + 1 can be simplified to:
B += 1
You should declare SUM first:
SUM=0
And at the end of while loop after print message, add
SUM = SUM + C
And thats all, simplest possible way.
B = 1
A = 3
C = 1
total = 0
while C < 1000:
B = B + 1
C = A * B
print(C)
total+=C
print("Sum is : ",total)

Multiple value assignment [duplicate]

This question already has an answer here:
How does swapping of members in tuples (a,b)=(b,a) work internally?
(1 answer)
Closed 3 years ago.
a, b, n = 0, 1, 500
while a < n:
print(a)
a, b = b, a+b
and
a, b, n = 0, 1, 500
while a < n:
print(a)
a = b
b = a+b
Both give different output.
What is the difference between a, b = b, a+b and a = b; b = a+b?
The below code is like swapping.
a, b = b, a+b
Its like doing this
temp = a
a = b
b = temp + b
a, b, n = 0, 1, 500
while a < n:
print(a)
a = b
b = a+b
In above line of code - after print(a), code value in b variable will be assigned to a first and hence the value of a is updated and the updated value of a is being used in b = a+b
Lets say, a =0, b =1 . So after print(a), value of a will be 1 first and b will have 1+1 =2.
Whereas,
a, b, n = 0, 1, 500
while a < n:
print(a)
a, b = b, a+b
In the above code, after print(a), a and b values are simultaneously assigned. In this case, whatever value of a is printed in print(a) will be used in assigning value for a in further step.
Lets say, a = 0 and b = 1 ,
after print(a) which will print 0 first, value in a will be 1 and value in b will be 0+1 = 1 because b = a+b will use a =0 and not a =1.
a, b = b, a+b
is equivalent to
tmp = a
a = b
b = tmp+b
This is not comma separated values. You are doing tuple unpacking.
a, b, n = 0, 1, 500
Is the same as:
a, b, n = (0, 1, 500)
The reason they are different is the first line assigns b to a then adds a and b together. It’s essentially the same as:
a = b
b = a+b

How to add iteration numbers

my question is about adding loops in python
I am trying to add iteration numbers like summation of all iteration results
For example
first iteration
a = 10
b = 5
a = a + b = 15
c = a = 15
second iteration
a = 15
b = 5
a = a + b = 20
c = a1 + a2 = 35
I know to iterate using for loop which is like this
for i in range(2)
a = 10
b = 5
a = a + b
which gives a = 20
but how to get c which is adding iteration results
a=10
b=5
c=0
for i in range(2):
a = a + b
c = c + a
print a
print c
Above one gives results of a and c
You can define your variable outside your for loop to update it with the sum of each iteration
a_values = [10, 15]
b_values = [5, 5]
c = 0
for a, b in zip(a_values, b_values):
c += a + b
print(c)
35
I am afraid you are quite confused OP. Why don't you just do this instead:
a = 10
b = 5
c = sum(a+b for _ in range(2))
The problem with your version is that after calculating a during the first iteration, you re-assign its value to 10 in the second. Your loop would work with some modifications:
a = 10
b = 5
c = 0
for i in range(2)
c += a + b
You actually don't need any loop if you apply some basic arithmetic:
print(a + n * b)
print(a * n + (n*(n+1))//2 * b)
With a = 10, b = 5 and n = 2, it outputs:
20
35

Categories

Resources