Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trying to teach myself Python

  1. Sep 17, 2012 #1
    x=0
    y = raw_input("""Up to what number would you like to locate primes?: """)
    for i in range(int(y)):
    x = x + 1
    if x%2 and x%3 and x%5 and x%7:
    print x, '--> PRIME'
    elif x==2 or x==3 or x==5 or x==7:
    print x, '--> PRIME'
    elif x==1:
    print x
    else:
    print x


    I've been on break for the last week and a half and I thought I would spend my time learning Python. I wrote this little script earlier tonight that simply prints out a list of integers within a user specified range and identifies which of them are prime. What I want to do but can't seem to find any documentation on is to have the script count the occurrences of the primes and echo a "There were (blank) number of primes within your specified interval." I have no idea where to look for that sort of thing. I don't want an answer but I would like someone to point me in the direction I need to be going in.

    As always,
    Thanks.

    P.S. This does work, I just want to make it 'better'.
     
    Last edited: Sep 17, 2012
  2. jcsd
  3. Sep 17, 2012 #2

    chiro

    User Avatar
    Science Advisor

    Hey mateomy.

    Have you considered saving results to some array and then processing the array later?
     
  4. Sep 17, 2012 #3
    I've never really done that before. I'm only loosely familiar with arrays in Python as I've only been at this about a week or so. I'm interested in learning though...
     
  5. Sep 17, 2012 #4

    chiro

    User Avatar
    Science Advisor

    Well basically an array can be dynamic (i.e. you determine its size from a variable at runtime) or static (you specify a fixed size that the program uses and it is fixed).

    Because computers have lots of memory, it's really not a big issue to allocate a huge array because not only do we have lots of memory (RAM), but it's getting faster as well.

    Take a look at something like this:

    http://pentangle.net/python/handbook/node39.html

    Basically the idea is to create an array and then store all your stuff in the array and then you can process it later to get whatever information out that you want after you've done your prime routine above.

    So if you want say the first n items in your list, then just access your array and get the first ten items. You can then do whatever you want with those like print them to a file, or the screen (pretty much whatever you want).

    If you do more and more programming, what you'll end up doing is you'll create functions that will take some data in and maybe spit some data back out and in this case if you get data out, you call a function which does its thing and then you take that data and do whatever you want with it (maybe give it to another function for instance).
     
  6. Sep 17, 2012 #5
    Great! I'll take a look at that.

    Thank you very much. I'll post back with new questions.
     
  7. Sep 17, 2012 #6
    I'm confused how I'd get this output piped into an array.
     
  8. Sep 17, 2012 #7

    uart

    User Avatar
    Science Advisor

    Hi mateomy, your program only works up to a maximum count of 120, due to only testing for divisibility with a limited number primes. To make the program more general (able to resolve larger primes) you need to store (and compare against) a "list" of primes currently found, rather than just working with that fixed set of "2,3,5,7".

    That being said, with your current program it is an extremely simple matter of just incrementing a counter to achieve what you want. For example,

    Code (Text):

    x=0
    count = 0
    y = raw_input('Up to what number would you like to locate primes? : ')
    for i in range(int(y)):
      x = x + 1
      if (x%2 and x%3 and x%5 and x%7 and x<>1) or x==2 or x==3 or x==5 or x==7:
        print x, '--> PRIME'
        count += 1
      else:
        print x

    print 'There were ',count,' primes in your range.'

     
    I haven't really tried to fix your code (except for not printing "1" as a prime), I've just compacted it a little to make it easier to read.

    Note the the line "count += 1" is essentially just shorthand for "count = count + 1". And btw, please use "code" "/code" tags (in square brackets) to preserve your formatting. :smile:
     
    Last edited: Sep 17, 2012
  9. Sep 18, 2012 #8
    Awesome! It's nice to be able to see someone with more experience put out a code that's a little more compact and efficient. I'm trying to get a handle on Python at a rudimentary level so I was pretty excited when it even ran. How does that count function work exactly?
     
  10. Sep 18, 2012 #9

    Borek

    User Avatar

    Staff: Mentor

    Funny, last year I tried to learn something about Python, and program finding n primes was the first thing I did:

    Code (Text):
    import math

    primes = [2]

    nth = 30

    def prime(n):
       """Checks if number n is prime, using table of primes found earlier."""
       for p in primes[:int(math.sqrt(n))]:
          if n % p == 0:
             return False
       return True

    i = 2
    while len(primes) < nth:
       i = i+1
       if prime(i):
          print i
          primes.append(i)
     
    n is hard coded, not asked for, but it doesn't change the idea.
     
  11. Sep 18, 2012 #10

    uart

    User Avatar
    Science Advisor

    It's so simple I was hoping it would be self explanatory :smile:

    The variable "count" is initialized to zero at the start of the program and then incremented by one (in the loop) each time that a prime is found. The line "count += 1" is does the same thing as "count = count + 1", that is, it increments the counter.
     
  12. Sep 18, 2012 #11

    uart

    User Avatar
    Science Advisor

    Thanks Borek. Hopefully that will give the OP some ideas on how to extend the program.

    There's one little problem you might like to fix though. With the array slice in the line "for p in primes[:int(math.sqrt(n))]", you're effectively testing for divisibility up to the prime whos index in the list is [itex]\sqrt{n}[/itex], however you should in fact be testing elements whos values are less than [itex]\sqrt{n}[/itex]. You see what I mean, the limit should be on the size of the prime, not on its index.

    Actually the code should still work, since the prime counting function [itex]\pi(n)[/itex] is asymptotic to [itex]n/\ln(n)[/itex]. And since [itex]\sqrt{n}/\ln(\sqrt{n}) \leq \sqrt{n} \leq n/\ln(n) [/itex] for n>2 then your code should always test enough primes and shouldn't exceed the list bounds. Though in general it will test more primes than needed.
     
    Last edited: Sep 18, 2012
  13. Sep 18, 2012 #12

    Borek

    User Avatar

    Staff: Mentor

    Good point, thanks. It is just a proof I am not thinking in correct categories.
     
  14. Sep 18, 2012 #13
    Oh okay, now I that I see that the 'count' is within the code indent for the 'if' value it IS self explanatory. That's cool. Thanks for the pointers.

    Borek, it is weird that you tried the same thing. Your code is much cleaner (not to mention further reaching) than mine, however.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Trying to teach myself Python
  1. Teaching myself C++? (Replies: 10)

  2. Python installation (Replies: 10)

Loading...