why does python consume so much memory and never release it - python

Why does my program keep consuming memory and never release it? If you try to run it, you will know what I mean.
#!/usr/local/bin/env python
def is_prime(num):
if num <= 1: return False
if num != 2 and num % 2 == 0: return False
to = num / 2 + 1
for x in range(3, to, 2):
if num % x == 0: return False
return True
if __name__ == "__main__":
primes = []
for x in range(2, 100):
if is_prime(x): primes.append(x)
print(primes)
product = primes[0]
for i in range(1, len(primes)):
print("prime: " + str(primes[i]))
new_prime = product * primes[i] + 1
if is_prime(new_prime):
print("new prime: " + str(new_prime))
else:
print(str(new_prime) + " is not prime! [error]")
product *= primes[i]

It turns out that python2 has memory leak. Python3 won't have this issue.

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)}")

TypeError: not all arguments converted during string formatting, Python

I dont know why the error is coming up. Its a program to show the numbers that include a 7 and are a multiple of 7.
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = NumbersList [num-1]
ListNumber = list(str(N))
if (N == 0):
print(Answer)
elif (num == Length):
print(Answer)
elif (N % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
sys.stdout.flush()
New Question. My elif statement at the bottom doesnt seem to work.
The input is a list of numbers from 0-100. Stop at a 0. Answer = Numbers with %7 = 0 or with a 7 in it
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = NumbersList [num]
ListNumber = list(str(N))
if (int(N) == 0):
print(Answer)
break
elif (num == Length):
if (int(N) % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
print(Answer)
elif (int(N) % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
sys.stdout.flush()
Stealing #PeterWood's comment, you need to convert the input to an integer first.
N = int( NumbersList [num-1] )
You may also want to consider using for num in NumberList and reading https://www.python.org/dev/peps/pep-0008/ for a guide to good practice.
This works for me (or doesn't error):
import sys
Numbers = raw_input()
Answer = 0
NumbersList = Numbers.split()
Length = len(NumbersList)
for num in range(0, Length):
N = int( NumbersList [num-1])
ListNumber = list(str(N))
if (N == 0):
print(Answer)
elif (num == Length):
print(Answer)
elif (N % 7 == 0):
Answer = Answer + 1
elif 7 in ListNumber:
Answer = Answer + 1
print Answer
sys.stdout.flush()

How can i make infite loop to ask user if he wants to input another number?

how can i make my code to ask user if wants to input another number? I could barely make my code run without errors, i am a toddler at python. I struggled a lot to write the code below. I know that stackoverflow is not a code writing service. But my little brain hurts now and i can't continue without help. I want to say simply "Do you want to convert another number?"
import math
# Global definition
#Base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
Base = [str (x) for x in range (10)] + [chr (x) for x in range (ord ('A'), ord ('A') +6)]
h=[str(i) for i in range(10)]+["A","B","C","D","E","F"]
def BIN2DEC (string_num):
num = string_num
if num == 0:
return '0'
bin_str = ''
while num > 0:
bin_str = str(num % 2) + bin_str
num = num / 2
return bin_str
def HEX2DEC (string_num):
return str (int (string_num.upper (), 16))
# Dec2bin
# Decimal to binary
def dec2bin (string_num):
num = int (string_num)
mid = []
while True:
if num == 0: break
num, rem = divmod (num, 2)
mid.append (Base [rem])
return''. join ([str (x) for x in mid [:: -1]])
# Dec2hex
# Decimal to hexadecimal
def DEC2HEX (number):
n = long(number ,16)
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
DEC2HEX( n / 16 )
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
# Hex2tobin
#The hexadecimal to bry
def HEX2BIN (hex_string):
s = int(hex_string, 16)
num_digits = int(math.ceil(math.log(s) / math.log(2)))
digit_lst = ['0'] * num_digits
idx = num_digits
while s > 0:
idx -= 1
if s % 2 == 1: digit_lst[idx] = '1'
s = s / 2
return ''.join(digit_lst)
# Bin2hex
# Binary to hexadecimal
def BIN2HEX (string_num):
return DEC2HEX (BIN2DEC (string_num))
my_num = 0
my_num = raw_input("Insert binary,decimal or hexadecimal:")
while(my_num != 0):
if my_num[0:2] == "0x" or my_num[0] == "x":
print HEX2BIN(my_num)
print HEX2DEC(my_num)
break
elif my_num[0:2] == "0b" or my_num[0] == "b" and all(x in "01" for x in my_num):
print""
print BIN2HEX(my_num)
print BIN2DEC(my_num)
break
else:
print dec2bin(my_num)
print HEX2BIN(my_num)
print long(my_num)
break
my_num = 0
my_num = raw_input(":")
print list(iter(lambda:raw_input("Enter Value, or 'q' to quit:"),"q"))
is my personal favorite way
iter makes an iterator (you need to look it up)
it takes an optional no-argument function that it will continually call until it receives the second argument

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");
}

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

Categories