Removing prime numbers from a linked list - python

I have a linked list that I am trying to generate a random list and then remove all of its prime numbers. This is what I have so far. I know how to find the primes I'm just not sure where to go on removing them from the list. This is my updated list, it only removes one number instead of deleting all primes.
import random
from linkListDef import *
def is_prime(llist):
number = llist[0]
half = int(number / 2)
status = True
for count in range(2, half + 1):
if number % count == 0:
status = False
return status
def main():
llist = LinkedList()
counter = 0
while counter != 20:
numbers = random.randrange(1, 101)
counter += 1
llist.push(numbers)
print ("Created Linked List: ")
llist.printList()
llist.deleteNode(numbers)
print ("Linked List after Deletion of primes:")
llist.printList()
if __name__ == '__main__':
main()

You can do a for loop on the now generated linked list, check the number using your isPrime method and running .remove(item) on the list, where item is the current iteration over the list

Related

I want a list of all the prime numbers that are smaller than a integer

Hey so i have these two functions. The first one checks whether a number is a prime number which works. The second one is supposed to take a number and have all the prime numbers that are smaller than that number added into a sorted list. This is the code i have right now,
def is_prime(n):
flag = True
if n == 1:
flag = False
for i in range(2, n):
if (n % i) == 0:
flag = False
return flag
def primes(num):
primelist = []
flag = is_prime(num)
for i in range(1, num - 1):
if flag == True:
primelist.append(num)
return sorted(primelist)
How would i go about adding all the prime numbers lower than a integer into the list?
You've almost got it!
The issue in your primes function is that flag is computed outside of the loop. So it's computed only once for the input num.
Instead, it should be computed for every loop entry.

Find prime numbers with list comprehension

I was trying to write a code to select the prime numbers in a list. The user gives a limit and the program displays all prime number from 2 to the limit. I was trying to reduce the maximum amount of lines I could and was surprised with some situations I can't understand. If you can help me, I'd be grateful.
I wrote this code:
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
lista = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in lista if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
It runs as I expected, but when I tried deleting the first list assignment line and include the range function directly into the comprehension, it doesn't work. Why?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in [*range(2, limit + 1)] if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
Other problem. As the line with range is not a list I fixed it only to improve the code, but when I changed the name of the value from 'lista' to another name, I saw that it doesn't work too. Why?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
nums = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in nums if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
Thanks for your attention.
This one-liner works perfectly :
def primes(val):
return [x for x in range(2, val) if all(x % y != 0 for y in range(2, x))]
print(primes(10))
Thank you for your attention.I liked the answer of our friend Yash Makan, but when I tried larger numbers, like 100000, it never led me to the result (or I was not so patient to wait). So I continued thinking about the problem and got the following that is the fastest way to compute this problem I could achieve with list comprehension. Note how fast you can compute millions of numbers.
# returns all integers from 2 to a limit given by the user.
def primes(limit):
l = [i for i in range(2, limit + 1) if all(i % j != 0 for j in [2, 3, 5])]
lista = []
return [2, 3, 5] + [lista.append(i) or i for i in l if all( i % j != 0 for j in lista[:int((len(lista) ** .5) + 1)])]
def main():
l = int(input("Enter the limit: "))
return print(primes(l))
if __name__ == '__main__':
main()

How to execute this in command line(I am using spyder)

Write a python program to accept 10 numbers through command line arguments and calculate the sum of prime numbers among them.
This is my question.
I tried this
for Number in range (1, 101):
count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break
if (count == 0 and Number != 1):
print(" %d" %Number, end = ' ')
but this is naive and works only for given range. I want to input 10 numbers in command prompt and it should find the sum of prime numbers in my input. I tried using import sys and giving sys.args[input] but it is showing errors.
Can someone please help with this?I am just starting to learn coding.
Thanks in advance:)
A solution can be this:
import sys
nums = sys.argv
def with_loop():
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(10):
num = int(input("{}. Please enter a number: ".format(count)))
if num > 1: # if number is larger than 1, we need to check
for j in range(2, num):
if (num % j) == 0:
break
else:
total += num
elif num == 1: # 1 is a prime number
total += num
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
def with_argv(nums):
total = 0 # to collect the prime numbers
count = 1 # a counter for the numbers that you entered
for i in range(1, len(nums)):
if int(nums[i]) > 1: # if number is larger than 1, we need to check
for j in range(2, int(nums[i])):
if (int(nums[i]) % j) == 0:
break
else:
total += int(nums[i])
elif int(nums[i]) == 1: # 1 is a prime number
total += int(nums[i])
else: # otherwise the number is negative so we skip.
pass
count += 1
print("\nTotal : {}".format(total))
with_loop()
with_argv(nums)
A simple example:
sum = 0
for count in range(1,11):
sum += int(input(f'Enter number {count} : '))
print(f'Total sum : {sum}')
To solve this problem, I would first define a function that checks whether a number is prime or not. It would only return a Boolean and nothing else.
Then I would create two lists- one for storing all the numbers entered by a user and another for storing all the prime numbers among the numbers entered by the user. I would use my predefined function for this check.
When the list of prime numbers is ready, I would use the sum() method to find the sum of the items of the list viz. the primes numbers the user has entered.
Here is the code-
def isPrime(num): #defining a function to check a given number is prime
factors = []
if num == 2:
return True
else:
for i in range(1, num + 1):
if (num % i == 0):
factors.append(i)
if len(factors) == 2:
return True
else:
return False
numbers = [] #list for user entered numbers
primes = [] #list for prime numbers among them
print("Enter 10 numbers.\n")
for i in range(10):
numbers.append(int(input(f'Enter number #{i + 1}:')))
#adding user inputs to numbers list
for i in numbers: #checking if the entered numbers are prime
if isPrime(i):
primes.append(i)
print("Sum of the prime numbers enters by the user is " + str(sum(primes)))
#sum() method adds all elements in an iterable
This code will do.
Spyder uses IPython Console. That is the command line referred in the question. So, if you run the code in Spyder, the IPython console will run this program.

random number list generator

I need to make a list of random numbers than separate each number, odd or even.
Here is my current progress.
import random
def main():
for x in range(20):
number=list(random.randint(1,101))
for number in number:
list=number
for x in list:
if (number % 2) == 0:
print("{0} is Even number".format(num))
else:
print("{0} is Odd number".format(num))
I think too much terms like number in number will make you confused, so I modified your code like this, I think this will help you to understand comprehensively.
import random
def main():
ls = [] #define a space list
ls_e = [] #even number
ls_o = [] #odd number
for x in range(20): #for loop 0-20
number=random.randint(1,101) #create random number between 1-101
ls.append(number) #put number into ls
print(ls)
for x in range(len(ls)): #for numbers in ls
if (ls[x] % 2) == 0: #check logic
print("{0} is Even number".format(ls[x]))
ls_e.append(ls[x]) #put into even list
else:
print("{0} is Odd number".format(ls[x]))
ls_o.append(ls[x]) #put into odd list
main()
Use this code.
import random
L_odd = []
L_even = []
for x in range(20):
number = random.randint(1, 101)
if number % 2 == 0:
L_even.append(number)
else:
L_odd.append(number)
In this code, append is a method to append element to the list (for example, L_even.append(number) means to append number to the list L_even)
As the comments from #Harshal Parekh and #PM 77-1, you need to know the importance of indent of Python, and I think you need to study python basic.
You could use list comprehension to keep it simple. Hope this helps!
from random import randint
rand_nums = [randint(0, 101) for i in range(20)]
rand_odds = [i for i in rand_nums if i % 2 == 1]
rand_evens = [i for i in rand_nums if i % 2 == 0]
print(rand_nums)
print(rand_evens)
print(rand_odds)

Printing first n Happy Numbers - Python

I am writing a piece of code in python that checks whether a given number is happy or not, that is taking the number and adding the sum of their squares is 1 which is a happy number or ending up with a never ending loop which defines a unhappy number.
After that, I want to list the first n Happy Numbers. I got the checking for happy numbers down albeit sloppily, I just can't seem to figure out the listing part.
def adder(num):
total=0
if len(str(num))>1: #check if given number is double digit or not
tens = int(str(num)[0]) # splitting the digits
ones = int(str(num)[1])
total = (tens**2)+(ones**2) # summing up the squares
#print (total)
return total
else: # if the given number is a single digit
total = (num**2)
#print (total)
return total
#adder(9)
def happynumber(num, counter):
N = adder (num) # storing the sum in a variable
#print ("value of n is {}".format(N))
if N == 1: #checks if the sum is 1
# print ("In just {} tries we found that {} is a happy number.".format(counter, number))
print (number)
else: # if the sum isn't 1, racalls the happynumber function
counter += 1 # keeps track of number of tries so that we don't end up in an infinite loop
if counter < 11: # setting the limit for number of tries
#print (counter)
happynumber (N, counter)
else:
#print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number))
return False
counter = 0
for i in range(0,100): # listing all the happy numbers between 0 and 100
number = i
happynumber (number, counter)
Additionally, I would like it if you guys would review my writing style and give some pointers.
The problem, I am not able to list the first n numbers however way I try.
I tried using counter in the loop but to no avail.
If your main problem is that you want to have all your happy numbers in a list, you can easily address this by defining a list outside the recursion loop.
def happynumber(num, counter):
N = adder(num)
if N == 1:
happyhappy.append(number) #new happy number into list
else:
...continue with your code
#-------main script-------------
happyhappy = [] #create a list to store your happy numbers
counter = 0
for i in range(100):
number = i
happynumber(number, counter)
print(happyhappy) #and retrieve the list
Having said that there is an inefficiency in your adder() function. It calculates only up to two digits. Even worse, it has to perform the square operation for each digit from scratch, which is very time consuming.
A better way is to pre-calculate the squares and store them in a dictionary:
square_dic = {str(i): i ** 2 for i in range(10)} #create a dictionary of squares
def adder(num):
s = str(num) #make the number into an iterable string
x = [square_dic[i] for i in s] #look up the square of each digit
return sum(x) #and calculate the sum of squares
Thanks to list comprehensions in Python we can make it even snappier
square_dic = {str(i): i ** 2 for i in range(10)}
def adder(num): #does exactly, what the other function did
return sum(square_dic[i] for i in str(num))
So first off, you shouldn't have to pass your counter variable since it is a global variable. I'd also probably declare it up above your methods just to make sure there are no issues.
Your next issue is you never reset your counter variable. So the first time the program runs into a number that is not-happy after 10 attempts it proceeds to return false for every single number that is not happy after the first attempt. Try adding in counter = 0 before your return False line in the if counter < 11/else block
Here is an example with very small change to your current code. I add another input for the happynumber function, that is your list that you want to store the happy numbers.
I am sure this is not the most efficient way, but it shows how you can update your code.
The code :
def happynumber(num, counter, the_list):
N = adder(num);
print ("value of n is {}".format(N));
if counter == 0: #THIS IS ADDED
the_list.append(num); #THIS IS ADDED
if N == 1:
print ("In just {} tries we found that {} is a happy number.".format(counter, number))
print (num);
else:
counter += 1
if counter < 11:
print (counter)
happynumber(N, counter, the_list)
else:
print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number))
the_list.pop(); #THIS IS ADDED
return False
counter = 0;
happynumber_list = []; #THIS IS ADDED
for i in range(0,100):
number = i
happynumber (number, counter, happynumber_list)
In the first attempt, the number will be stored to the list...but if the number was found not a happy number.. then that number will be pop out of the list.
Here is the result :
[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 59, 68, 70, 79, 82, 86, 91, 94, 95, 97]
Is this okay?
You could use memoization to make the use of a counter unnecessary. I would also use a generator (yield) so only the number of results are produced that you ask for. Then you don't have to specify a range (0, 100), but can just specify that you want the first 25 happy numbers (or whatever is needed).
Here is how that would look:
import itertools
def sum_digit_squares(num):
return sum(int(i)*int(i) for i in str(num))
def happynumbers():
memo = { 1: True }
for i in itertools.count(): # forever (as long as getting from this iterator)
result = None # Will become either True (happy) or False (not happy)
visited = set()
j = i
while result is None:
if j in memo: # Did we make the calculation for this one before?
result = memo[j]
elif j in visited:
result = False # endless loop detected
else:
visited.add(j)
j = sum_digit_squares(j)
for j in visited:
memo[j] = result
if result:
yield i
print (list(itertools.islice(happynumbers(), 0, 25))) # Produce first 25 happy numbers

Categories