iteration counter for GCD - python

I have the following code for calulating the GCD of two numbers:
def gcd(m, n):
r = m % n
while r != 0:
m = n
n = r
r = m % n
return n
print ("\n", "gcd (10, 35) = ", gcd(10, 35))
print ("\n", "gcd (735, 175) = ", gcd(735, 175))
print ("\n", "gcd (735, 350) = ", gcd(735, 350))
I would like to count the number of iterations that the algorithm has to go through before finding the GCD. I am having trouble making a for loop to determine the number of iterations.

def gcd(m, n):
r = m % n
counter = 0
while r != 0:
m = n
n = r
r = m % n
counter += 1
return n, counter

Related

I'm trying to find sum of first n palindromes using python

Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")

What are the time complexity of these two codes

Following are two different dynamic programming codes for fibonacci series. I cannot figure out the time complexity of these. Results of both are the same. Any help is appreciated.
#Code 1
def fibo(n) :
if mem[n] is not None:
return mem[n]
if n == 1 or n == 2 :
res = 1
else :
res = fibo(n - 1) + fibo(n - 2)
mem[n] = res
return res
n = int(input("Enter position :"))
mem = [None] * (n + 1)
fibo(n)
Code 2
def fibo(n) :
if len(mem) == n-1 :
return mem[n-1]
if n == 1 or n == 2 :
res = 1
else :
res = fibo(n - 1) + fibo(n - 2)
mem.append(res)
return res
n = int(input("Enter position :"))
mem = []
fibo(n)

list assignment index out of range by code python?

I keep getting an
IndexError: list assignment index out of range.
The error on line 78
This code is written to find motif DNA to bioinformatics
How we can solve this error or the problem ?
Here is my code:
from math import log
class MotifMedianFinding(object):
def __init__(self, input_file):
super(MotifMedianFinding, self).__init__()
self.input_lines = open("C:\\Users\\A.Khassawneh\\Desktop\\fasta.txt")
def output(self):
#main method to call both functions
sequences = {}
for line in self.input_lines:
if '>' in line:
sequences[line] = self.input_lines.next()
for label, seq in sequences.iteritems():
print "DNA:" + seq + "\n\n\n\n\n"
median = self.median_string(seq, 5,5, len(seq))
self.motif(seq, median,5,len(seq))
def median_string(self, dna, t, n, l):
#bound and search method of calulating median string
start_pos = start_pos = [1,1,1,1,1]
best_dist = 1000000000
i = 1
while i > 0:
if i < l:
prefix = str(start_pos)
opt_dist = self.hamming_score(prefix, dna)
if opt_dist > best_dist:
s,i = self.bypass(start_pos,i,l,4)
else:
s,i = self.next_vertex(start_pos,i,l,4)
else:
word = str(s)
if self.hamming_score(word, dna) < best_dist:
best_dist = self.hamming_score(word, dna)
bestword = word
s,i = self.next_vertex(start_pos,i,l,4)
print "Best Word: %s (tot_dis = %s)" % (bestword,best_dist)
return bestword
def motif(self, dna, t, n, l):
#bound and search method of calculating motif
start_pos = [1,1,1,1,1]
best_score = 0
i = 1
while 1 > 0:
if i < t:
opt_score = Score(s, i, dna) + (t-1) * l
if opt_score < best_score:
start_pos, i = self.bypass(start_pos, i, t, n-l+1)
else:
start_pos, i = self.next_vertex(start_pos, i, t, n-l+1)
else:
if self.score(start_pos, dna) > best_score:
best_score = self.score(start_pos)
best_motif = str(s)
start_pos, i = self.next_vertex(start_pos, i, t, n-l+1)
print "motif consensus string: %s (consensus_score = %s) " % (best_motif, best_score)
print "motif positions/string s=(s1..st): %s" % ', '.join(start_pos)
return best_motif
def bypass(vertex, level, l, k):
#skip uncessary calculations in the tree
j = level
for ind in xrange(j,1,-1):
if a[j] < k:
a[j] = a[j] + 1
return vertex, j
return vertex, 0
def next_vertex(self, vertex, level, L, k):
#transverse the tree of a strand of genes
if level <L:
vertex[level+1] = 1
return vertex,level+1
else:
j = L
for ind in xrange(j,1,-1):
if vertex[ind] < k:
vertex[j] = vertex[j] + 1
return vertex, j
return vertex, 0
def score(start_pos):
# biggest score of motif
total = 0
for i in start_pos:
total += i
return total
def hamming_score(self, s, dna):
pass
motif_median = MotifMedianFinding('HMP-part.fa')
motif_median.output()
xrange(x,y) goes from x to y-1 (x, x+1.... y-1). In your code, it would have been fine to do xrange(1,j), because that wouldn't have included j. But if you swap it to xrange(j,1,-1), you go (j, j-1.... 2).
Basically, you probably need to change it to xrange(j-1,0,-1) depending on your intended range.

Russian Peasant Multiplication Python using recursive-tail

I tried making this code and run it, but the result showed "None".
I've edited by adding another else in the loop function, then it actually produces a int result of '57' which is not exactly the answer.
def double(n):
return n*2
def halve(n):
return n//2
def mult(m,n):
def loop(m,n):
if n>1:
if n%2 != 0:
return m + loop(double(m),halve(n))
else:
return m #added another else
else:
return m
if n>0:
return loop(m,n)
else:
return 0
print(mult(57,86))
by simple recursion
def double(n):
return n * 2
def halve(n):
return n // 2
def mult(m, n, a = 0):
if n % 2 != 0:
a = a + m
m = double(m)
n = halve(n)
if n % 2 == 0:
m = double(m)
n = halve(n)
if n != 0:
return mult(m, n, a)
return a
print(mult(57, 86))
by nested function
def double(n):
return n * 2
def halve(n):
return n // 2
def mult(m, n):
def loop(m, n, a = 0):
if n % 2 != 0:
a = a + m
m = double(m)
n = halve(n)
if n % 2 == 0:
m = double(m)
n = halve(n)
if n != 0:
return loop(m, n, a)
return a
return loop(m, n)
print(mult(57, 86))

List not being written to a text file

I have a program that is supposed to ask how many primes to calculate then write them all to a text file. However, it creates the file then dosen't run.
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
while(True):
constantcall()
Your problem is the code:
while len(primes) < int(ask):
k = 2
at this point len(primes) is less than int(ask), and there is nothing that add items to primes, so infinite loop.
Your code must be (in order to avoid infinite loop):
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
constantcall()
Using Sieve of Eratosthenes algorithm
You could use the algorithm Sieve of Eratosthenes:
def primes(count):
"""
Returns a list with the first `count` prime numbers.
An advice: If you will be using this functiona a lot it's better
for performance if you precalculate cribe.
"""
# Calculate primes up to 50, you can change this to your preference.
MAX = 50
sieve = [1] * MAX
for i in range(2, int(MAX ** 0.5) + 2 ):
for j in range(i + i, MAX, i):
sieve[j] = 0
# Finally primes are indexes in the list that still has 0.
result = []
for index, elem in enumerate(sieve):
if elem == 1: result.append(index)
return result[1:count + 1]
Your code can then be rewrited as:
def constantcall():
f = open("primes.txt", "w")
ask = int(input("how many primes? "))
prime_numbers = primes(ask)
f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))
if __name__ == '__main__':
constantcall()
Your code does nothing.
while len(primes) < int(ask):
k = 2
Is useless.
while not(k==j) and not(j%k==0):
k = k + 1
Is useless as j is always 2.
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
Here you append 2 to primes once.
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close()
return
So len(primes) is always 1.
Here is a solution. Sorry for C language, but you could easily pythonize it.
#include <stdio.h>
typedef unsigned long long ull;
int main(){
ull numb=10000,stop=20000;
ull i,c;
int cnt;
printf("Here are the primes between %lld and %lld :\n\n",numb,stop);
while(numb<=stop){
for(i=1;i<=numb;++i){
if(!(numb%i)) ++cnt;
}
if ((cnt==2) || (i==1)) printf("%lld; ",numb);
cnt=0;
++numb;
}
printf("\n\nThat's all\n");
}

Categories