Are the following code fragments a really logically equivalent. . | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Are the following code fragments a really logically equivalent. .

if x==5: if x==5; x+=1 x+=1 else: if x!=5: x=8 x=8 give answer with a strong and standard reason...thank you..

20th Apr 2020, 12:55 PM
SARTHAK JAIN
SARTHAK JAIN - avatar
4 Answers
+ 5
Given codes are Functionally Equivalent not logically equivalent. Functionally Equivalent because they both shows same behaviour but not are Logically Equivalent because in Code 1, Only x==5 condition is checked by compiler and based on its result, it will execute either of the block. While Code 2, Both of the conditions will be checked, which will be an overhead.
20th Apr 2020, 1:29 PM
Arvind Singh Rawat
Arvind Singh Rawat - avatar
+ 5
In the 1st code, the program will read only the 1st if statement and if it is false it may switch to else statement (meaning 1 at a time). But in 2nd code the program will read the 2nd if condition too. hence they're not equivalent.
20th Apr 2020, 1:30 PM
Tricker
+ 5
The example to the left (using if-else) does only one evaluation of <x> value, it checks whether <x> value equals to 5. The example to the right (using two `if`) does two evaluation of <x> value, it checks whether <x> value equals to 5, and then it checks whether <x> value not equal to 5. IMHO The example to the left is *relatively* more efficient because comparison is done only once.
20th Apr 2020, 1:34 PM
Ipang
0
Thanks for the answer. .👏👍
23rd Apr 2020, 4:01 PM
SARTHAK JAIN
SARTHAK JAIN - avatar