Regning med Python - noen eksempler

Pedagogisk programmeringsspråk
KBleivik
Site Admin
Innlegg: 30
Registrert: fre mar 29, 2013 7:52 pm

Regning med Python - noen eksempler

Legg innav KBleivik » fre mar 29, 2013 10:41 pm

Her er noen eksempler på Pyhton kode som kan klippes direkte inn i et IDLE editoren, lagres som .py fil og kjøres:

Eksempel 1. Fibonacci tallene

Kode: Velg alt

# fibonacci generator code from diveintopython.org

def fibonacci(max):
    a, b = 0, 1
    while a < max:
        yield a
        a, b = b, a+b

for n in fibonacci(100):
    print (n),
print()
enter=input('Hit enter ')


Eksempel 2. Python er relativt rask og greier store tall

Kode: Velg alt

# fibonacci generator code from diveintopython.org

def fibonacci(max):
    a, b = 0, 1
    while a < max:
        yield a
        a, b = b, a+b

for n in fibonacci(1000000000000000000000000000000000000000000000000000000):
    print (n),
print()
enter=input('Hit enter ') #Prevent output window from closing.


Eksempel 3. Python2 henter raskt informason fra et nettsted

Kode: Velg alt

# Get information from the internet.
#
#
# ---------------------------------------------------------------------------------------------------
#
# Opens the webdocument with The First 10,000 Primes, read the file and print the
# content. It functions for Python version 2.5, but not for version 3.1.2
#
# ---------------------------------------------------------------------------------------------------
#
import urllib
file = urllib.urlopen('http://primes.utm.edu/lists/small/10000.txt')
primes = file.read()
print (primes)


Eksempel 4. Tilsvarende program for Pyhon 3.+

Kode: Velg alt

# Python 3 program
#

# ---------------------------------------------------------------------------------------------------
#
# Opens the webdocument with The First 10,000 Primes, read the file and print the
# content.  For version 3.1.2.  Version 2.5 is commented out.
# Reference:  http://diveintopython3.org/porting-code-to-python-3-with-2to3.html
#
# ---------------------------------------------------------------------------------------------------
#
#import urllib
#file = urllib.urlopen('http://primes.utm.edu/lists/small/10000.txt')
#primes = file.read()
#print (primes)

import urllib.request
file = urllib.request.urlopen('http://primes.utm.edu/lists/small/10000.txt')
primes = file.read().decode("utf8")

my_primes = []
for i,line in enumerate(primes.split('\n')):
    if i > 3 and i < 1004:
        temp = ((int(item) for item in line.split()))
        for i in temp:
            my_primes.append(i)
print (my_primes)
#You can take out number you want.
#10 first prime number
#print (my_primes[0:10])


Eksempel 5. Primtalls tallknusing

Kode: Velg alt

# Prim.py
#
# Kjell Bleivik 2010: www.kjellbleivik.com - www.oopschool.com - www.digitalpunkt.no,
#
# ---------------------------------------------------------------------------------------------------
#
# Brute force prime number and prime number twin calculation. There ar no security net, exception
# handling in the code.  Note that all twin primes except (3, 5) are of the form: (nx6) +/- 1. 
# References:  http://mathworld.wolfram.com/TwinPrimeConjecture.html
# http://mathworld.wolfram.com/OftheForm.html
#
# ---------------------------------------------------------------------------------------------------
print('This prgram is only valid for natural number between 1 and 1700')
print()
primes=[3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101] #Python inbuilt list
import math #import math module
n = int(input ('Enter a natural number between 1 and 1700 : '))
m1 = n*6 - 1
m2 = n*6 + 1
print()
limit=int(math.ceil(math.sqrt(m2))) + 1 #Ceiling of square root of number + 1
bool1=1
for prime in primes: #Loop through the list of known primes.       
        if prime <= limit:
           if m1 % prime == 0:  #Enough to test for prime factors up to the square root
               bool1=0 #No prime
               break #Break out of the loop if a prime factor is found.
if bool1 == 1:
    print (m1, ' is prime ')   
else:
    print (m1, ' is NOT prime ')
print()
bool2=1
for prime in primes: #Loop through the list of known primes.       
        if prime <= limit:
           if m2 % prime == 0:  #Enough to test for prime factors up to the square root
               bool2=0 #No prime
               break #Break out of the loop if a prime factor is found.
if bool2 == 1:
    print (m2, ' is prime ')   
else:
    print (m2, ' is NOT prime ')
print()

print()
enter=input('Hit enter ') #Prevent output window from closing.


Oppgave:
Kombiner det siste programmet ovenfor med programmene som leser inn primtall fra en fil med å legge dem i en liste eventulet array. Hvor store primtallstvillinger er du nå i stand til å beregne?

Dersom du ikke vet hvordan du leser tall fra en fil (html dokument i dette tilfellet) inn i en liste, kan du søke på nettet. Naturlig søkestreng er:

python read numbers from file into list

eller lignende søkestrenger.

Bruker du en Windows maskin og har problemer, kan du finne løsningen her:

Python on Windows FAQ http://docs.python.org/faq/windows.html ... er-windows

Gå tilbake til «Python»

Hvem er online

Brukere i dette forumet: Ingen registrerte brukere og 2 gjester