[Tutor] Generate Prime Numbers

2015-05-29 Thread Mirage Web Studio

Hello,

Below is a sample code i created.

Can i better it any way?

Thanks

George

---

import time
start_time = time.time()


def IsDivisibleBy3(number):#string variable
v=0
for c in number:
v=v+int(c)
if v%3==0:
return True
else:
return False

def IsDivisibleBy7(number):#string variable
last=int(number[-1])*2
length=len(number)-1
tnumber=number[0:length]
tnumber=int(tnumber)-last
if tnumber%7==0:
return True
else:
return False


def IsDivisibleBy9(number):#string variable
v=0
for c in number:
v=v+int(c)
if v%9==0:
return True
else:
return False

def IsPrime(number):
l=len(number)
if number[l-1] in ['2','4','5','6','8','0']:
#print("retuning base false")
return False

if IsDivisibleBy3(number):
 #print("retuning 3 check false")
  return False

if IsDivisibleBy7(number):
  #print("retuning 7 check false")
  return False

if IsDivisibleBy9(number):
  #print("retuning 9 check false")
  return False

number=int(number)
half=(number/2)+1
i=7
while half>=i:
if number%i==0:
return False
i=i+1
return True


primelist=[]

for i in range (11,20,2):
number=str(i)
print "checking ",i

if IsPrime(number):
primelist.append(number)

print ("primes",len(primelist),primelist)


print("--- %s seconds ---" % (time.time() - start_time))

---
This email has been checked for viruses by Avast antivirus software.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generate Prime Numbers

2015-05-30 Thread Mirage Web Studio


On 2015-05-29 11:18 PM, Alan Gauld wrote:

On 29/05/15 16:28, George wrote:


Below is a sample code i created.

Can i better it any way?


Of course. There is always improvements that can be made.
But in your case there are quite a few!


def IsDivisibleBy3(number):#string variable
 v=0
 for c in number:
 v=v+int(c)
 if v%3==0:
 return True
 else:
 return False


def IsDivisibleBy3(number):#string variable
return not int(number) % 3


def IsDivisibleBy7(number):#string variable


See above, but maybe better still

def isDivisibleByN(number, N):
   return not int(number)%N


def IsPrime(number):


Google for the "sieve of eratosthenes"
Or look it up on wikipedia.

That will give one of several possible
improvements to your algorithm.


primelist=[]

for i in range (11,20,2):
 number=str(i)
 print "checking ",i

 if IsPrime(number):


Note, you are starting with a number, then converting
it to a string then in your functions converting it
back to a number.
That's crazy!

Also where do you store the primes less than 11?
ie. 1,3,5,7

HTH


Hello,

I thank u all for the replies.  I have checked  sieve of Eratosthenes 
and have at first devised a solution using class-object, thinking it 
easier, but it proved to be slower than my basic algorithm which i 
submitted earlier,  results were my algorithm processed 100 thousand 
numbers in 80 or so sec but class based algorithm produced same result 
in about 230 sec. After putting some thought i used dict for a change 
with the sieve method and am able to produce primes for 1 million nos in 
about 10 sec, which is better than both earlier algorithms.  I am 
submitting both.


My query is does using classes slowed it or the python hardcoded 
algorithm for dicts was better?

and
if you had to implement the sieve algorithm how would u have done it.

Thank u


George

-
class based algorithm
-

import time

starttime=time.time()

class Number:
def __init__(self,number,p=None,n=None):
self.no=number
self.marked=None
self.p=p
self.n=n


node=Number(2,None,None)
start=node

counter=1
for i in range(3,11):
counter+=1
newnode=Number(i,node)
node.n=newnode
node=newnode

node=start


while start != None:
if start.marked==True:
start=start.n
continue
else:
newprime = start.no
print ("\nNewPrime",newprime,"\nMarking no:")
tmpnode=start
while tmpnode !=None:
for i in range (newprime):
tmpnode=tmpnode.n
if tmpnode==None:
break
if tmpnode==None:
break
#print ( tmpnode.no, end=" ")
tmpnode.marked=True
start=start.n

print ("primes")
counter=0
while node!=None:
if not node.marked:
counter+=1
print(node.no)

node=node.n

print("--- %s seconds ---" % (time.time() - starttime), counter)


---
dict based algorithm
-



import time

starttime=time.time()

max=600

nodict={}

for i in range(2,max):
nodict[i]=0

for no in sorted(nodict.keys()):
x=no+no
while xhttp://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generate Prime Numbers

2015-06-10 Thread Mirage Web Studio



On 2015-05-31 5:04 AM, Alan Gauld wrote:

On 30/05/15 19:14, George wrote:


Excuse me please for replying late.

I got lists to use the method and it is more efficient and faster. 
(Takes about 10 secs to process first 50 mil numbers)


But now another problem i seem to notice that only 1 core of my amd 
Athlon X2 4core processor is being used.  I suppose if all the four 
cores are simultaneously used then the programme might run even faster.  
Is there a way.


Kindly guide me.

Thank You.

George




---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generate Prime Numbers

2015-06-11 Thread Mirage Web Studio



On 2015-06-11 12:38 AM, Laura Creighton wrote:

In a message of Wed, 10 Jun 2015 23:11:36 +0530, George writes:



On 2015-05-31 5:04 AM, Alan Gauld wrote:

On 30/05/15 19:14, George wrote:

Excuse me please for replying late.

I got lists to use the method and it is more efficient and faster.
(Takes about 10 secs to process first 50 mil numbers)

But now another problem i seem to notice that only 1 core of my amd
Athlon X2 4core processor is being used.  I suppose if all the four
cores are simultaneously used then the programme might run even faster.
Is there a way.

Kindly guide me.

Thank You.

George

If you want, you can use the STM branch of the pypy interpreter.  This
is a Python without the global interpreter lock.  One of the tests
we did was, surprise, to calculate prime numbers.

See the blog post here:
http://morepypy.blogspot.se/2014/11/tornado-without-gil-on-pypy-stm.html

Laura


Thank u,

PYPY is indeed very fast and as expected is using all the cores.  I 
think i have found what i was looking for.  I saw that stm branch is 
only for linux.  Windows binaries if available would be of great help.


Thank u all for interest in replying.


George.

---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Problem reading large files in binary mode

2014-06-12 Thread Mirage Web Studio


Hello

I am new to python programming.  while trying it out i find that in my
code file io.read is not reading large files particularly over 1 gb. my
code is posted below.  i am working on python 3.3 on windows with ntfs
partition and intel corei3 ram 3gb. the execution always stops saying
error with py.exe but idle editor and idle window remains open.

thank you
George

##function module generates md5 for given file data

import hashlib
import io
import os

def filemd5(file="g:\\filelargerthan1gb.iso"):
#print ("reached here")
#print ("File for processing %s",file)

try:
filelen=os.path.getsize(file)
except PermissionError:
print("Don't have permission for ",file,".\tTry running as
administrator")
return ''

if filelen>1073741824:
print ("file len greater than 1gb.\nNot hashing")
return ''



try:
f=open(file,'rb', buffering=0)   #i have tried without
buffering also
except PermissionError:
print("Don't have permission for ",file,".\tTry running as
administrator")
return ''


try:
#print ("Readding")
fcontents=f.read()
#print ("Read successfully")
hashvalue=hashlib.md5(fcontents).hexdigest()
#print ("md5 successfully")
except:
hashvalue=''
print ("Error during reading md5")

f.close()

#print (hashvalue)
return hashvalue

filemd5()




---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem reading large files in binary mode

2014-06-13 Thread Mirage Web Studio

Try reading the file in chunks instead:

CHUNKSIZE = 2**20
hash = hashlib.md5()
while True:
chunk = f.read(CHUNKSIZE)
if not chunk:
break
hash.update(chunk)
hashvalue = hash.hexdigest()


Thank you peter for the above valubale reply.  but shouldn't read() by itself 
work because i have enough memory to load it or should it be a bug.

thank you

george


---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem reading large files in binary mode

2014-06-13 Thread Mirage Web Studio

Thank you, i will keep all that in mind.

My python version is 3.3.5

George

On 13-06-2014 16:07, Peter Otten wrote:

Mirage Web Studio wrote:


Try reading the file in chunks instead:

CHUNKSIZE = 2**20
hash = hashlib.md5()
while True:
  chunk = f.read(CHUNKSIZE)
  if not chunk:
  break
  hash.update(chunk)
hashvalue = hash.hexdigest()


Thank you peter for the above valubale reply.  but shouldn't read() by
itself work because i have enough memory to load it or should it be a bug.

I think you are right. At least you should get a MemoryError (the well-
behaved way of the Python interpreter to say that it cannot allocate enough
memory) while your description hints at a segmentation fault.

A quick test with the Python versions I have lying around:

$ python -c 'open("bigfile", "rb").read()'
Traceback (most recent call last):
   File "", line 1, in 
MemoryError
$ python3.3 -c 'open("bigfile", "rb").read()'
Segmentation fault
$ python3.3 -V
Python 3.3.2+
$ python3.4 -c 'open("bigfile", "rb").read()'
Traceback (most recent call last):
   File "", line 1, in 
MemoryError

So the bug occurs in 3.3 at least up to 3.3.2.

If you don't have the latest bugfix release Python 3.3.4 you can try and
install that or if you are not tied to 3.3 update to 3.4.1.

Note that you may still run out of memory, particularly if you are using the
32 bit version.

Also it is never a good idea to load a lot of data into memory when you
intend to use it just once. Therefore I recommend that you calculate the
checksum the way that I have shown in the example.

PS: There was an email in my inbox where eryksun suggests potential
improvements to my code:


You might see better performance if you preallocate a bytearray and
`readinto` it. On Windows, you might see even better performance if
you map sections of the file using mmap; the map `length` needs to be
a multiple of ALLOCATIONGRANULARITY (except the residual) to set the
`offset` for a sliding window.

While I don't expect significant improvements since the problem is "I/O-
bound", i. e. the speed limit is imposed by communication with the harddisk
rather than the Python interpreter, you may still find it instructive to
compare the various approaches.

Another candidate when you are working in an environment where the md5sum
utility is available is to delegate the work to the "specialist":

hashvalue = subprocess.Popen(
 ["md5sum", filename],
 stdout=subprocess.PIPE).communicate()[0].split()[0].decode()

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] usage difference between tabs and spaces

2014-09-09 Thread Mirage Web Studio


Hello,

I am not an advanced programmer, but am very good with keyboard and find
using tabs for syntax and formatting very helpful. But in this list and
other python documentation i have repeatedly seen people recommending
use of spaces.

I know that i can use any of them and use tabs as my preference.  But i
would like to understand why hitting the poor keyboard 4/8/12 times is
preferred than just hitting it 1/2/3 times.

Thank you

George



---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] usage difference between tabs and spaces

2014-09-09 Thread Mirage Web Studio

Thank you and everybody else for the reply.

I am using pycharm and i have found the way to produce four spaces for 
single tab key press.



George



On 10-Sep-14 2:32 AM, Danny Yoo wrote:

I am not an advanced programmer, but am very good with keyboard and find
using tabs for syntax and formatting very helpful. But in this list and
other python documentation i have repeatedly seen people recommending
use of spaces.



Usually, you want to match the style used by the majority of the
community.  According to the community PEP-8:

 http://legacy.python.org/dev/peps/pep-0008/#tabs-or-spaces

it's spaces, and in particular, four spaces:

 http://legacy.python.org/dev/peps/pep-0008/#indentation

The overriding reason, as I understand it, is not technical, but
rather social: influential folks used that indentation level, the
style spread, and the community generally followed that style.  Now
it's the majority.


There is value in coming to terms with this: there are bigger, more
important issues out there.

Like big-endian vs little-endian.  :P



I know that i can use any of them and use tabs as my preference.  But i
would like to understand why hitting the poor keyboard 4/8/12 times is
preferred than just hitting it 1/2/3 times.


You can use an editor that will do the right thing, but still let you
use your tab key the way you want.  What editor are you using now?


Best of wishes!



---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help please

2018-10-10 Thread Mirage Web Studio
You are using the same variable name twice.
You may use "rivers" for the dict and "river" for values.
Also use descriptive names for variables. For eg if you correct the above
mistake, the next one will be this line

for rivers in rivers.values():
print (rivers)


and sorry for top positing.


On Wed 10 Oct, 2018, 12:38 Michael Schmitt, 
wrote:

> To whom it may concern:
>
>
> I am trying to teach myself Python and ran into a problem. This is my code
>
>
> # name of rivers and country
>
> rivers = {'nile' : 'egypt', 'ohio' : 'US', 'rhine' : 'germany' }
>
> # prints river name
> for rivers in rivers.keys():
> print (rivers)
>
> #prints country
> for rivers in rivers.values():
> print (rivers)
>
> # prints statement " The (river) is in the country of (country)
> for rivers in rivers:
> print ("The " + rivers.keys() + "is in the country of " +
> rivers.vaules())
>
> I am getting the following error
>  for rivers in rivers.values():
> AttributeError: 'str' object has no attribute 'values'
>
> Thanks for the help.
>
> Sincerely,
>
> Michael S. Schmitt
>
>
> [
> https://ipmcdn.avast.com/images/icons/icon-envelope-tick-round-orange-animated-no-repeat-v1.gif
> ]<
> https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail&utm_term=icon>
>   Virus-free. www.avast.com<
> https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail&utm_term=link
> >
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor