简体   繁体   中英

Getting values from all the indices of a list (Determining Prime Numbers)

First and foremost I'm new to Python. I am trying to determine if a number, let's say 167 is a prime number by using the modulo operation, % .

Eg, Let 167 % n = some value i

When 167 % 1 and 167 % 167 , it should return 0 and for n in range(2,166) , it should be giving the remainder of 167 % n . The problem I have is that I am trying to print the remainder when 167 % n for n = 1 ~ 167 but don't know how to get the values (which should be the remainder) of the indices of a list.

So, here's what I have:

L  = [] #creates empty list
i=0     #initialize i? 
for i in range(1, 168) :
if 167 % i == 0  :
    print ("There is no remainder")
else :
    167 % i == x   # x should be the value of the remainder 
    L[i].append(x) #attempting to add x ... to the indices of a list. 
    print(L[x])    #print values of x.

It's even better if I can use the while loop, that should be much clearer. So, while i iterates from 1-167, it should be adding the results x into the indices of the list and I want to print those results.

Any recommendation guys? Any help appreciated!! Thanks a bunch.

This creates a list of all remainders that are not equal to zero:

L  = []
for i in range(1, 168) :
    remainder = 167 % i
    if remainder == 0  :
        print("There is no remainder")
    else:
        L.append(remainder)
        print(remainder)

>>> len(L)
165

There are a number of problems in your code:

  • Your indentation is wrong.
  • Setting i = 0 before the loop does not make sense because it is not used before the loop and overridden in the loop.
  • This: 167 % i == x compares the remainder with a non-existing x . You want to assign the result to x with x = 167 % i .
  • You try to append to an element of L at index i using L[i].append(x) but you want to append x to L with L.append(x) .
  • Finally, you try to get the value you just added using print(L[x]) but you need to use print(L[i]) , simpler, just print remainder with print(remainder) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM