Тёмный

Recursion in Python  

Exploring the IT World / Oleg Shpagin / WISEPLAT
Подписаться 147 тыс.
Просмотров 204 тыс.
50% 1

How does recursion work in Python? What is recursion?! The best example of recursion is the calculation of the factorial! How to do this, see the video....
► To support the channel: wiseplat.org/donat​
By card number: 5599005072205482
👍 Like it if you liked the video 👍
►► Subscribe to the channel! 🔔
Press the bell to not miss it!

Опубликовано:

 

24 июн 2021

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 187   
@DatNguyen-vj1ro
@DatNguyen-vj1ro 3 года назад
I was today's year old when I learned that the print function can write to a file
@beelzebub3920
@beelzebub3920 3 года назад
Yeah didn't know that
@filippo2185
@filippo2185 3 года назад
Good 'ol fprintf
@WasiMaster
@WasiMaster 3 года назад
You can also specify a separator with the sep keyword argument which is default to " " (space) x = 1 y = 2 print(x, y) # prints: 1 2 print(x, y, sep=",") # prints: 1,2
@warker6186
@warker6186 3 года назад
2
@puspamadak
@puspamadak 3 года назад
Same here 😅
@animenosekai_edit
@animenosekai_edit 3 года назад
For the best practices you don’t need the “else” and you should use the “with” statement to open the file so that it is properly closed after use
@ItalianPizza64
@ItalianPizza64 3 года назад
But "else" does make the code more readable
@calliioa
@calliioa 3 года назад
Heck, use a walrus operator or just open the file beforehand and close after
@animenosekai_edit
@animenosekai_edit 3 года назад
@@calliioa And then you lose the 30% of persons using python 3.6
@thegreatarchive-a8801
@thegreatarchive-a8801 2 года назад
@@ItalianPizza64 That's true but so does an extrawhitespace, which is what I would do
@carlossegura403
@carlossegura403 2 года назад
True, but I like readable code, so i use it.
@crispybacon1999
@crispybacon1999 3 года назад
TIL you can just print to a file
@leonhma
@leonhma 3 года назад
Your Keyboard ist so hollow i can literally feel it
@The_Mitchell
@The_Mitchell 3 года назад
If you can rewrite the code in terms of nested functions you can get significantly better results than recursion and because you essentially turn it into a for loop there's no recursion limit. Look up python closure for a better explanation
@WilcoVerhoef
@WilcoVerhoef 3 года назад
Or use Haskell in which it's actually more performant to write in the recursive form
@TheJackal917
@TheJackal917 3 года назад
Video example plz.
@khodis2002
@khodis2002 3 года назад
@@WilcoVerhoef it's like first telling how a molecule works, and then a whale.
@boomerboxer3574
@boomerboxer3574 2 года назад
Would it be something like this? (i'm learning Python so feedback would be great) def factorial(n): acc, x = 1, 1 def step(): nonlocal acc, x acc *= x x += 1 return acc res = 1 for i in range(n): res = step() return res
@The_Mitchell
@The_Mitchell 2 года назад
yeah that code looks good. Theres no need to change it but one of the advantages however of writing your code using closure is that you can continue the function from whereever you leave off so maybe its not ideal to put the for loop inside of the outer function. def factorial(): acc, x = 1, 1 def step(): nonlocal acc, x acc *= x x += 1 return acc return step fact = factorial() for i in range(1,5): num = fact() print(i, num) try this one out, because the foor loop is outside of the function you can pick up where it leaves off by calling fact() again this way you can use your function to calculate 100! and then if you decide you can immediately start calculating 101! without having to start at 1 again
@DedeKurnn
@DedeKurnn 3 года назад
Try fibonacci with recursion.
@metafates
@metafates 2 года назад
from functools import cache @cache def fib(nth): if nth < 2: return nth return fib(nth-1) + fib(nth - 2)
@alexjung1425
@alexjung1425 3 года назад
0:00 nice work
@soewaiyanaung
@soewaiyanaung 3 года назад
You should do n == 0 return 1 instead of n==1.
@dfla5472
@dfla5472 3 года назад
Why?
@soewaiyanaung
@soewaiyanaung 3 года назад
@@dfla5472 because factorial 0 give you the value of 1. If you do n == 1, factorial 0 will give you error instead of returning 1.
@ViniciusTeixeira1
@ViniciusTeixeira1 3 года назад
@@glooring7039 that's not the point. The point is that 0! equals 1, but this function can't evaluate the factorial of 0
@geniusvedant673
@geniusvedant673 3 года назад
@@soewaiyanaung why when n is 1 the control will move to the if block and simply return 1
@dd28924
@dd28924 3 года назад
@@geniusvedant673dude if you give it the value 0 it won't return 1 ever! Because 0 isn't 1 and better: the next number in this code would be -1 and it will go on until the stack is full and this will lead to a stackoverflow. Try it yourself. The if should be if n == 0 or if n == 0 || n ==1. The second one would return the factorial of 1 even without recursion.
@d3r1n
@d3r1n 3 года назад
C++ / Rust / Go folks: "Haha hard recursion limit"
@willardsun5437
@willardsun5437 3 года назад
integer limit tho :((
@khodis2002
@khodis2002 3 года назад
@@willardsun5437 Try to write your own big integer, if you are worthy.
@nolann6324
@nolann6324 2 года назад
Rust has recursion limit no ?
@dzikriqalam5010
@dzikriqalam5010 3 года назад
Thankyou, I never knew there was a parameter for printing to a file
@IshanShah
@IshanShah 3 года назад
You can convert this to linear time automatically using a cache decorator
@chrisisawesomeandcoo
@chrisisawesomeandcoo 2 года назад
Isn't this already linear time?
@caedenw
@caedenw 2 года назад
cache seems like a waste of memory for a factorial function……… just saying that shit is gonna fill up fast
@AlexanderBukh
@AlexanderBukh 2 года назад
@@caedenw classic memory/speed tradeoff, as an educational example, it should have it, in real use you need more checks and limits ofc
@caedenw
@caedenw 2 года назад
@@AlexanderBukh not really… why would you memoize something you never use as a recursive call? the recursive DAG for this has a trivial topological sorting which is just in order from 1 to n so there is no point in using a cache decorator. the recursive calls are literally never reused. plus now you have to store in memory a bunch of large numbers. that means memory must be allocated for this purpose which takes time so a cache decorator would be slower. but if you ever want to computer the factorial more than once, sure it would be a speed up to have precalculated this. i would personally prefer to store the precalculations in a list, but whatever floats your boat. i still think there are better ways because the memory requirements become huge even for relatively small n.
@sebaitor
@sebaitor 2 года назад
@@chrisisawesomeandcoo he meant constant
@caedenw
@caedenw 2 года назад
Alternative definitions I like: def factorial(n): return n * factorial(n-1) if n else 1 def factorial(n): r = 1 for i in range(1, n+1): r *= i return r def factorial(n): return math.prod(range(1, n+1)) but the best is probably math.factorial(n)
@WebMafia
@WebMafia 2 года назад
in the first definition you're making an unnecessary function call with n = 0
@ManuelInfoSec
@ManuelInfoSec 2 года назад
Nice. I like the file writing
@boppinggamer8571
@boppinggamer8571 2 года назад
This dude sounds like hes writing with his mouse's middle button.
@Sciencedoneright
@Sciencedoneright 2 года назад
2002! sure is huge
@FedSilVor
@FedSilVor 3 года назад
Me who is learning C++ and doesn't care about Python: interesting
@kadensharpin2156
@kadensharpin2156 3 года назад
python is garbo
@no-better-name
@no-better-name 2 года назад
@@kadensharpin2156 it's quite slow, but it's very readable and it's more of a glue language: use easy-to-read stuff to outsource hard tasks to other languages like C (import numpy). also you can do things quick and dirty, like if you just want, idk, a truth table for a boolean function, easier to write a few Python lines than C++, for example. I'm learning C++ and Python, so I think I can see the difference
@kadensharpin2156
@kadensharpin2156 2 года назад
@@no-better-name honestly I'm just trying to bait. I have never used python before and frankly I don't think I ever will. However, Python does have a lot of valid uses. IMO the archaic syntax and no types throws me off. For me, typescript or java is easiest to write something quick and dirty because these languages follow the common programming syntax.
@no-better-name
@no-better-name 2 года назад
@@kadensharpin2156 ... master baiter **badum-tss**
@rohit-gupta
@rohit-gupta 3 года назад
factorial 0 will break it
@alibinnaseer
@alibinnaseer 3 года назад
What about (1/2)! ?
@maheedhara4317
@maheedhara4317 3 года назад
@@alibinnaseer bro that will be sqrt(pi) it won't come under normal factorial rules
@catlord69
@catlord69 3 года назад
what about factorial("meow") ?????
@no-better-name
@no-better-name 2 года назад
@@catlord69 hah xd
@no-better-name
@no-better-name 2 года назад
@@maheedhara4317 man, gamma function is weird i tried plugging in some numbers and well, apparently error function is a thing. really interesting and entertaining
@maliin26
@maliin26 3 года назад
What keyboard and switches (if mechanical) are those ones?
@Anonim-im6ln
@Anonim-im6ln 2 года назад
Воу!)😆
@enesaladag7387
@enesaladag7387 2 года назад
How u used function before complete to define it
@user4gent416
@user4gent416 2 года назад
Keyboard sounds like asmr
@anadibrothers-yourwaytorel5259
@anadibrothers-yourwaytorel5259 2 года назад
Woah.. I'm gonna try this
@user-pf1cg8uz1d
@user-pf1cg8uz1d 3 года назад
most satisfying keyboard sound
@TNtubeDev
@TNtubeDev 2 года назад
The condition should be if n==0 and not 1, 'cause factorial(0) should return 1
@sushimunch6459
@sushimunch6459 3 года назад
Wow u smart
@vareden1770
@vareden1770 2 года назад
when the import is sus 😳
@alongcoh
@alongcoh 2 года назад
By limiting your sys commands to a margin of n-1, you can actually return a better response for the config.sys file that you initially created. This of course is complete BS and I have literally no idea what I’m talking about. 🤷🏼‍♂️
@josefkaras7519
@josefkaras7519 3 года назад
Nice
@BeatRush2011
@BeatRush2011 2 года назад
Now run factorial(0) 😈
@duhOhuh
@duhOhuh 3 года назад
I think he drag clicked!
@UnM4rked
@UnM4rked 2 года назад
That looks like lua not gonna lie
@tuhoclaptrinh3158
@tuhoclaptrinh3158 2 года назад
What is your keyboard? Is this mechanic keyboard?
@EvgenSuit
@EvgenSuit 3 года назад
But what if the parameter of factorial function wil be 0? I think you should've could considered adding one more if statement,because all calculations will be in vain
@carbun.
@carbun. 3 года назад
What
@palmberry5576
@palmberry5576 3 года назад
@@carbun. basically, because it only checks if it is equal to one(which is what it would be equal to on the last step of recursion for positive integers), 0 or lower will never satisfy the condition meaning it will keep calling the function until it errors
@laenprogrammation
@laenprogrammation 3 года назад
factorial(0) = 1 fyi
@no-better-name
@no-better-name 2 года назад
@@laenprogrammation supposed to be, they didn't define it though
@ballsuckervr
@ballsuckervr 2 года назад
Program?
@GimliGame
@GimliGame 2 года назад
Может плохо понимаю или там должно быть factorial (n+1) и он будет по наросту идти , а не по уменьшению как тут ?
@user-nq9oe8hv6t
@user-nq9oe8hv6t 2 года назад
Нет, он все правильно написал
@Shahuang
@Shahuang 2 года назад
Числа Фибоначчи
@CHECKERCE
@CHECKERCE 2 года назад
1:00
@ytop4ikrus798
@ytop4ikrus798 3 года назад
А что по времени выполнения?
@bad-_-boy
@bad-_-boy 3 года назад
не более секунды
@ko-Daegu
@ko-Daegu 3 года назад
Why does YT stories looks so weird ?? Sup with these bad logos that reminds me with my collage project
@nepheo5243
@nepheo5243 2 года назад
TIL Python users don't know how to print to a file
@rotrhino
@rotrhino 3 года назад
Все же лучше не пользоваться рекурсией и все разворачивать по мере возможности.
@khodis2002
@khodis2002 3 года назад
Если там не больше 50 коллов, то не думаю, что это проблема. Например в квиксорте
@pratik4833
@pratik4833 2 года назад
I want to code that fast
@igorodnogulov2395
@igorodnogulov2395 Год назад
У меня короче код получился и все работает,при чем можно выбрать длину строки
@knifest323
@knifest323 2 года назад
лол с лимитом
@govindarampersad31
@govindarampersad31 3 года назад
How do I get my python to look like that
@kevinfrankdevid5452
@kevinfrankdevid5452 3 года назад
What do you mean? If you talking about syntax highlighting, it's a "PyCharm".
@flo7968
@flo7968 3 года назад
Thats roughly how all JetBrains IDEs look. Syntax highlighting though is supported throughout all IDEs and even some text editors. Just search up Python IDE and choose by preference or simply download PyCharm Community Edition for a safe bet.
@DarF1ne
@DarF1ne 2 года назад
Какой редактор кода?
@KEN_LUCIOUS
@KEN_LUCIOUS 3 года назад
2000!
@user-tn2ll3rv2x
@user-tn2ll3rv2x 3 года назад
2000!
@enricogolfen
@enricogolfen 3 года назад
2000!
@mariomuysensual
@mariomuysensual 2 года назад
Lol its faster to do a for cycle snd thats it
@taureon_
@taureon_ 2 года назад
you dont need recursion to do factorial
@derekyoungman3895
@derekyoungman3895 2 года назад
You don’t need recursion to do anything but sometimes it’s better to use recursion
@ScROnZjara
@ScROnZjara 3 года назад
Каким софтом вы пользуетесь для написания кода? Спасибо
@zarpach1551
@zarpach1551 3 года назад
pyCharm повсеместный стандарт)
@lev9240
@lev9240 2 года назад
Что за программа?
@beechass4451
@beechass4451 3 года назад
So.....you use factorials to define factorials.Great!
@coffeeyu8484
@coffeeyu8484 3 года назад
What font is he using??
@Vodka665
@Vodka665 2 года назад
I think it is “JetBrains Mono”.
@tanmaysinghal8370
@tanmaysinghal8370 3 года назад
What were we supposed to understand by this video?
@unknownunknown-sx7mr
@unknownunknown-sx7mr 3 года назад
Какие переключатели клавиатуры у вас есть?
@khodis2002
@khodis2002 3 года назад
I like this use of the translator. You can see it right away, but it's interesting when this happens.
@iwmmwi1038
@iwmmwi1038 2 года назад
I am arbic and there is some words I don't understand so I can't understand what is this?
@TheJackal917
@TheJackal917 3 года назад
One question - why?
@laenprogrammation
@laenprogrammation 3 года назад
yes but factorial(0)=1 so your function does not work
@jonahfarrell6235
@jonahfarrell6235 3 года назад
Which program is this
@macicoinc9363
@macicoinc9363 2 года назад
I believe it is PyCharm
@aldianandaprasetya6876
@aldianandaprasetya6876 2 года назад
Import Sheeessshhhhh
@airwell2017
@airwell2017 2 года назад
Imposter in the sys
@robercarrillo1894
@robercarrillo1894 3 года назад
What is this IDE
@yousufhossain9768
@yousufhossain9768 3 года назад
Did he created a new file or it was existed before?
@Vodka665
@Vodka665 2 года назад
A new file.
@undercawa1109
@undercawa1109 3 года назад
What the fuck? You can make a file with "print"?
@subha1818
@subha1818 2 года назад
What will the function return for 0! 🤔
@thatotherandrew_
@thatotherandrew_ 2 года назад
It'll hit RecursionError
@pmmeurcatpics
@pmmeurcatpics 2 года назад
it would be better to write the if-statement as if n == 0 or n == 1: return 1
@nikitalevanov1398
@nikitalevanov1398 2 года назад
What is it???
@Ayanami00
@Ayanami00 2 года назад
Mines don't work
@philpalbert6383
@philpalbert6383 2 года назад
What is recursion?
@ewertonal
@ewertonal 2 года назад
Noob move by using an else clause after a return statement
@_timestamp
@_timestamp 2 года назад
This is wrong. factorial(0) # zero factorial(-3) # negative factorial(3.1415) # wrong type factorial("string") # wrong type ...the list goes on
@Astromath
@Astromath 2 года назад
0! = 1
@sritimanadak3937
@sritimanadak3937 3 года назад
The base case is wrong
@Ostup_Burtik
@Ostup_Burtik 3 года назад
123 просмотра 0-0
@iwmmwi1038
@iwmmwi1038 2 года назад
I can't understand what is this.
@Gainshu_lis
@Gainshu_lis 3 года назад
Amongsys
@smellthel
@smellthel 3 года назад
THICC
@kaydentheyummykid4819
@kaydentheyummykid4819 2 года назад
Æ
@misaalanshori
@misaalanshori 3 года назад
What kind of calculation needs the result of factorial 2000?
@IlliterateSorcerer
@IlliterateSorcerer 3 года назад
Why tf does it have a recursion limit
@yousufhossain9768
@yousufhossain9768 3 года назад
It didn't have a limit unless you put n-1.. When a function call its self its called recursion. Well, the function is gonna call its self until the value of n = 1.. And everytime is trigger it will decrease by 1 from the initial value. This is a good practice but loop is faster.. But recursion is great for finding value
@IlliterateSorcerer
@IlliterateSorcerer 3 года назад
@@yousufhossain9768 I know what recursion is but the question is why does a limit for it exist in Python Stack trace issues?
@yousufhossain9768
@yousufhossain9768 3 года назад
@@IlliterateSorcerer maybe he set a limit for safety.. But it never required from first places .
@IlliterateSorcerer
@IlliterateSorcerer 3 года назад
@@yousufhossain9768 No he states that the default is 1000. Fuuuuck this I'll just stick to c++
@farhanaditya2647
@farhanaditya2647 3 года назад
@@IlliterateSorcerer Because why not? People can make a mistake. Without a safeguard like that, a simple mistake could crash the whole system.
@mrgaxapok.
@mrgaxapok. 2 года назад
import sus
@rau149
@rau149 3 года назад
What did i see?
@sina_1239
@sina_1239 3 года назад
Don't you run outta ram?
@macicoinc9363
@macicoinc9363 2 года назад
It is very unlikely considering the recursion depth is only 2002 and the max integer has < 2002*3 digits.
@coddr4778
@coddr4778 3 года назад
Wait what
@specialmaster1938
@specialmaster1938 3 года назад
спасибо вам , не забрасывайте главно
@thanksforyourliquidity
@thanksforyourliquidity 3 года назад
What even is recursion hahaha
@narutoff9247
@narutoff9247 3 года назад
How to put = on visual studio 😅
@FabioGamingFG
@FabioGamingFG 3 года назад
You clearly dont know how to use a keyboard my guy
@iisky1
@iisky1 3 года назад
@@FabioGamingFG lmao
@silenthooman
@silenthooman 2 года назад
Else is not needed
@FlippinFingers
@FlippinFingers 3 года назад
What is this even used for 😅😅
@sichOhhte
@sichOhhte 3 года назад
Ух епт... Я когда вижу такие большие числа, зная, что это ввчислила машина, думаю: блин, ну нафиг, больше так делать не буду, мало ли сбой к чертям произойдет, уф...
@terrydav1s
@terrydav1s 3 года назад
похуй
@user-eh7zj8mt5d
@user-eh7zj8mt5d 2 года назад
Что это такое?
@desert915
@desert915 3 года назад
The sound is annoying
@smov6136
@smov6136 2 года назад
ей а почему тут только англичанин? Ю
@comingflex
@comingflex 2 года назад
хз очень странно
@mircrypti5417
@mircrypti5417 3 года назад
Бро сделай видос вэбвью приложение для андроида и йос для сайтов своих
@Filmy_HD
@Filmy_HD 3 года назад
А где пояснения, не фига не понятно
@bad-_-boy
@bad-_-boy 3 года назад
Найс рофл
Далее
Python Decorators in 15 Minutes
15:14
Просмотров 427 тыс.
10 Python Basics You Should Know!
10:08
Просмотров 78 тыс.
Клип Уже На Канале #янгер #shorts
00:15
If __name__ == "__main__" for Python Developers
8:47
Просмотров 383 тыс.
Unlocking your CPU cores in Python (multiprocessing)
12:16
Enums considered harmful
9:23
Просмотров 195 тыс.
Алгоритмы на Python 3. Лекция №1
1:20:50
Learn JSON in 10 Minutes
12:00
Просмотров 3,1 млн
Dictionary in Python
12:24
Просмотров 1,3 млн
How to Learn to Code FAST (Do This or Keep Struggling)
11:00