4. Strukturované datové typy

1. příklad

a = 10
b = 3
print("a:", a, "b:", b)
 
# prohozeni promennych s pomocnou promennou
tmp = a
a = b
b = tmp
print("a:", a, "b:", b)
 
# prozeni promennych bez pomocne promenne
a = a + b
b = a - b
a = a - b
print("a:", a, "b:", b)
 
# prohozeni promennych pomoci tuple
(a, b) = (b, a)
print("a:", a, "b:", b)

2. příklad

def obdelnik(arg):
    (a,b) = arg
    return (a*b)
 
def kruznice(arg):
    return (3.14*(arg**2))
 
def vypocet(f, arg):
    return f(arg)
 
print("obdelnik:", vypocet(obdelnik, (2,3)))
print("kruznice:", vypocet(kruznice, 2.2))

3. příklad

# pole vytvorene vyctem
a = [1, 2, 3]
 
for i in range(len(a)):
    print("a[", i, "] = ", a[i])
 
y = 0
for i in a:
    print("a[", y, "] = ", i)
    y += 1
 
# prazdne pole b
b = []
b += [10]
b += [20]
print(b)
 
# prazdne pole c
c = list()
c.append(10)
c.append(20)
printc(c)

4. příklad

def pole(p):
    for i in range(len(p)):
        p[i] += 10
 
a = [1, 2, 3, 4]
b = a # neni kopie, pouze reference
print("b: ", b)
a[3] = 100
print("b: ", b)
# kopie pomoci rezu
c = a[:]
print("c: ", c)
a[2] = 88
print("a: ", a)
print("c: ", c)
 
pole(c)
print("c: ", c)

5. příklad

import random
 
def vektor(delka, rozsah):
    "vektor nahodnych celych cisel"
    r = []  # pole, ktere budu na konci vracet
    for i in range(delka):
        # r += [random.randint(1, rozsah)]
        r.append(random.randint(1, rozsah))
 
    return r
 
def vektor1(delka, rozsah=100):
    return ([random.randint(1,rozsah) for i in range(delka)])
 
def soucet(x, y):
    "soucet vektoru x a y"
    return ([x[i]+y[i] for i in range(len(x))])
 
def soucin(x, y):
    "skalarni soucin vektoru x a y"
    s = 0
    for i in range(len(x)):
        s += x[i]*y[i]
    return s
 
a = vektor(10, 40)
print(a)
b = vektor1(10)
print(b) 

6. příklad

b = [[1, 22, 3], [4, 5, 18]]
print("b: ", b)
print("b[0]: ", b[0])
print("len(b): ", len(b))
print("b[1][1]: ", b[1][1])
 
for i in b:
    print(i)
 
for i in range(len(b)):        # pocet vektoru
    for j in range(len(b[0])): # delka vektoru
        print(str(b[i][j]).rjust(2), end=" ")
    print()
 
garaz = [
    ("petr", ["porsche", "bmw", "volvo"]),
    ("jan", ["bmw", "volvo"]),
    ("jiri", ["bmw", "porsche"])]
 
p = 0
for i in garaz:
    (clovek, auta) = i
    if "porsche" in auta:
        p+=1
print("v garazi je ", p, "vozu znacky porsche")
 
a = [[]]
a[0] = [10, 20, 30]
print(a)
a.append([20, 30, 60])
print(a)

courses/bab37zpr/solutions/lab04.txt · Last modified: 2019/10/16 20:28 by viteks