NBA_02_Listen_Dezimalzahlen_Werkzeuge

(c) 2019/2020 Hochschule Augsburg - Fakultät für Informatik - Prof.Dr.Nik Klever

Listen

array

In [1]:
from array import array
a = array("H", [1,2,3,4])
a
Out[1]:
array('H', [1, 2, 3, 4])
In [2]:
with open("binär.bin","wb") as f:
    a.tofile(f)
In [3]:
!hexdump binär.bin -C
00000000  01 00 02 00 03 00 04 00                           |........|
00000008
In [4]:
a = array("H", range(65,67))
a
Out[4]:
array('H', [65, 66])
In [5]:
with open("binär.bin","wb") as f:
    a.tofile(f)
In [6]:
!hexdump binär.bin -C
00000000  41 00 42 00                                       |A.B.|
00000004
In [7]:
ord("B")
Out[7]:
66
In [8]:
hex(ord("B"))
Out[8]:
'0x42'

collections

deque

In [9]:
from collections import deque
d = deque([1,2,3])
print("Warteschlange:",d)
Warteschlange: deque([1, 2, 3])
In [10]:
n = 4
d.append(n)
print("Warteschlange:",d)
Warteschlange: deque([1, 2, 3, 4])
In [11]:
b = d.popleft()
b
Out[11]:
1
In [12]:
print("Warteschlange:",d)
Warteschlange: deque([2, 3, 4])

OrderedDict

In [13]:
from collections import OrderedDict
d = {"Banane": 3, "Zitrone": 12, "Kiwi": 5, "Orange":15}
od = OrderedDict(d)
od
Out[13]:
OrderedDict([('Kiwi', 5), ('Orange', 15), ('Banane', 3), ('Zitrone', 12)])

bisect

In [14]:
import bisect
tupelliste = [(1,"Apfel"),(5,"Banane"),(8,"Zitrone")]
bisect.insort(tupelliste,(3,"Birne"))
tupelliste
Out[14]:
[(1, 'Apfel'), (3, 'Birne'), (5, 'Banane'), (8, 'Zitrone')]

heapq

    heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] # für alle k >= 0; heap[x] = unendlich, wenn x > len(heap)
In [17]:
from heapq import heapify, heappop, heappush

def testheap(data):
    for i in range(len(data)):
        compare = [True, True]
        for j in 0,1:
            if 2*i+j+1 < len(data):
                compare[j] = data[i] <= data[2*i+j+1]
        if not (compare[0] and compare[1]):
            print("data is not a heap")
            break
    else:
        print("data is a heap")
In [18]:
data = [1,3,5,7,9,2,4,6,8,0]
print(data)
testheap(data)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
data is not a heap
In [19]:
heapify(data)
print(data)
testheap(data)
[0, 1, 2, 6, 3, 5, 4, 7, 8, 9]
data is a heap

Dezimalzahlen

In [20]:
from decimal import *
round(Decimal("0.70")*Decimal("1.05"), 2)
Out[20]:
Decimal('0.74')
In [21]:
round(0.70*1.05,2)
Out[21]:
0.73
In [22]:
Decimal("1.00") % Decimal(".10")
Out[22]:
Decimal('0.00')
In [23]:
1.0 % 0.1
Out[23]:
0.09999999999999995
In [24]:
sum([Decimal("0.1")]*10) == Decimal("1.0")
Out[24]:
True
In [25]:
sum([0.1]*10) == 1.0
Out[25]:
False
In [26]:
sum([0.1]*10) - 1.0
Out[26]:
-1.1102230246251565e-16
In [27]:
getcontext()
Out[27]:
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])
In [28]:
getcontext().prec=36
Decimal(1) / Decimal(7)
Out[28]:
Decimal('0.142857142857142857142857142857142857')