import this
import random
def make_maze(w = 16, h = 8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
random.shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]: continue
if xx == x: hor[max(y, yy)][x] = "+ "
if yy == y: ver[y][max(x, xx)] = " "
walk(xx, yy)
walk(random.randrange(w), random.randrange(h))
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
print(make_maze())
Kicsit más mint a legtöbb nyelvben:
i = 2
kb azt jelenti, hogy a típussal rendelkező i változó megkapja a 2 érték másolatát.Python i = 2
kb azt jelenti hogy az i név kap egy referenciát egy egy numerikus objektumhoz, aminek az értéke 2.
mindig a jobb oldal értékelődik ki először, majd pedig a bal oldali név kap egy referenciát a jobb oldali értékhez
Az id
függvény visszaadja az objektum egyedi azonosító számát. (Miért lehet gond az id használatából?)
i = 2
print(id(i))
i = 3
print(id(i))
i = "elte"
print(id(i))
s = i
print(id(s) == id(i))
old_id = id(s)
s = s + "matek"
print(id(s) == id(i))
print(old_id == id(s))
i
Az id-kat összehasonlíthatjuk az is
paranccsal.
a = 2
b = a
print(id(a) == id(b))
print(a is b)
a = a+1
print(id(a) == id(b))
a is b
a=25
b=25
a is b
a=300
b=300
a is b
25 is 25
300 is 300
#n = int(input())
n = 1
if n < 0:
print("N negatív")
elif n > 0:
print("N pozitív")
else:
print("N se nem negatív se nem pozitív")
if
utasítások is vannak int x = -2;
int abs_x = x>=0 ? x : -x;
Pythonban:
<kifejezés1> if <feltétel> else <kifejezés2>
n = -2
abs_n = n if n >= 0 else -n
abs_n
for e in ["foo", "bar"]:
print(e)
print(e)
Így nézne ki C++-ban:
for (int i=0; i<5; i++)
{ cout << i << endl;}
A range
mindig 0-val kezdődik!
for i in range(5):
print(i)
Megadhatjuk a kezdőértéket:
for i in range(2, 5):
print(i)
Megadhatjuk a növekedés értékét is. Ekkor viszont kötelező megadni a kezdőértéket is.
for i in range(1, 10, 2):
print(i)
i = 0
while i < 5:
print(i)
i = i + 1
i
Nincs do...while
Pythonban.
break
: ha korábban ki akarunk lépni egy ciklusbólcontinue
: ha korábban szeretnénk a következő ciklus futásra lépnifor i in range(10):
if i % 2 == 0:
continue
print(i)
for i in range(10):
if i > 4:
break
print(i)
print('süsü')
Fontos, hogy ezek nem matematikai függvények. Például nem csak a bemenettől függ a függvényérték!
Függvényeket a def
kulcsszó segítségévek használhatunk:
def foo():
print("én egy nagyon okos függvény vagyok")
foo()
Először a pozíció szerintieket kell írni aztán a kulcsszavasokat
def foo(arg1, arg2, arg3):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(1, 2, "asdfs")
foo(1, arg3=2, arg2=29)
arg3=4
l=["matek"]
def add_matek(k):
k.append("matek")
print(l)
add_matek(l)
print(l)
add_matek(l)
print(l)
s="matek"
def add_matek(k):
k=k+"matek"
print(s)
add_matek(s)
print(s)
add_matek(s)
print(s)
def foo(arg1, arg2=8, arg3=2):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(1)
Alapértelmezett argumentumokat nem is kötelező megadni.
foo(1, 2)
foo(arg1=1, arg3=33, arg2=222)
Tetszőleges kihagyható közülük.
def foo(arg1, arg2=2, arg3=3):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(11, 33)
print("")
foo(11, arg3=33)
Emiatt rengeteg argumentumod lehet úgy is, hogy ez nem nehezíti meg a függvény használatát. Sok könyvtárban találunk olyan függvényeket, amiknek rengeteg argumentumunk van.
Például a következő függvényt a pandas
könyvtárban találjuk:
pandas.read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)
return
parancs¶return
parancsot, a visszatérési érték automatikusan none
lesz.return
parancs is None
-nal tér vissza. def foo(n):
if n < 0:
return "negative"
if 0 <= n < 10:
return "positive", n
#return None
return
print(foo(-2))
print(foo(3), type(foo(3)))
print(foo(12))
i = 2
type(i), id(i)
i = "foo"
type(i), id(i)
i = 2
f = 1.2
s = i + f
print(type(i), type(f))
print(type(i + f))
print(s,type(s))
print("Nekem " + 3.1415 + " az IQ-m")
Viszont explicit konverzióval működik:
print("Nekem " + str(3.1415) + " az IQ-m")
True
és False
(nagybetűvel kell kezdeni!!!)x = False
type(x)
True and False
True or False
not False
True and True and False
and
, or
and not
x = 5
x < 2 and x >= 2
x > 0 and x < 10
not x < 0
int
, float
and complex
i = 2
f = 1.2
c = 1+2j
type(i), type(f), type(c)
c2 = i + c
print(c2, type(c2))
2**100000
type(2**63 + 1)
sys.float_info
parancs segítségével kapunkimport sys
sys.float_info
sys.int_info
i = 2
f = 4.2
c = 4.1-3j
s1 = i + f
s2 = f - c
s3 = i * c
print(s1, type(s1))
print(s2, type(s2))
print(s3, type(s3))
/
törtet is adhat//
a hányados egész részét adja vissza3 / 2
-3.0 // 2, 3 // 2
4 / 0.8, 4.0 / 0.8, 4 // 0.8, 4.0 // 0.8
Mi a megoldás a ilyesmi problémák elkerülésére?
x = 23
x < 24, x >= 22
Össze is lehet őket láncolni
23 < x and x < 100
23 <= x < 100
5 % 3
2 ** 3
2 ** 0.5
abs(-2 - 1j), abs(1+1j)
round(2.3456), round(2.3456, 2), round(3.5)
type(float(2))
# 0 felé kerekít
int(-2.7), int(2.7)
math
és cmath
modulok még sok mást tartalmaznak¶import math
math.log(16), math.log(16, 2), math.exp(2), math.exp(math.log(10))
x=300
y=300
x is y
x = 2
old_id = id(x)
x = x + 1
print(id(x) == old_id)
Egyedi immutable objektumok, csak egy példány van belőlük.
x = True
y = False
print(x is y)
x = False
print(x is y)
l1 = [0, 1]
old_id = id(l1)
l1.append(2)
old_id == id(l1)
[1,2] is [1,2]
A listák helyben megváltoztathatóak!