I am creating a program that
- accepts an inputted list
- finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c =1
if c==1:
prime.append(i)
return (prime)
CodePudding user response:
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
CodePudding user response:
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer
for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step)
- learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how to find prime numbers in list python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.