Warning
This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

3. Cykly a funkce

1. příklad

# program na aproximaci Ludolfova cisla metodou Monte Carlo
import random
import math
 
m = 0   # cisla vne jednotkove kruznice
n = 0   # cisla uvnitr jednotkove kruznice
 
for i in range(1000000):
    x = random.random()
    y = random.random()
    z = math.sqrt(x*x + y*y)
 
    if z > 1:
        m += 1
    else:
        n += 1
 
piq = n/(n+m)
 
print("pi = %.6f" % (piq*4))

2. příklad

# program pro kresleni geometrickych tvaru
for a in range(1,6):
    for b in range(a):
        print('*', end='')
    print()
 
print()
 
for a in range(5):
    for b in range(5-a):
        print('*', end='')
    print()
 
print()
 
for a in range(1,6):
    for b in range(1,6-a):
        print(' ', end='')
    for b in range(a):
        print('*', end='')
    print()
 
print()
 
# poznamka k funkci range
 
for i in range(1,10,2):
    print(i, end=' ')
print()
 
for i in range(10, 1, -2):
    print(i, end=' ')
print()

3. příklad

# diagonaly
for i in range(100):
    if (i % 11 == 0):
        print (str(i).rjust(3), end='')
    elif (i % 9 == 0):
        print (str(i).rjust(3), end='')
    else:
        print ('   ', end='')
    if (i % 10)==9: print()

4. příklad

mons = ['Leden', 'Unor', 'Brezen', 'Duben']
days = ['Po', 'Ut', 'St', 'Ct', 'Pa', 'So', 'Ne']
nums = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 
def calendar (mesic, den):
    konec = 0
    print(" " + mons[mesic-1])
    # tisk nazvu dnu v tydnu
    for i in range(7):
        print(days[i].rjust(3), end='')
    # odradkovani
    print()
    # tisk cisel dnu v mesici
    for i in range(1, nums[mesic-1]+den):
        konec += 1
        if i < den:
            print('   ', end='')
        else:
            print(str(i-den+1).rjust(3), end='')
        if i % 7 == 0:
            print()
            konec = 0
    print("\n")
    return konec
 
k = calendar (1, 2)
k = calendar (2, k+1)

courses/bab37zpr/solutions/lab03.txt · Last modified: 2019/10/16 21:07 by viteks