It works using a regular loop but I want it to work using set comprehension.
def setComp():
result = set()
for n in range(1, 101):
x = n
y = x**2
if y%x == 0 and y%3 == 0:
tup = (x,y)
result.add(tup)
return result
print(setComp())
This is what I have:
result = { x = n, y = x**2 for n in range(1, 101)if n%x == 0 and y%3 == 0 }
Try it
{(x, x**2) for x in range(1,101) if (x**2) %3 == 0}
You can do this with a one-liner list comprehension
result = {(n, n ** 2) for n in range(1, 101) if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}
However the downside to this is that is has to calculate n**2 three times during the comprehensive. For better performance, generate two list and use zip in the comprehension
xs = range(1, 101)
ys = [n ** 2 for n in q]
reuslts = {(x, y) for x, y in zip(xs, ys) if (y % x) == 0 and (y % 3 == 0)}
The latter option provides better performance than the former
import timeit
xs = range(1, 101)
ys = [n ** 2 for n in xs]
def l():
return {(n, n ** 2) for n in xs if (n ** 2 % n) == 0 and ((n ** 2) % 3 == 0)}
def f():
return {(x, y) for x, y in zip(xs, ys) if (y % x) == 0 and (y % 3 == 0)}
print('l', timeit.timeit(l))
>>> 68.20
print('f', timeit.timeit(f))
>>> 19.67
Related
we have array A that has N len(N = the len of the array)
I have to found the numbers of pairs (J, I) that work on the following statement:
A[J]+A[I} == A[J] * A[I]
1<=i, j<=N
(1 ≤ N ≤ 40000)
(0 ≤ A(i) ≤ 10^9)
example:
input:
3
2 4 2
output:
1
well i counldn't know how to limit the input size to only have 2 spaces or to split it if there was any more than the N
edit*
A = []
N = int(input(""))
B = (input(""))
B = B.split()
z = 0
myList = []
mylist2= []
pairs = 0
for q in B:
if z < N:
myList.append(q)
z += 1
elif z >= N:
break
for w in myList:
w = int(w)
mylist2.append(w)
for i in mylist2:
for k in mylist2:`enter code here`
if i + k == i * k:
pairs+1
that what i have done so far
So, as already mentioned in comments only pairs (2, 2) and (0, 0) satisfy the condition. The number of (0, 0) pairs is count(0) * (count(0) - 1) / 2. The same for (2, 2) pairs. Expressing this in python (assuming that array a is given).
def countsumprod(a):
c0 = a.count(0)
c2 = a.count(2)
return (c0 * (c0 - 1) + c2 * (c2 - 1)) // 2
I'm pretty new in python and I'm having trouble doing this double summation.
I already tried using
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
and using 2 for loops but nothing seens to work
You were pretty close:
N = int(input("N: "))
M = int(input("M: "))
x = sum(sum(j ** 2 * (k + 1) for k in range(M)) for j in range(1, N + 1))
It also can be done with nested for loops:
x = 0
for j in range(1, N + 1): # [1, N]
for k in range(M): # [0, M - 1]
x += j ** 2 * (k + 1)
After a little math...
x = M * (M+1) * N * (N+1) * (2*N+1) // 12
I have written a code to find Pythagorean triplets but it is not optimized
it took 5-6 minutes for the algorithm to find answer for big numbers...
my teacher said it should take less than 3 secs...
num = int(input())
def main(n):
for x in range(1, n):
for y in range(1, x):
for z in range(1, y):
if x + y + z == n:
if x * x == y * y + z * z or y * y == x * x + z * z or z * z == x * x + y * y:
a = f'{z} {y} {x}'
print(a)
return
else:
print('Impossible')
for example if you enter 12, you'll get 3,4,5
if you enter 30 , the answer will be 5,12,13
The sum of these three numbers must be equal to the number you entered.
can anyone please help me ?
Note the proof for the parametric representation of primitive pythagorean triples. In the proof, the author states:
We can use this proof to write an optimized algorithm:
def p(num):
a, b, c = 1, 1, 0
n = 0
while c < num:
for m in range(1, n):
a = 2 * m * n
b = n ** 2 - m ** 2
c = n ** 2 + m ** 2
if c >= num:
return "Impossible!"
elif a + b + c == num:
return b, a, c
n = n + 1
print(p(12)) # >>> (3, 4, 5)
print(p(30)) # >>> (5, 12, 13)
print(p(31)) # >>> Impossible!
You're doing a lot of repeated and unnecessary work. You know that A^2 + B^2 = C^2 and you know that C > B > A. It doesn't matter if you want to say C > A > B because any solution you find with that would be satisfied with C > B > A. For instance take 12 and solution 3, 4, 5. It doesn't actually matter if you say that A=3 and B=4 or A=4 and B=3. Knowing this we can adjust the loops of each for loop.
A can go from 1 to num, that's fine. Technically it can go to a bit less since you are adding another value to it that has to be at least 1 as well.
B then can go from A+1 to num since it needs to be greater than it.
So what about C? Well it doesnt' need to go from 1 since that's not possible. In fact we only care about A + B + C = num, so solve for C and you get C = num - A - B. That means you don't need to use a loop to find C since you can just solve for it. Knowing this you can do something like so:
In [142]: def find_triplet(num):
...: for a in range(1, num-1):
...: for b in range(a+1, num):
...: # A^2 + B^2 = C^2
...: # And A+B+C = N
...: c = num - a - b
...: if c > 0:
...: if a*a + b*b == c*c:
...: print(f'{a} {b} {c}')
...: else:
...: break
...:
In [143]: find_triplet(30)
5 12 13
So why check to see if C > 0 and break otherwise? Well, if you know C = num - A - B and you are incrementing B, then once B becomes too large, C is going to continue to get more and more negative. Because of that you can check if C > 0 and if it's not, break out of that inner loop to have A increment and B reset.
The approach you discussed takes O(n^3) complexity.
An efficient solution is to run two loops, where first loop runs from x = 1 to n/3, second loop runs from y = x+1 to n/2. In second loop, we check if (n – x – y) is equal to (x * x + y * y):
def pythagoreanTriplet(n):
# Considering triplets in
# sorted order. The value
# of first element in sorted
# triplet can be at-most n/3.
for x in range(1, int(n / 3) + 1):
# The value of second element
# must be less than equal to n/2
for y in range(x + 1,
int(n / 2) + 1):
z = n - x - y
if (x * x + y * y == z * z):
print(x, " ", y, " ", z)
return
print("Impossible")
# Driver Code
n = int(input())
pythagoreanTriplet(n)
PS: Time complexity = O(n^2)
So, for school, I got an exercise on recursion, which goes as follows:
I'm given a string and a random int value 'N'. The string is a boolean expression, for example '3*x - 2* y <0' . The result has to be a list of tuples(x, y), (-N < x < N and -N < y < N), from all the possible tuple combinations who meet the expression. I did this exercise first with for loops etc and that was not so difficult, but then I had to do it recursively, and here's where I got stuck:
As you can see, I just add up x and y by '1' at the end of the code, which will give me all tuple combinations where X and Y are the same. For example, if N = 5, my code only evaluates the combinations (-4,-4), (-3,-3) ... (4,4) but not (-2,1) or (1,3) for example. So my question is: can anyone help me writing a recursive code which evaluates the boolean expression in all the possible tuple combinations?
My code has to be written recursively and I can't use functions as 'itertools' etc, it's not allowed in our school.
**MY CODE:**
def solution(expression, N,x=None,y=None):
if x is None: x = -N + 1
if y is None: y = -N + 1
res = []
if x >= N and y >= N:
return []
if eval(expression) == True:
res.append((x, y))
return res + solution(expression, N, x+1, y+1)
I have modified your code and I think it works now:
UPDATE: I have corrected this expression if x < N - 1 : to that one if x < N - 1 or y < N - 1:
def solution(expression, N, x=None, y=None):
if x is None: x = -N + 1
if y is None: y = -N + 1
res = []
if eval(expression) == True:
res.append((x, y))
# if x < N - 1 :
if x < N - 1 or y < N - 1:
if y < N - 1:
y += 1
else:
x += 1
y = - N + 1
return res + solution(expression, N, x, y)
else:
return res
print(solution('3*x - 2* y <0', 4))
Slightly different approach building on getting permutations for a list and in the end checking the expression. Not the prettiest code but does the job.
results = []
def check(expression, items):
x = y = None
if len(items) == 1:
x = y = items[0]
if eval(expression) and (x, y) not in results:
results.append((x, y))
if len(items) == 2:
x = items[0]
y = items[1]
if eval(expression) and (x, y) not in results:
results.append((x, y))
x = items[1]
y = items[0]
if eval(expression) and (x, y) not in results:
results.append((x, y))
if len(items) > 2:
for i in items:
remaining_elements = [x for x in items if x != i]
check(expression, remaining_elements)
expression = "3*x - 2*y < 0"
N = 4
items = range(-N + 1, N)
check(expression, items)
print(results)
I am trying to write a function to determine if a number is prime. I have come up with
the following solution, however inelegant, but cannot figure out how to write it.
I want to do the following: take the number x and divide it by every number that is less than itself. If any solution equals zero, print 'Not prime.' If no solution equals zero, print 'Prime.'
In other words, I want the function to do the following:
x % (x - 1) =
x % (x - 2) =
x % (x - 3) =
x % (x - 4) =
etc...
Here is as far as I have been able to get:
def prime_num(x):
p = x - 1
p = p - 1
L = (x % (p))
while p > 0:
return L
Wikipedia provides one possible primality check in Python
def is_prime(n):
if n <= 3:
return n >= 2
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, int(n ** 0.5) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True