Trying to teach myself Python

  • Thread starter mateomy
  • Start date
  • Tags
    Python
In summary: The "count" function simply keeps track of the number of times a given integer appears in the input. So, for example, if you input "2", "3", and "5", the count will be "2", "3", and "5", respectively.
  • #1
mateomy
307
0
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 xI'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:
Technology news on Phys.org
  • #2
Hey mateomy.

Have you considered saving results to some array and then processing the array later?
 
  • #3
chiro said:
Hey mateomy.

Have you considered saving results to some array and then processing the array later?

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...
 
  • #4
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).
 
  • #5
Great! I'll take a look at that.

Thank you very much. I'll post back with new questions.
 
  • #6
I'm confused how I'd get this output piped into an array.
 
  • #7
mateomy said:
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.

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:
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:
  • #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?
 
  • #9
Funny, last year I tried to learn something about Python, and program finding n primes was the first thing I did:

Code:
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.
 
  • #10
mateomy said:
How does that count function work exactly?
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.
 
  • #11
Borek said:
Funny, last year I tried to learn something about Python, and program finding n primes was the first thing I did:

Code:
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.

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:
  • #12
uart said:
you're effectively testing for divisibility up to the prime whos index in the list is [itex]\sqrt{n}[/itex]

Good point, thanks. It is just a proof I am not thinking in correct categories.
 
  • #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.
 

What is Python and why should I learn it?

Python is a high-level, interpreted programming language used for a wide range of applications such as web development, data analysis, and artificial intelligence. It is known for its simplicity and readability, making it a popular language for beginners. Learning Python can open up job opportunities and improve problem-solving skills.

How do I start learning Python?

There are many resources available for learning Python, including online tutorials, books, and courses. It is important to choose a method that works best for your learning style. It is also recommended to start with the basics, such as syntax and data types, before moving on to more complex concepts.

Is Python a difficult language to learn?

Python is generally considered to be one of the easier programming languages to learn. Its simple syntax and extensive libraries make it beginner-friendly. However, like any new skill, it may take time and practice to become proficient in Python.

What are the benefits of teaching myself Python?

Teaching yourself Python allows you to learn at your own pace and focus on the areas that interest you the most. It also gives you the flexibility to choose your own learning resources and tailor your learning experience to your needs.

How can I apply my knowledge of Python in real-world situations?

Python is used in a variety of industries, including web development, data analysis, machine learning, and scientific computing. By learning Python, you can gain skills that are in high demand and apply them to real-world problems and projects.

Similar threads

  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
4
Views
863
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
2
Views
905
  • Programming and Computer Science
Replies
1
Views
766
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
2
Replies
55
Views
4K
  • Programming and Computer Science
Replies
7
Views
403
Replies
17
Views
7K
  • Programming and Computer Science
Replies
5
Views
4K
Back
Top