Seite 1 von 1

None für Stringformatierung

Verfasst: Freitag 29. April 2022, 11:17
von mm96
Hallo zusammen,

ich habe die Aufgabe, zu einer gegebenen Testfunktion die eigentliche Funktion zu schreiben.
Ziel ist es, eine Tabelle mit Funktionswerten auszugeben. Dabei ist die linke Spalte die der y-Werte, die unterste Zeile sind die x-Werte.
Hier mal meine Lösung:

Code: Alles auswählen

def write_table_to_file(f, xmin, xmax, nx, ymin, ymax, ny, width = 10, decimals = 5, filename = 'table.dat'):
    x = np.linspace(xmin, xmax, nx+1)
    y = np.flip(np.sort(np.linspace(ymin, ymax, ny+1)))
    vals = f(x, y[:, np.newaxis])
    with open(filename, 'w') as outfile:
        for yval, row in zip(y, vals):
            outfile.write(f"{yval:{width}.{decimals}g}")
            for col in row:
                outfile.write(f"{col:{width}.{decimals}g}")
            outfile.write('\n')
        outfile.write('\n')
        outfile.write(width * ' ')
        for xval in x:
            outfile.write(f"{xval:{width}.{decimals}g}")

def test_write_table_to_file():
    filename = 'tmp.dat'
    write_table_to_file(f=lambda x, y: x + 2*y,
                        xmin = 0, xmax = 2, nx = 4,
                        ymin = -1, ymax = 2, ny = 3,
                        width = 5, decimals = None,     # soll %5g entsprechen
                        filename = filename)
    # Load text in file and compare with expected results
    with open(filename, 'r') as infile:
        computed = infile.read()
    expected = """\
    2    4  4.5    5  5.5    6
    1    2  2.5    3  3.5    4
    0    0  0.5    1  1.5    2
   -1   -2 -1.5   -1 -0.5    0

         0  0.5    1  1.5    2"""
    assert computed == expected


import numpy as np

test_write_table_to_file()

Mein Problem ist jetzt das "None" in der Testfunktion bei dem Argument "decimals".
Vorgabe ist, dass width = 10, decimals = 1 %10.1g entspricht und width = 5, decimals = None soll zu %5g werden (da wird die alte Formatierungsweise verwendet).

Für decimals=5 z. B. funktioniert meine Funktion, aber mit dem None weiß ich nichts anzufangen.

Liebe Grüße

Re: None für Stringformatierung

Verfasst: Freitag 29. April 2022, 11:28
von __blackjack__
@mm96: Da würde man statt 5 den Wert `None` als Defaultwert angeben und in der Funktion dann testen ob es `None` ist und falls ja durch 5 ersetzen.

Re: None für Stringformatierung

Verfasst: Freitag 29. April 2022, 11:30
von __deets__
Na wenn du einen default-Wert fuer None hast, musst du eben auf None testen, und dann mit dem default wert belegen.

Code: Alles auswählen

yval = yval if yval is not None else DEFAULT_YVAL

Re: None für Stringformatierung

Verfasst: Freitag 29. April 2022, 11:32
von Sirius3
Ohne eine if-Abfrage geht das nicht. Du mußt also die Formatangabe am Anfang berechnen:

Code: Alles auswählen

number_format = f"{width}.{decimals}g"
und hier eben für den Fall `decimals is None` eine andere Formatangabe schreiben.

Das was np.linspace liefert sollte schon sortiert sein, ein np.sort ist da überflüssig.

Re: None für Stringformatierung

Verfasst: Freitag 29. April 2022, 13:20
von mm96
Alles klar, danke für die Antworten!