What the missing part for my python stress test Algorithm? - python

Here's the code, The main problem is to test the algorithm with the naive method and my own method.
def my_solution(numbers):
n = len(numbers)
index_1 = 1
for i in range(0,n):
if numbers[i] > numbers[index_1]:
index_1 = i
if index_1 == 0:
index_2 = 1
else:
index_2 = 0
for i in range(0,n):
if numbers[i] != numbers[index_1] and numbers[i] >= numbers[index_2]:
index_2 = i
sum = numbers[index_1] * numbers[index_2]
return sum
def naive_solution(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def testGenerator():
pass
def main():
for i in range(1000):
test = testGenerator()
correct_answer = naive_solution(test)
my_answer = my_solution(test)
assert(my_answer == correct_answer)
Do I need to edit the testGenerator function? Or any other part missing for? I run the code and nothing happen.

You haven't called your functions. Try calling them by using their name followed by parentheses () and any arguments that need to be entered

Related

How do I count the number of recursive calls for n-queens problem?

I have the following code for solving the n-queens problem and I am supposed to count the number of recursive calls made. I have a function called ConstructCandidates to get the candidate solutions and I am trying to count the number of recursive calls it makes. I was wondering if I am counting the recursive calls correctly as I am not sure if I am doing this correctly.
def createChessBoard(boardSize):
chessBoard = [0]*boardSize
for index in range(boardSize):
chessBoard[index] = [0]*boardSize
return chessBoard
def isSolution(results, numberOfQueens):
if numberOfQueens==n:
for r in results:
for row in r:
print(row)
print()
return numberOfQueens>len(results)
def safeToPlaceQueen(chessBoard, boardRow, boardColumn, boardSize):
for indexColumn in range(boardColumn):
if chessBoard[boardRow][indexColumn] == 1:
return False
indexRow, indexColumn = boardRow, boardColumn
while indexRow >= 0 and indexColumn >= 0:
if chessBoard[indexRow][indexColumn] == 1:
return False
indexRow-=1
indexColumn-=1
diagonalRow, diagonalColumn = boardRow,boardColumn
while diagonalRow < boardSize and diagonalColumn >= 0:
if chessBoard[diagonalRow][diagonalColumn] == 1:
return False
diagonalRow+=1
diagonalColumn-=1
return True
def ConstructCandidates(chessBoard, columnLength, boardSize):
global recursionCounter
if columnLength >= boardSize:
return
for row in range(boardSize):
if safeToPlaceQueen(chessBoard, row, columnLength, boardSize):
chessBoard[row][columnLength] = 1
if columnLength == boardSize-1:
Process(chessBoard)
chessBoard[row][columnLength] = 0
return
#recursively call ConstructCandidates to find more candidate solutions
ConstructCandidates(chessBoard, columnLength+1, boardSize)
chessBoard[row][columnLength] = 0
recursionCounter+=1
def Process(chessBoard):
global results
solutions = copy.deepcopy(chessBoard)
results.append(solutions)
global count
count= len(results)
def isFinished():
if count >0:
return False
n = 8
chessBoard = createChessBoard(n)
results = []
recursionCounter =0
ConstructCandidates(chessBoard, 0, n)
isSolution(results, n)
if isFinished() is False:
print("All possible solutions without the Queen being in danger have been found")
print("The total number of possible solutions for",n,"Queens is:",len(results))
print("The total number of recursive calls to solve the problem of",n,"Queens is:",recursionCounter)
If I am not doing this correctly would someone be able to show me how? The current result I get for 8-queens is 1964

A python function that finds a number's largest divisor excluding itself

When I write this code:
n = int(input('num: '))
for i in range(2, n):
if n%i == 0:
a = i
print(a)
It works without a problem.
But this creates a problem. It says
local variable a referenced before assignment
def largestDivisor(n):
for i in range(2, n):
if n%i == 0:
a = i
return a
How can I fix it?
If you call like largestDivisor(2) you won't go in the for so not in the if and you'll never define a, define it at the beginning :
def largestDivisor(n):
a = 1
for i in range(2, n):
if n % i == 0:
a = i
return a
def largestDivisor(n):
a = 1
for i in range(2,n):
if n%i==0:
a=i
return a
If the condition "n % i == 0" is never True the variable "a" will not exist, therefore you must initialize it before the loop.
def largestDivisor(n):
a = 1
for i in range(2, n):
if n%i == 0:
a = i
return a

how to fix this combination program using binomial factorial equation?

my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1

The "3n+1" Programming Challenge in Pythonallenge

I'm a Python beginner. I'm trying to solve the 3n+1 problem on UVa Online Judge. The program worked fine with the input files. However, I submitted several times but still got Runtime error.
import sys
def compute(i, j):
maxCycleLength = 1
if i <= j/2:
k = j/2+1
else:
k = i
for n in range(k, j+1):
num = n
cycleLength = 1
while (num != 1):
if num%2 != 0:
num = 3*num+1
else:
num = num/2
cycleLength += 1
if cycleLength > maxCycleLength:
maxCycleLength = cycleLength
return maxCycleLength
while True:
nums = sorted(int(x) for x in next(sys.stdin).split())
m = compute(nums[0], nums[1])
print("{} {} {}\n".format(nums[0], nums[1], m))

None output when I run my code

I run this code:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
i = input("input the number: ")
print (fact(i))
and see this output:
input the number: 6
None
Why is my output None? What is wrong?
You are printing the result of a function. In order for a function to return result, you must use the return statement. If you don't return anything, then the the function will automaticaly return None. I suspect you want your function to return j so you need to add return j to the end of the function for it to work.
That should work:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
return j
i = input("input the number: ")
print (fact(i))

Categories

Resources