logo

Crowdly

Browser

Add to Chrome

Rekenaarwetenskap - Computer science - 113/114

Looking for Rekenaarwetenskap - Computer science - 113/114 test answers and solutions? Browse our comprehensive collection of verified answers for Rekenaarwetenskap - Computer science - 113/114 at stemlearn.sun.ac.za.

Get instant access to accurate answers and detailed explanations for your course questions. Our community-driven platform helps students succeed!

ProcessMarks

INPUT FILE: marks.txt

Write a program processmarks.py that reads student records from a file. The name of the file is given as a command-line parameter. The file consists of multiple records, with one student record per line in the following format: / Skryf 'n program processmarks.py wat studenterekords uit 'n lêer lees. Die naam van die lêer word gegee as 'n opdragreëlparameter. Die lêer bestaan uit veelvuldige rekords, met een studenterekord per reël in die volgende formaat:

12345678 Surname FirstName T1 T2 P

The line consists of six fields, all separated with a space: the student number, the student's surname, the student's first name, two test marks, and a project mark. The marks are all either integers in the range 0 to 100, or a single "-" to indicate that no mark was awarded. / Die reël bestaan uit ses velde, elkeen geskei met 'n spasie: die studentenommer, die student se van, die student se voornaam, twee toetspunte en 'n projekpunt. Die punte is almal óf heelgetalle in die reeks 0 tot 100, óf 'n enkele "-" om aan te dui dat geen punt toegeken is nie.

The program must read all and display all of the marks neatly and, for each line, add the student's final mark. The final mark is calculated as F=0.25(T1+T2)+0.50P. At the end of the list of students, the program must display three extra lines with the minima, maxima, and averages of T1, T2, P, and the final marks. / Die program moet alles lees en al die punte netjies vertoon en vir elke reël die student se finale punt byvoeg. Die finale punt word bereken as F=0.25(T1+T2)+0.50P. Aan die einde van die lys studente moet die program drie ekstra reëls vertoon met die minimum, maksimum en gemiddeldes van T1, T2, P en die finale punte.

Then, use stdstats to display a histogram (bar graph) of the student marks sorted into ten bins: 0 .. 9.9, 10 .. 19.9, 20 .. 29.9, and so on.  Hint: You will have to use stddraw.setCanvasSize() before and stddraw.show() after the call to display the bar graph. / Gebruik dan stdstats om 'n histogram (staafgrafiek) van die studentepunte te vertoon wat in tien bakke gesorteer is: 0 .. 9.9, 10 .. 19.9, 20 .. 29.9, ensovoorts. Wenk: Jy sal stddraw.setCanvasSize() voor en stddraw.show() na die oproep moet gebruik om die staafgrafiek te vertoon.

There are two important rules: / Daar is twee belangrike reëls:

  • If any mark field is "-", the corresponding mark is 0. / As enige merkveld "-" is, is die ooreenstemmende punt 0.

  • If any mark field contains an invalid value (less than 0 or more than 100), the entire line is ignored and *not* printed or used in the average calculation. / As enige merkveld 'n ongeldige waarde bevat (minder as 0 of meer as 100), word die hele reël geïgnoreer en *nie* gedruk of in die gemiddelde berekening gebruik nie.

For example, if marks.txt contains / Byvoorbeeld, as marks.txt bevat

34567890 Tyolo Thabo 78 -  89

45678901 Lardo Luigi 101 62 56

23456789 Brown Bobby 65 66 93

12345678 Smith Sally - 84 71

the program must behave as follows: / die program moet soos volg optree:

$ python processmarks.py < marks.txt

34567890 Thabo Tyolo 78 0 89 64.0

23456789 Bobby Brown 65 66 93 79.3

12345678 Sally Smith 0 84 71 56.5

Min 0.0 0.0 71.0 56.5

Max 78.0 84.0 93.0 79.3

Average 47.7 50.0 84.3 66.6

Use the following statements to display the list: / Gebruik die volgende stellings om die lys te vertoon:

stdio.writef('%8s %-14s ', STUDENTNR, FIRSTNAME + ' ' + SURNAME)

stdio.writef('%6d %6d %6d %6.1f\n', T1, T2, P, F)

...

stdio.writef('%-23s ', 'Average');

stdio.writef('%6.1f %6.1f %6.1f %6.1f\n', AVERT1, AVERT2, AVERP, AVERF)

Download the following marks file: marks.txt and process it with your program.  The last line should read / Laai die volgende puntelêer af: marks.txt en verwerk dit met jou program. Die laaste reël moet lees

Average                   50.5   45.5   46.7   47.3

and you should see this histogram: / en jy behoort hierdie histogram te sien:

View this question

Haystack

Unit tests can be tedious to write by hand. Instead, we can sometimes achieve good results by testing with random values. This is not always possible, because we need an oracle to tell us if our test results are correct. But in this assignment, we shall look at a case where the oracle is easy to write. / Eenheidstoetse kan vervelig wees as dit met die hand geskryf is. In plaas daarvan kan ons soms goeie resultate behaal deur met ewekansige waardes te toets. Dit is nie altyd moontlik nie, want ons het 'n orakel nodig om vir ons te sê of ons toetsuitslae korrek is. Maar in hierdie opdrag gaan ons kyk na 'n geval waar die orakel maklik is om te skryf.

Download the BadSearch.py module that implements two search functions. Now create the program called testsearch.py to test the BadSearch.find0() method with random parameters. Start by writing a method def randomTest(size) that implements the following steps: / Laai die BadSearch.py program af wat twee soek funksies implementeer. Skep nou 'n program testsearch.py om die BadSearch.find0() metode met ewekansige parameters te toets. Begin deur 'n metode def randomTest(size) te skryf wat die volgende stappe implementeer:

  1. Pick a random target value k from 0 to 49. / Kies 'n ewekansige teikenwaarde k van 0 tot 49.

  2. Construct a new integer array of size size. / Konstrueer 'n nuwe heelgetal-skikking van grootte size.

  3. Fill the array with random values from 0 to 49. / Vul die skikking met ewekansige waardes van 0 tot 49.

  4. If a random value you are placing in the array is equal to k, make a note of the index where the value is placed. / As 'n ewekansige waarde wat jy in die skikking plaas gelyk is aan k, maak 'n nota van die indeks waar die waarde geplaas is.

  5. If none of the random values are equal to k, the noted index should be -1. / As nie een van die ewekansige waardes gelyk is aan k nie, moet die genoteerde indeks -1 wees.

  6. Call BadSearch.find0() and return true if and only if it returns the noted index. / Bel BadSearch0.find() en gee true as en slegs as dit die genoteerde indeks terugstuur.

In the main function, call randomTest(size) for different array sizes: 100,000 times for size 2, another 100,000 times for size 3, and so on, up to 100,000 times for size 7. For each size, record how many times randomTest() detected an error (= returned False), and display this statistic. / In die main funksie, roep randomTest(size) vir verskillende skikkingsgroottes: 100 000 keer vir grootte 2, nog 100 000 keer vir grootte 3, ensovoorts, tot 100 000 keer vir grootte 7. Vir elke grootte, teken aan hoeveel keer randomTest( ) 'n fout opgespoor het (= returned False), en vertoon hierdie statistiek.

$ python testsearch.py

n:2 bug: 96.1%

n:3 bug: 94.2%

n:4 bug: 92.4%

n:5 bug: 90.5%

n:6 bug: 88.5%

n:7 bug: 86.9%

Repeat all of the above for BadSearch.find1(). / Herhaal al die bogenoemde vir BadSearch.find1().

View this question

Craps

 The following are the rules for a pass bet in the game of craps. Roll two six-sided dice, and let x be their sum.

  • If x is 7 or 11,you win.
  • If x is 2,3, or 12,you lose.

Otherwise, repeatedly roll the two dice until their sum is either x or 7.

  • If their sum is x, you win.
  • If their sum is 7,you lose.

Write a modular program to estimate the probability of winning a passbet. Use your program to simulate 1 million dice rolls and answer the below:

Die reëls vir `n slaag wedenskap in die speletjie `craps` is soos volg: Rol twee seskantige dobbelstene en laat x hulle som verteenwoordig.

  • As x 7 of 11 is wen jy.
  • As x 2, 3 of 12 is verloor jy.

As x nie een van hierdie nommers is nie moet jy herhaaldelik die dobbelstene rol totdat hulle som x is of 7 is.

  • As hulle som x is, dan wen jy.
  • As hulle som 7 is, dan verloor jy.

Skryf `n modulêre program om te skat wat die waarskynlikheid is dat jy hierdie slaag weddenskap wen. Gebruik jou program om 1 miljoen dobbelsteentjies te simuleer en beantwoord die onderstaande:

0%
0%
View this question

Hyperbolic

Write a module hyperbolic.py consisting of methods that implement the hyperbolic functions based on the definitions and . First write the methods for sinh and cosh. By making use of these two implementations, write functions that implement the function , , , and , defined in a manner analogous to standard trigonometric functions. Test your implementations by adding a main method that accepts one command-line parameter x and prints the results of each method. The output should look as follows: / Skryf 'n module hyperbolic.py wat bestaan uit metodes wat die hiperboliese funksies implementeer gebaseer op die definisies en . Skryf eers die metodes vir sinh en cosh neer. Deur gebruik te maak van hierdie twee metodes, skryf statiese metodes wat die funksie , , , en implementeer, gedefinieer op 'n wyse analoog aan standaard trigonometriese funksies. Toets jou implementerings deur 'n main metode by te voeg wat een opdragreëlparameter x aanvaar en die resultate van elke metode druk. 'n Korrekte implementering sal die volgende resultate lewer:

$ python hyperbolic.py 0.2

sinh(0.200000) = 0.201336

cosh(0.200000) = 1.020067

tanh(0.200000) = 0.197375

coth(0.200000) = 5.066490

sech(0.200000) = 0.980328

csch(0.200000) = 4.966822

Now write client program hyper_client.py (it's file should be in the same directory as the hyperbolic module) that takes two commen-line parameters func_type and value and prints out the computed hyperbolic value of value based on the string input func_type. To use the functions of the hyperbolic module, there are three ways of importing modules from a library which are listed below together on how to use them in the client code. It also gives a reason of using a particular import stype (although this can sometime be up to a programmers preferred coding style): / Skryf nou kliëntprograme hyper_client.py wat twee commen-lyn parameters func_type en value neem en die berekende hiperboliese waarde van value uitdruk gebaseer op die string func_type. Om die funksies van die hiperboliese module te gebruik, is daar drie maniere om modules vanaf 'n biblioteek in te voer wat hieronder saam gelys word oor hoe om dit in die kliëntkode te gebruik. Dit gee ook 'n rede om 'n spesifieke invoertipe te gebruik (alhoewel dit soms tot 'n programmeerders se voorkeur-koderingstyl kan wees):

from hyperbolic import cosh

# usage: cosh(x)

# reason: "If you are only planning on using cosh, then there is no need to import the other methods"

from hyperbolic import *

# usage: cosh(x)

# reason: "If you are using most of the module's methods, this will be the cleaner import statement,

# however, it is often considered unclear and bad style."

import hyperbolic

# usage: hyperbolic.cosh(x)

# reason: "This is an absolute import and considered by most to be the cleanest and best import style."

The output should look as follows: / 'n Korrekte implementering sal die volgende resultate lewer:

$ python hyper_client.py cosh 0.9

1.4330863854487745

$ python hyper_client.py sinh 0.9

1.0265167257081753

$ python hyper_client.py sinc 0.9

Hyperbolic function name not recognised.
View this question

Please upload your projects files for Hand-in 2 here.

Make sure you have completed the following tasks:

  • Read the use of student code document and signed and uploaded the plagiarism document here.
  • Made sure that your project files pass the Hand-in 2 Smoke Test as well as the dedicated smoke tests for the scanner.py and parser.py files.
  • Upload all your .py files required for your project, but at a minimum you need to upload:

    • scanner.py
    • parser.py
    • SU<su number>.py where <su number> is YOUR 8-digit student number.

Note: No late submissions will be accepted. Late submissions will automatically receive a mark of 0.

You can only submit your submission once!

View this question

Complete playthattune.py by selecting one of the given code snippets below. The code snippet you select must enable playthattune.py to play the notes depicted in Figure A when it is executed. 

Voltooi playthattune.py deur een van die gegewe kode uitreksels te kies. Die kode uitreksel wat jy kies moet playthattune.py in staat stel om die note wat in Figuur A uitgebeeld word te kan speel wanneer dit uitgevoer word. 

#playthattune.py

import stdaudio

import

math

import stdarray

def playnotes(pitch, duration):

    sps =

44100

    n = int(sps*duration)

    for k in range(0,len(pitch)):

        hz =

440*math.pow(2,pitch[k]/12.0)

        a =

stdarray.create1D(n+1,0.0)

        for i in

range(0,n+1):

            a[i] =

math.sin((2*math.pi*i*hz)/sps)

       

stdaudio.playSamples(a)

    

def

main():

    #YOUR CHOSEN CODE SNIPPET GOES

HERE

    playnotes(A,0.5)

if __name__ == "__main__": main()

 

                                 Figure A/Figuur A

View this question

Which one of the following pictures appear on your canvas when the following Python program is executed?

Watter een van die volgende prentjies verskyn op jou verfdoek wanneer die volgende Python program uitgevoer word?

#circles.py

import stddraw

def main():

    for k in range(1,5):

        for j in range(1,5):

            x_cor = j*0.2

            y_cor = k*0.2

            if ((k%j == 0) or (j%k == 0)):

                stddraw.setPenColor(stddraw.BLUE)

                stddraw.filledCircle(x_cor, y_cor, 0.1)

            else:

                stddraw.setPenColor(stddraw.GREEN)

                stddraw.filledCircle(x_cor, y_cor, 0.1)

    stddraw.show()

if __name__ == "__main__": main()

          

The lines above were not generated by the program. Color hues of actual output may differ slightly from the depiction above.

Die lyne hierbo is nie deur die program geskep nie. Kleurskakerings van ware afvoer mag effens verskil van die uitbeeldings hierbo.

View this question

Complete sierpinski.py by selecting one of the given code snippets below. The code snippet you select must enable sierpinski.py to generate Figure A when it is executed. 

Voltooi sierpinski.py deur een van die gegewe kode uitreksels te kies. Die kode uitreksel wat jy kies moet sierpinski.py in staat stel om Figuur A te genereer.

#sierpinski.py

import stddraw

def main():

        

        #YOUR CHOSEN CODE SNIPPET WILL BE INSERTED HERE

        cx = [0.000, 1.000, 0.500]

        cy = [0.000, 0.000, 0.866]

                

        stddraw.setXscale(-0.1,1.1)

        stddraw.setYscale(-0.1,1.1)

        stddraw.line(cx[0],cy[0],cx[1],cy[1])

        stddraw.line(cx[1],cy[1],cx[2],cy[2])

        stddraw.line(cx[2],cy[2],cx[0],cy[0])

            

        stddraw.setPenColor(stddraw.RED)

        stddraw.filledCircle(cx[0], cy[0], 0.05)

        stddraw.setPenColor(stddraw.BLACK)

        stddraw.text(cx[0], cy[0], "0")

                

        x = 0.0

        y= 0.0

        for v in range(0,len(vertices)):

            r = vertices[v]

            

            x = (x + cx[r]) / 2.0

            y = (y + cy[r]) / 2.0

            

            if (r == 0):

                stddraw.setPenColor(stddraw.RED)

            elif (r == 1):

                stddraw.setPenColor(stddraw.GREEN)

            elif (r == 2):

                stddraw.setPenColor(stddraw.BLUE)                

            

            stddraw.filledCircle(x, y, 0.05)

            if (r == 2):

               stddraw.setPenColor(stddraw.WHITE)

            else:

                stddraw.setPenColor(stddraw.BLACK)

                

            stddraw.text(x, y, ""+str(v+1))

    

        stddraw.show()

if __name__ == "__main__": main()

                                          Figure A/Figuur A

View this question

Given the following statement:

arr = [ [1,2,3] ,[4,5,6], [7,8,9] ]

which of the following code snippets will print all the elements of arr to the screen?

Gegee die volgende stelling:

arr = [ [1,2,3] ,[4,5,6], [7,8,9] ]

watter van die volgende kodebrokkies sal al die skikkingselemente van arr na die skerm druk?

View this question

What does the following code print to the terminal when it is executed?

Wat druk die volgende kode na die terminaal wanneer dit uitgevoer word?

import math, stdio

stdio.writef("|%-3.2s|%-2d|%5.2f|%5d|","Google",1000,math.pi,14)

View this question

Want instant access to all verified answers on stemlearn.sun.ac.za?

Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!

Browser

Add to Chrome