Puzzler solver program: How many different solutions are there to (1/a)+(1/b)+(1/c)+(1/d)+(1/e)+(1/f)+(1/g) = 1? - add

I wrote the python code below that solves and prints each possible solution for anything under 6 unit fractions, but given how I programmed it, it takes infinitely long to check for 7 fractions. Any ideas on how to modify the code to find all the possible solutions more efficienty?
import sys
from fractions import Fraction
import os
#myfile = open('7fractions.txt', 'w')
max = 7 #>2 #THIS VARIABLE DECIDES HOW MANY FRACTIONS ARE ALLOWED
A = [0] * max
A[0] = 1
def printList(A):
return str(A).strip('[]')
def sumList(A):
sum = 0
for i in A:
if i != 0:
sum += Fraction(1, i)
return sum
def sumTest(A):
sum = 0
v = 0
for i in range(0, len(A)):
if A[i] == 0 and v == 0:
v = Fraction(1,A[i-1])
if v != 0:
sum += v
else:
sum += Fraction(1, A[i])
return sum
def solve(n, A):
if n == max - 2:
while (sumTest(A) > 1):
print(A)
if sumList(A) < 1:
e = 1 - sumList(A)
if e.numerator == 1 and e.denominator>A[n-1]:
A[n+1] = e.denominator
#myfile.write(printList(A) + '\n')
print(A)
A[n+1] = 0
A[n] += 1
else:
while (sumTest(A) > 1):
if sumList(A) < 1:
A[n+1] = A[n] + 1
solve(n+1, A)
A[n+1] = 0
A[n] += 1
#execute
solve(0, A)

Related

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

How to write a function using for and if

I'm trying to write a code for calculating the number of factors for an arbitrary integer number but unfortunately when I run that I receive a false answer
I have tried for loop without defining function in this case and I got the result.Contrary to that, when I define a function I can't see the proper result
r = 0
def factor(a):
global r
for i in range(1, a + 1):
if a % i == 0:
r += 1
return r
a = int(input())
factor(a)
for example 18 has 6 factors but I receive just 1.
Use print to check your code. Indentation in Python matters. Also, global is not needed.
def factor(a):
r = 0
for i in range(1, a + 1):
if a % i == 0:
print('i', i)
r += 1
return r
a = int(input())
print(factor(a))
It was an indentation problem: the function should only return after the loop has finished iterating.
r = 0
def factor(a):
global r
for i in range(1, a + 1):
if a % i == 0:
r += 1
return r
a = 18 # int(input())
factor(a)
output:
6

solve n which is an integer above 0 in python

This code works but it is not very efficient is there any help on a faster code in python to find n knowing that n is an integer above 0 and that n has no upper bound, how(x) will return you 1 if x>n, 0 if x = n, and -1 if x
def how(x):
if x > n:
return 1
elif x < n:
return -1
else:
return 0
def find(how):
if how(1) == 1:
return 1
x = 2
while how(x) != 1:
x = x**x
v = x
while how(x) != 0:
if how(x) == 1:
v = x
x = (x+1)//2
else:
x += (v-x+1)//2
return x
Rebecca, I've added some print statements so you can see where goes what wrong. As Patrick Artner said... its a bit confusing which way to go so I've tried to clean-up some things that enable you to continue exploring comparison of two variables against each other (and fake error catching (0).
Lets start and remove the confusing lingo and produce something workable code. With current below script it runs and with value = 1, reference = 1 you get the below print result in a continues loop until YOU stop the script manually:
v1 = n: error
loop1 1
def selector(v1, n):
if v1 > n:
print 'v1 > n', v1, n
return 1
elif v1 < n:
print 'v1 < n', v1, n
return -1
else:
print 'v1 == n: error'
return 0
def find(value, reference):
if selector(value, reference) == 1:
return 1
while selector(value, reference) != 1:
x = value**value
print 'loop1', x
v = x
while selector(value, reference) != 0:
print 'loop2'
if selector(value, reference) == 1:
v = value
x = (value+1)/2
print 'loop2-if', v, x
else:
x += (v-(value+1))/2
print 'loop2-else', x
print ' Almost done...'
return x
if __name__ == '__main__':
n = 1
print find(1, 1)
Happy exploring,....

Euler 12 need optimization

I have solved euler problem 12, but it needs some optimization. I have read on the euler forums, but it has not helped me optimized it. However, I have managed to get the solution, I just need to speed it up. It currently takes 4 minutes to run. Here is my code:
import time
def nthtriangle(n):
return (n * (n + 1)) / 2
def numberofnfactors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
def FirstTriangleNumberWithoverxdivisors(divisors):
found = False
counter = 1
while not found:
print(int(nthtriangle(counter)), " ", numberofnfactors(nthtriangle(counter)))
if numberofnfactors(nthtriangle(counter)) > divisors:
print(" first triangle with over ",divisors, " divisors is ", int(nthtriangle(counter)))
found = True
break
counter += 1
start_time = time.time()
FirstTriangleNumberWithoverxdivisors(500)
print("My program took", time.time() - start_time, "to run")
Instead of calculating each triangle number individually, use a generator to get the triangle numbers
from timeit import timeit
def triangle_numbers():
count = 1
num = 0
while True:
num += count
count += 1
yield num
def count_divisors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
print(timeit('next(num for num in triangle_numbers() if count_divisors(num) >= 500)',
globals=globals(), number=1))
Gives me 3.8404819999996107 (seconds) on my machine. You could probably also improve the divisor counting.
What's really slowing you down is calling nthtriangle and numberoffactors more than once in your loop! Plus, those calls to print aren't free.

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

Resources