Continue and Break

Stellt hier eure Projekte vor.
Internetseiten, Skripte, und alles andere bzgl. Python.
Antworten
vounesa
User
Beiträge: 6
Registriert: Freitag 22. Juni 2018, 10:44

Hallo,

und zwar bereitet mir auf der Uni in Informatik 1 ohne Programmier Vorkenntnisse dieser Minitask ein Problem:
Write a function task_2_3. It should expect two parameters. The first is a limiter and the second is a target which is a positive integer with a value of 0 to 100. Randomly create numbers from 0 to 100 and count how long it takes until your random number is equal to the target. Repeat this process multiple times (defined by limiter param) and output the number of random values created in each run and return the average at the end.
Implement this as follows:
Create random numbers using the following code:
1. random_number = random.randint(0,100)
2. Count how long it takes until the random number is equal to the target (second parameter)
3. Escape this loop using break when you hit the target.
4. Output the number of values created until the target was hit.
5. Repeat this process multiple times (defined by the limit parameter)
6. Return the mean number of random values created across all runs.

Mein Code bis jetzt sieht so aus mit Kommentaren wie ich darauf komme:

Code: Alles auswählen

import random
def task_2_3(limiter,target):
    target= range(0,100)
    random_number = random.randint(0,100) 
    count = 0 #für das mitzählen wie lange die random zahl braucht um target zu erreichen
    while True: #solange die random zahl nicht gleich target ist wird der counter um 1 erhöht
        count += 1
        if random_number == target: #ist die random number gleich target wird die schleife abgebrochen
            break
            print(random_number)
Beim Ausführen wird jedoch nichts ausgegeben, stimmt der Code soweit bzw was stimmt nicht? Und hat wer Tipps etc was das weitere Vorgehen betrifft?

Vielen Dank im Vorraus!
Sirius3
User
Beiträge: 17737
Registriert: Sonntag 21. Oktober 2012, 17:20

Die Funktion muß auch aufgerufen werden. Dann landest Du in einer Endlosschleife, weil eine Zahl nie gleich einem Range-Objekt ist und sich keines der beiden Variablen innerhalb der while-Schleife ändert. Auch wenn `target` die Zahl bliebe, die Du als Parameter übergibst und auch wenn die Zufallszahlen innerhalb der Schleife jedesmal neu erzeugt würden, gäbe es immer noch keine Ausgabe, da das `print` hinter dem `break` steht, also niemals erreicht wird. Laut Aufgabe solltest Du auch `count` ausgeben, bzw. damit weiter arbeiten.
Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Vor dem ``break`` würde das ausgeben der Zufallszahl auch sinnlos sein, denn die wäre an der Stelle ja immer gleich `target`.
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Spasseshabler mal als Bash-Skript:

Code: Alles auswählen

#!/bin/bash

Task_2_3() {
    local limiter=$1
    local target=$2
    local count
    local total_count=0
    local i
    
    for (( i = 0; i < limiter; i++ )); do
        for (( count = 1;; count++ )); do
            if [[ $(shuf -i 1-100 -n 1) -eq target ]]; then
                (( total_count += count ))
                echo $count
                break
            fi
        done
    done
    dc -e "2k $total_count $count / p"
}

Task_2_3 20 50
Für eine Python-Lösung lohnt sich eventuell ein Blick auf `itertools.count()`. Dann braucht man keine ``while``-Schleife.
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Benutzeravatar
__blackjack__
User
Beiträge: 13069
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Und noch eine Lösung in Python:

Code: Alles auswählen

#!/usr/bin/env python3
from itertools import count
from random import randint

MIN_TARGET = 0
MAX_TARGET = 100


def task_2_3(repetition_count, target):
    if repetition_count <= 0:
        raise ValueError(
            f"repetition count must be positive, got {repetition_count!r}"
        )
    if not MIN_TARGET <= target <= MAX_TARGET:
        raise ValueError(
            f"target {target!r} not in range {MIN_TARGET}..{MAX_TARGET}"
        )

    total_count = trial_count = 0
    for _ in range(repetition_count):
        for trial_count in count(1):
            if randint(MIN_TARGET, MAX_TARGET) == target:
                break
        print(trial_count)
        total_count += trial_count

    print(total_count / repetition_count)


def main():
    task_2_3(20, 42)


if __name__ == "__main__":
    main()
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Antworten