Archive

Posts Tagged ‘Project’

Python: Library Managment System -P6



Learning : Python, DataBase, SQlite
Subject: Create Simple Library Managment System

This will be the last post of Library Managment System, and we will start another project. So in this last part, we will write a final function to get some statistics & summaries about our Library such as :

  • Number of book in the library
  • Books without classifications
  • Books without Author
  • Books without ISBN
  • Books under each classification
  • Statistics about Authors
  • Statistics about Classifications

so we will add the function name in the Main Menu (in this case will take number 5), here is a screen shot of the menu.



So we will write some SQL commands using (SQlite), we will start with Books statistics and will NOT cover all commands, but all will be in the course code file in the Download page.

#Total Books in the Library
    c.execute ("select count() from books where b_id > 0") 
    books_count = c.fetchone()

 # Books without classifications

    c.execute ("select b_id from b_class where b_class_id > 0") 
    books_no_class = [item[0] for item in c.fetchall()]    


 # Authors without emails

    c.execute ("select count() from authors where a_email='' and a_id > 0") 
    auth_no_email = c.fetchall()


 # Authors without Social Media Account
 
    c.execute ("select a_id from sma where sma_id > 0") 
    sma_aid = c.fetchall()       
    a_in_sma = lambda sma_aid: [sma_id for each in sma_aid for sma_id in each]
    a_with_sma = list(dict.fromkeys(a_in_sma(sma_aid)))
    print('     Total Authors without Social Media Accounts: ',(auth_count[0] - len(a_with_sma)))  



Here is the run-time for sample data ..




By this point I will stop working on the “Library Managment System“, the goal of this series of articles was to build a Fast, Simple, Personal system. We did NOT cover some important issues like Validations or Exporting the data.



Enhancment:
Here are some points we can incluod in Version 02 of the LMS Application.

  1. Validations: We need to make sure the user Entering in right and good format as we expect. [Date format, Emails, ISBN and So-On]

  2. User Deletign: This is very Important, so if the user Deletes a Classification or Books or Authors we MUST do some modifications on other tables in the DataBase. [Very High Priority]

  3. Capitalization: To make sure we capitalize all user inputs like first character in each Names [Books name, Authors .. So-On].

  4. Search: Although we have this option in our Main-Menu, but I will not cover it in this Version due to time consumption.

  5. Date Export: This is an extra option we may have to Export the Data as Excel or DB-Backup file.
  6. Multi Libraries: In family using of the system, we can insert Books of other family members (Father Home Library, Brother or Cousin). So in that case we need a Full set of Functions to manage this part.
  7. .


[ NOTE ]
1. I am using Galaxy Tab and QPython3 App.
2. All the above codes are available in the Download Section/Page under the project name.
3. The application codes, Functions, Menus and other parts of the Application are subject of changes. In case of changes I will mention that.
4. This is a simple personal Library application, so I did not use any validations on Data Entry.

:: Library Managment System ::

Part 1 Part 2 Part 3 Part 4
Part 5 Part 6


To Download my Python code (.py) files Click-Here




Follow me on Twitter..

By: Ali Radwani

Python: Drawing Math Equations



Learning : Python and Math
Subject: Python Project to Draw a Math Equations

In the past week or so I saw a tweet from @matthen2 it was about drawing half circles on 99 points, the 99 points was distributed on a hidden circle, each line (or half circle) connecting x (a point on the circle) and it’s double, so point num 2 is connected to P num 4; (P3 to P6, P4 to P8, …) and so-on

This inspired me to write a Python app (code) to perform same action. Then I just upgrade the idea to draw any mathematical Equation. (Lets say simple mathematical Equations)

In our project, the user will enter the number of points and the starting circle radius, also I fond that we can do more by reducing the circle radius after each point, so i add this to the project.

Coding: We will write a function to collect the points in a list as [x,y], and returns the list. Then we pass each two points of (x1,y1) and (x2,y2) to another Function to draw a line between those points. In this version we will write the Equations as hard-code in our project.

So First Function will be the get_points() here the systems will ask the user to Enter some variables. We will collect the number of points P, the raidus of the circle circumference that points will be distributed On it’s, also we will ask the user if circle radius is fixed or decreased by a given factor.
Using mathematics we know that a circle has 360degree, so if we divide 360 over P we will have (if we can call it) the arc_angle. .. Here is the code for the function …

# Function to collect the x,y points

def get_points() :
  p = int(input('  Enter number of Points:  ')) # number of points.

  arc_angle = 360 / p
  circle_r = int(input('  Enter the Cricle Radius: ') )  
  fix_r = int(input('  Enter a number to reduce the Radius:'))
  
  #To return the x,y list of the points that we want to connect. 
  p_list = []
  t.goto(0,0)
  t.setheading(-90)
  
  for p in range (0,p+1) :

    t.goto(0,0)
    t.forward(circle_r)
    nx = t.xcor()
    ny = t.ycor()
  
     # If the user want to reduce the radius.
    circle_r = circle_r - fix_r
    p_list.append([nx,ny])
    t.right(-arc_angle)

  return p_list



By now, we have a list of points [x,y], and we will passing two points to another function def draw_line(x1, y1, x2, y2): to draw a line between the points. Very simple and easy Function …

# Function to draw a line

def draw_line(x1, y1, x2, y2):
  
  t.goto(x1,y1)
  t.pendown()
  t.goto(x2,y2)
  t.penup()


Now the tricky part, How to select the points?. To do this we assume we have an Equation (e1) and if we got any errors like (division by zero, or out of index) we will apply another Equation (e2), e1 and e2 will be hard-coded and each time we need to change it and run the application again to see the result. And to draw a line between the points based on e1 and e2 we will run a for loop …. Here is the code ..

# drawing the equations 

 

for d in range(len(p_list)-1) :
  
  e1 = d * 2
  e2 =  abs( len(p_list) - (d*2))

  try:
    draw_line(p_list[d][0], p_list[d][1],p_list[e1][0], p_list[e1][1])
  except:
    if e1 > len(p_list) :
      draw_line(p_list[d][0], p_list[d][1],p_list[e2][0], p_list[e2][1])


Here is some output




This is the end of this project, Do we need any upgrading in any part of it?



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python : Triangle Parameters



Learning : Python to Draw a Triangle
Subject: To get the Parameters of a Triangle

A week ago I start helping a friend in a mathematics geometric to draw a Triangle from Two points that represent the The Hypotenuse of a Triangle, then I deside to write a python project to Draw a triangle based on two given points (x1,y1) and (x2,y2) and to print it’s parameter (other sides and angles). We will use the Trinket.io as a Python interrapter and will draw with turtle library.

Project Details: The system will ask the user to Enter the coordinates of Two points To draw a Right Angle Triangle. In our Triangle, we will call the (x1,y1) as Point A, and (x2,y2) as Point C. From our starting poins we can calculate the distance between point A and point (B), also the length of Hypotenuse and the angels in the Triangle.

So, What we have:

tri_opposite = abs( y2 – y1 )

tri_adjacent = abs( x2 – x1 )

From a mathimatics triangle formula we know that:

Opposite^2 + Adjacent^2 = Hypotenuse^2

where: x^2 = square(x)

So:

tri_hypo = tri_opposite**2 + tri_adjacent**2

tri_hypo = math.sqrt(tri_hypo)

tri_hypo is the distance between point A and Point C (the opposite
side of the right angle)

Now the Angels:
As we know that in a triangle the summation on all inside angles is 180deg, and in a Right Triangle we will have a one fixed 90 degree angle (ABC), so the first thing we will work on calculating the Opposite angle (BAC).

From a Triangle math:

tri_opposite = abs( y2 – y1)

tri_adjacent = abs(x2 -x1)

the_deg (BAC) = inverse tan for (tri_opposite / tri_adjacent)

# get the inverse of Tan

the_ang = math.degrees(math.atan(the_deg))

Now, lets do some coding ..

First thing we will import two libraries turtle and math, also we will do some setting for our turtle. … Here is the code ..

# Turtle setting


import turtle, math
# turtle_setting 
t = turtle.Turtle()
t.penup() 
t.shape("non")
#t.speed(9)
t.speed('fastes')
#t.visible = False

t.hideturtle()



Then we will write a code to draw a ‘Gray’ coordinates cross lines for our project. Here is the code for it ..



def the_cross() :
     # To draw the cross represents the coordinate.
    t.penup()
    t.pencolor('gray') 
    t.goto(-200,0)
    t.setheading(0)
    t.pendown()
    t.forward(400)
    t.penup()
    t.goto(0,200)
    t.setheading(90)
    t.pendown()
    t.forward(-400)
    t.penup()
    t.goto(2,0)
    t.pendown()
    t.circle(2)
    t.penup()
    t.goto(0,0)
    t.setheading(0)

# calling the function 
the_cross() 


Now we will write the main function code, First we will ask the user to enter the x,y for two points, then we will do our calculations to get other Triangle parameters and angles, finally we will draw the Triangle. .. Here is the code..



def draw_triangle(x1, y1, x2, y2) :

# draw the Triangle. 
    style = ('Courier', 20)   # font style.
    t.penup()
    t.goto(x1,y1)
    t.setheading(0)
    t.pendown()
    t.circle(1)  # To draw small circle on point A.
    t.write('A',font = style)  # To write A next to the point.
    t.forward((x2-x1))
    x3 = t.xcor() # here is the x for point B
    y3 = t.ycor() # here is the y for point B

    t.right(-90)
    t.forward((y2-y1))
    t.write('C',font = style)  # To write C next to the point.
    t.goto(x2,y2)
    t.setheading(0)
    t.pendown()
    t.circle(1)  # To draw small circle on point C.
    t.penup()
    t.goto(x3,y3)
    t.pendown()
    t.circle(1)  # To draw small circle on point B.
    t.penup()
    t.setpos(x3-15,y3-15)
    t.write('B',font = style)  # To write B next to the point.


    # To calculate the angle of BAC using Triangle Math Equations. 
    tri_opposite = abs( y2 - y1)
    tri_adjacent = abs(x2 -x1)
    the_deg = tri_opposite /  tri_adjacent

    # get the inverse ot Tan using Triangle Math Equations.  
    the_ang = math.degrees(math.atan(the_deg)) #atan(x) is the inverse of math Tan function.

    t.goto(x1,y1)

    # To correct the rotation angle based on it's coordinates.
    if (x1 > x3) and (y2 > y1) :
      rotation = the_ang - 180

    elif (x1  y1):
      rotation =  360 - the_ang

    elif (x1 > x3) and  (y2 < y1) :
      rotation =  180 - the_ang

    elif (x1 < x3) and  (y2 < y1) :
      rotation =   the_ang - 360

    #t.right(rotation)
    #t.pendown()
# From using Triangle Math Equations, we know that Hypotenuse^2 = Opposite^2 + adjacent^2.  
    
    tri_hypo = tri_opposite**2 + tri_adjacent**2
    tri_hypo = math.sqrt(tri_hypo)
    t.right(rotation)
    t.pendown()
    t.forward(tri_hypo)
    t.penup()

    print('\n  The Triangle Information:')
    print('  Point A= ({},{})'.format(x1,y1))
    print('  Point B= ({},{})'.format(x3,y3))
    print('  Point C= ({},{})'.format(x2,y2))
    print('  Adjacent',tri_adjacent)
    print('  Opposite',tri_opposite)
    print('  Hypotenuse',tri_hypo)
    print('  Angle: ABC = 90')
    print('  Angle: BAC = ',the_ang)
    print('  Angle: ACB = ',180 - the_ang - 90)


Finally, we need to call the function and pass the two point to it, to do this first we will ask the user to Enter the Two Points and we will make sure that the points are not the same.. Here is the code ..

# calling the draw_triangle function ..
 
print('\n   To draw the Triangle you need to Enter Two Points as X,Y for each one.')
x1 = int(input('   Enter x for First point: '))
y1 = int(input('   Enter y for First point: ')) 
x2 = int(input('   Enter x for Second point: '))
y2 = int(input('   Enter y for Second point: ')) 
 
if (x2==x1) or (y2==y1) : 
   print('  Your Points are not valid, (x1,x2) or (y1,y2) can't be equal ')
else :
   draw_triangle(x1, y1, x2, y2)




To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: Cooking App P-8



Learning : Python, Data-Base, SQlite
Subject: Writing a Cooking Application

RECIPES MENU: Show Recipe During writing all functions of the application I notes that my “Show Recipe” need to be updated, so in this post we will do some changes on “def show_all_rec(opt)” function.

First, we will change the if opt ==”name” to list all the Recipes Name with ID’s and ask the user to Enter a Recipe ID to show its information.
Here is the code ..

 # Changes on show_all_rec(opt) - if opt =="name"

if opt =="name" :
        #First we will list down all Recipes Names.
        c.execute("select r_id,r_name from recipes where r_id > 0")
        for each_r_name in c.fetchall():
            print(' ID:',each_r_name[0], ' Name:',each_r_name[1])
            
        get_rec_id = input ('\n Enter the Recipe ID you want to read: ')
        # Get the Recipe information based on ID.
        c.execute("select * from recipes where r_id ={}".format(get_rec_id))
        for each_basic in c.fetchall():
            print('\n  ID: ',each_basic[0])
            print('  Name: ',each_basic[1])
            print('  Date: ',each_basic[2])
            print('  Type: ',each_basic[3])
            print('  Other: ',each_basic[4])

            print('\n  The Recipe Ingredients: ')
            # Get all Recipe Ingredients.
            get_sql = '''
                    select
                        i_name

                    from
                    ingredients_list

                    INNER JOIN rec_ingredient ON ingredients_list.i_l_id = rec_ingredient.i_l_id
                    where rec_ingredient.r_id = {}

                    '''
            c.execute(get_sql.format(each_basic[0]))

            st = 1
            for each in c.fetchall():
                print('  ',st,': ',each[0])
                st = st + 1

            print('\n\n  Cooking Steps: ')
            # Get the Cooking Steps. 
            c.execute("select * from recipes_steps where recipes_steps.r_id = {}".format(each_basic[0]))
            st = 1
            for each in c.fetchall():
                print('\n    Step-',st,': ',each[2])
                st = st + 1

            print('\n ---------------------------------------------')


Here is the out-put screen :

First we have the Menus, we select 1,1,1 to
get “Show Recipe By Name”


Here is the List of All Recipes and we will enter
the ID of the one we want to see.


Here is the Recipes Information.


Notes That 1. We don’t have any Ingredient (we did not add any) so in coming post we will develop the Edit function to add some Ingredient and change/Update the Recipe Information.
2. We are not using any Validations, so if we enter any dummy data for Date the system will accept it.
3. We are not using any (avoiding Error code) such as Try…except.



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python Project: Ant Escaping Path

August 29, 2019 Leave a comment


Python simulation project
Python, Graphics and simulation

In this project we assume that we have a square pad and we put an ant in the center of this pad, we let the ant to walk, once it reach any eadgs of the square we move it with our hand to the middle again, say we doing this for x times and each time we colored the ant foots with gray level (light to dark) color. Our project is to write a code to simulate this task (ant movement). 

Enhancement: Here are some enhancement ideas:
1. We can use the Pi or Golden Ratio for the variables.
2. Also we can set a memory facto so with each time we move the Ant to the center the memory will increase so it may use the same path.
3. For the memory, we can set a position (x,y) as a food, and each time it reach the food it’s memory will increase.


The Code

# Create in 27/8/2019 .

import turtle
import random

screen = turtle.Screen()
screen.setworldcoordinates(-700,-700,700,700)
screen.tracer(5)

t1=turtle.Turtle()
t1.speed(0)
t1.penup()

# colors varibles
# r=240, g=240, b=240 is a light gray color

r=240
g=240
b=240
t1.pencolor(r,g,b)

cf = 3 # color increasing factor
ff = 0 # ant forward moving factor
#screen.bgcolor(“black”)

def rand_walk(x,the_t):

the_t.pendown()

# The color will be darker each time

the_t.pencolor(r-(x*cf),g-(x*cf),b-(x*cf))

the_t.forward(20+(ff*x))

def ant_walk ():

x = 1

while x < 7 : # Moving the Ant to the center 7 times

rand_walk(x,t1)

if random.randrange(1,100) %2:

t_ang = random.randrange(10,45)

t1.right(t_ang)

else:

t_ang = random.randrange(10,45)

t1.left (t_ang)

# if the ant reach the square boards then we move it to the center.

if (t1.xcor() > 650 ) or (t1.xcor() 650 ) or (t1.ycor() < -650 ):

t1.penup()

t1.goto(0,0)

x = x + 1

# Calling the Function
ant_walk()


Here is an GIF file



To Download my Python code (.py) files Click-Here




Follow me on Twitter..





Python: Orders Manager P2

August 22, 2019 Leave a comment


Orders Managment System
Subject: Main Menu and creation of the data file – P2

First thing we will talk about the menu, in this post we will cover the Main Menu and the user choice. Also we will add some validation.

Main Menu: Here is a list of what we will have in the main menu with some descriptions for each choice.
Load File: We will name the file as “orders_data.csv” so once we start the application the system will check if the file exist or not, if Yes then the application will load it automatically as DataFrame (df) if not thats mean you are running the app for the first time, so we will go through file creating process.

Show Data: In this option we will have another sub menu page having:
1. Show all data.
2. Show sample data.
3. Show last 5 records.

Sort: Here we will have sorting as columns that we have, the user will select a column.

Search: We can here search for an order by Date, Price, Quantity or details, also we will do groping for the data.
Missing Data: To show us how many missing data we have so we can fill them.
Add New Order: To add new order to the system.
Edit a Record: To Edit/change a record.
Delete a Record: To delete a record from the DataFrame.
Save: To save what ever you do to the DataFrame.

The Main Menu

def the_menu ():

print(‘\n ::—–{ The menu }—-::’)

print(‘1. Create New csv File’)

print(‘2. Show Data’)

print(‘3. Sort.’)

print(‘4. Search.’)

print(‘5. Missing Data’)

print(‘6. Add New Record.’)

print(‘7. Edit a record.’)

print(‘8. Delete a Record.’)

print(’9. Save the File.’)

return input(‘\n Select from the menu (”q” to quit): ‘)


Main while loop: In the application body we will use a while loop to control the user input and run the function he select. Unlike what we did In the zoo managment system, we will add a validation on the user input as:

Validation:
1. If the user enter any thing else than numbers (1 to 9) or ([q – Q] for quit) nothing will happen.
2. If the user select (q to quit) then we will ask if he want to save before Exit.



Here is the code …

Main while loop
# calling the menu
user_enter = the_menu()

”’
Validation: If the user enter any thing else than numbers
or (q for quit) nothing will happen.
”’
while user_enter !=’q’ or ‘Q’ :

if user_enter in [‘q’,’Q’] :

print(‘\n You select to Exit the application.’)

save_it = input(‘\n Do your want to save your work/changes [y or n] ? ‘)

if save_it in [‘y’,’Y’]:

save_the_df (df)

break

elif user_enter not in [‘1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9’] :

user_enter = the_menu()

else:

user_choice(user_enter)

user_enter = the_menu()


Here is a screen shot for the code..




In this post we cover the Main Menu and the main while loop we need to call the functions, in the coming post we will create the data file and Adding new record.



Follow me on Twitter..





Python: Pandas Lesson 11

August 15, 2019 2 comments


Learning : Pandas Lesson 11
Subject: Zoo Management System – P5

In this post we will cover another three functions, let’s start.

Missing Data: A commun problems we will face in any data file is Missing data, and if we are doing data analysis this may ledd us to a real problem. In this section we will cover only the missing data and will not go through any filling techniques.

Missing Data Report

def missing_data(df):

clear() # To clear the terminal.

print(‘\n\n *** Missing Data Report ***\n’)

print(‘ There are {} rows and {} columns.’.format(df.shape[0],df.shape[1]))

print(‘\n Number of missing data in each columns are:\n’)

total_miss = 0 # Counter

for each in df:

print(‘\n We have {} missing data in {} column.’.format(df[each].isnull().sum(),each))

total_miss = total_miss + df[each].isnull().sum()

print(‘\n Total missing data :’,total_miss)

print(‘\n The missing data represent {}% of the DataFrame.’.format((df.size*total_miss)/100))

input(‘\n\n\n\n ** Press any key to continue .. . . ‘)

This is a very simple missing data report, but doing the job for-now, we cover some part of missing data in lesson 5 read it Here.

Add New Record: I divide the editing function into three parts or three functions, Add new record, Edit a record and delete a record.
First we will work on Add New Record, from the name we know that this function will allow the user to add a record to the DataFrame, first we will get all columns in the dataframe, also we will get the maximum value in the ID column and increase it by one, then we will ask the user to enter the data for each column, and we are assuming that the user will (or MUST) enter a valid data since we agree that we will not have any validation test in this version of the application, also if the user just press ‘Enter’ thats mean NA data so we will add NaN to the field.
So let’s start..

Add New Record
def add_new_record(old_df):

clear() # To clear the terminal.

# First we will fitch the columns from the df

col_list = []

for each in old_df.columns :

col_list.append(each)

print(col_list)

# Get max id and increase it by 1

next_id = old_df[‘id’].max()+1

new_row={}

# let user enter the new record.

print(‘\n Enter the data for each field then press Enter.\n’ )

print(‘ If you just press Enter NaN will be entered.’)

for each in col_list:

if each !=’id’:

print(‘ Enter data for ‘,each)

new_row.update({each:(input(‘ : ‘))})

new_row.update({‘id’:next_id})

old_df = old_df.append([new_row])

for each in col_list :

if (old_df.loc[old_df[‘id’] == next_id, each][0]) ==”:

(old_df.loc[old_df[‘id’] == next_id,[each]]) = float(‘NaN’)

print(‘\n New Record added successfully..\n’)

# print out last 5 rows to show the new record.

print(‘\n The new record in the df..\n ”,old_df.tail(5))

global df # Reset the df as global variable

df = old_df

input(‘\n\n\n\n ** Press any key to continu .. . . ‘)

Save : At this point we will jump to the last function, simply after adding data to our DataFrame we need to keep this change, we need to save the new record so we can retrieve it next time we run the application. So to do this we will re-write the csv file again.

Save the DataFrame

def save_the_df (df):

clear() # To clear the terminal.

file_name=’data_file_zoo.csv’

df.to_csv(file_name, encoding=’utf-8′, index=False)

print(‘\n File saved .. ‘)

input(‘\n\n\n\n ** Press any key to continue .. . . ‘)



Now, if we close the application then re-open it again we will have the new records that we add. We just save the file and will not have any option to rename it.

In Next Post.. in coming post we will cover deleting and editting functions, also I will upload the full code file to the portal so any one can download it as python file.




:: Pandas Lessons Post ::

Lesson 1 Lesson 2 Lesson 3 Lesson 4
Lesson 5 Lesson 6 Lesson 7 Lesson 8
Lesson 9 Lesson 10 Lesson 11



Follow me on Twitter..




Python: Powerful Digit Counts



Python: Powerful Digit Counts
Problem No.63 @ ProjectEuler
Completed on: Completed on Thu, 11 Jul 2019, 17:21

Just to make my post simple, i am quoting from ProjectEuler page

The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power.
How many n-digit positive integers exist which are also an nth power?


Then, we need to find the loop that will solve this, and we did..



The Code:



# P63
# Power digit count
# Solved
# Completed on Thu, 11 Jul 2019, 17:21

c = 0
for x in range (1,50):

for p in range (1,50) :

if (len(str(x**p)) == p ):

c += 1

print(‘\n We have {} n-digit integers exist which are also an nth power.’.format(c))






Follow me on Twitter..



Python: Pentagon Numbers



Python: Pentagon Numbers
Problem No.44 on ProjectEuler
Completed on: Thu, 11 Jul 2019, 18:37

This problem talking about the Pentagonal numbers and gives us a formula. Using that formula for a certain range of numbers, the generated sequence showing that P4 + P7 = 22 + 70 = 92, 92 is the P8, but if we subtracting (P7 – P4) = 70 – 22 = 48, 48 is not in the generated sequence of pentagonal numbers, so 48 is not pentagonal.

The task here is to find the pair of pentagonal Pj,Pk which their sum and difference are Pentagonal D = Pk – Pj is minimised.(we need to get the D).



The Code:




# P44
# Pentagon Numbers
# Solved
#Completed on Thu, 11 Jul 2019, 18:37


def pn(n):

return int(n*(3*n-1)/2)

pn_list=[]

for n in range (1000,3000) : # I start increasing the range step by step.

pn_list.append(pn(n))

we_found_it = False
for x in range (0,len(pn_list)-1) :

px= pn_list[x]

for y in range (x+1,len(pn_list)-1) :

py= pn_list[y]

if (px+py) in pn_list:

if (py-px) in pn_list:

print(‘\n We found one ‘,px,py,’D = ‘,py-px )

we_found_it = True

if we_found_it : break

print(‘Done’)






Follow me on Twitter..



Python is_prime and time consuming

July 11, 2019 4 comments


Python: is_prime and time consuming
Function enhancement

Once i start solving projectEuler problems i notes that i need the prime numbers in most of cases, so I wrote a function called ‘is_prime’ and it works fine. Some time just to get all the primes in a given range takes some seconds, seconds in computer time means waiting a lot. With some other problems that we need to get the prime in large numbers my function looks slow, since I am not deep in math I search the net for a better way to get the primes or to check if a given number is prime or not.

Definition A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. wikipedia.org.
So as I understand a prime number is not dividable by any other numbers, so my is_prime function is taking a number let’s say n= 13, and start a loop from 2 to n=13 if we fond a number that divide 13 then 13 is not a prime.

Here is the code:

def is_prime1(num):

for t in range (2, num):

if num % t == 0 :

return False

return True

The function is working fine and we can get the prime numbers, but as I mention above, if we have a large number or a wide range, this will take some time. After searching the web, I found some facts regarding the Prime Numbers:



1. The only even prime number is 2. (So any other even numbers are not prime)
2. If the sum of a number digits is a multiple of 3, that number can be divided by 3.
3. No prime number greater than 5 ends in/with 5.


OK, now I can first cut any range to half by not going through even numbers (if even false). Then, I will see if the number end with 5 or not (if end with 5 false),last I will do a summation of the digits in the number if the sum divide by 3 (if yes false), and if the number pass then i will take it in the loop from 5 to n, and if any number divide it we will return false.



Here is the code after the enhancement:

def is_prime2(num):

if num %2==0 : # pass the even numbers.

return False

num_d= str(num) # if last digits is 5, then not prime

t= len(num_d)

if (num_d[t-1]) == 5 :

return False

tot = 0

for each in str(num):

tot = tot + int(each)

if tot % 3 == 0 : # if digits sum divide by 3, then not prime

return False

for t in range (3, num, 2):

if num % t == 0 :

return False

return True

I test both function on my laptop, for different number ranges, and use the time function to see the time delays with each one. Here is the results. If any one know better way to do this please drop it here. Or on My Twitter.





Follow me on Twitter..