Monday 23 November 2015

Time Complexity of Python Programs With Break Statement

हिंदी में प्रोग्राम को समझाया गया है 

यह पोस्ट में python कार्यक्रम से जुड़े बयानों (functions) अथवा प्रोग्राम की समय जटिलता ( Time Complexity ) खोजने के बारे में है।
ये break स्टेटमेंट इस्सतमल किये हुए प्रोग्राम की समय जटिलता बताता है।

def Function(n):
   count = 0
   for i in range(n / 2, n):  # बाहरी पाश एन / 2 बार निष्पादित होता है।(Outer loop execute n/2 times)
      j = 1
      while j + n / 2 <= n:  # मध्य पाश के पास ब्रेक स्टेटमेंट है (Middle loop has break)
         break
         j = j * 2

      print (count)

Function(20)


इस प्रोगाम में आप ऍन की कोई भी वैल्यू लें सकते है परन्तु जो परिस्थिति दी हुई है ( j + n/2 <= n ) वो हमेशा ही सही रहेगी। इसके परिणाम के रूप में while लूप ख़त्म ( terminate ) हो जाता है। यह प्रोग्राम का while ब्लॉक केवल एक ही बार चलेगा क्योकि ब्रेक स्टेटमेंट प्रोग्राम को while लूप से बहार ले जायेगा और लूप ख़त्म हो जायेगा।
परन्तु फॉर लूप वाला ब्लॉक ऍन बार चलेगा। 

प्रणाम स्वरूप इस पाइथन प्रोग्राम इस समय जटिलता ( Time Complexity ) ओ(n) अथवा  O(n) हो जाएगी। 


Python program explained in English

Here we are going to learn how to find the time complexity of a python program which involves the a break statement.
The program is written in the above segment of this post.

In the program if we put any value of n ( in this case I have taken 20 as the value of n), then the condition inside the while loop ( j + n/2 <= n) remains true and then the execution of break statement takes place which brings us out of the while loop and then clearly we can see that the for loop is running n times. So the overall time complexity of the above program is O(n).

No comments:

Post a Comment