Circuit Switching VS Packet Switching

Circuit Switching VS Packet Switching

Circuit switching and packet switching are the two most prevalent methods for connecting diverse communicating devices. Packet switching, on the other hand, splits the data to be communicated into packets and then sends each packet via the network individually.

Instead of being committed to one communication session at a time, packets from numerous competing communication sessions share network links in packet switching, resulting in the loss of the quality of service guarantees offered by circuit switching.

Circuit Switching was originally intended for voice communication and was not well suited to data transmission. As a result, packet switching emerged as a better data transfer technique. The most significant distinctions between circuit switching and packet switching are listed below.

Differences between Packet switching and Circuit switching

 

Circuit Switching Packet Switching
Circuit switching is Connection oriented, i.e, a semi-permanent connection is established before any useful data gets transferred, and the stream of data is then delivered in the same order as it was sent. Packet switching is connection-less, which means data transfer takes place directly without the need to establish a connection.
In circuit switching, each data unit knows the entire path address that is provided by the source.  This method is inflexible as once a path is set all parts of a transmission follows the same path. In Packet switching, each data unit just knows the final destination address and the intermediate path is decided by the routers. This method is flexible because a route is created for each packet to travel to the destination.
A message is received in the order in which it is sent from the source. Packets of a message are received out of order and all of them get assembled at the destination.
The delay between data units is uniform in case of circuit switching. The delay between data units is not uniform in case of packet switching.
The main disadvantage is that if the connection is lost at any place, the entire communication must be restarted. The main advantage of packet switching is if one path is lost only the packets which are on that path will be restarted. But not the entire data packets.
More reliable. Less reliable.
This is implemented in the Physical layer. This is implemented in the network layer.

Python 2 Vs Python 3 | Which one should You Learn ?

Python 2 Vs Python 3 | Which one should You Learn ?

The considerable difference in the versions of Python makes it difficult for programmer/beginners to understand which among Python 2 and 3 is preferable. However, this article on Python 2 vs Python 3 will help you get a better idea.

If asked which among Python 2 and 3 should a beginner learn, then absolutely we would suggest you learn the latest version i.e Python 3. If you haven’t downloaded it yet, then here is how you can quickly do it now.

The software industry has also started using Python 3 adversely soon after it was declared that Python 2 will no longer be supported after 2020. Yes! You heard it right. You will also no longer receive support for Python 2 after 2020 and hence effort to learn it at this point in time doesn’t make sense. So quickly get started with using Python 3.

However, if are still curious to know the differences, then here they are:

Python 2.x
Python 3.x
Version Python 2.x is legacy
Python 3.x is the present and future of the language
Standard Libraries The final 2.x version 2.7 was released in mid-2010 and no more new versions will be released
Python 3.x is under active development and all recent standard library improvements, for example, are only available by default in Python 3.x
Unicode In Python 2.x, all the strings are stored as ASCII values by default and hence to store Unicode string values you need to define them with “u”
But in Python 3, all strings are stored as Unicode by default
Integer Division In Python 2.x, the resultant of division is always an integer value
Whereas in Python 3 this has been corrected and the resultant will be a float value
Print Function print “hello”
print (“hello”)
Ordering Comparisons Rules of ordering comparisons in Python 2 versions are complex in nature
Python 3 has simplified the rules for ordering comparisons
Iterations It has both range and x range functions to iterate one object or through a list at a time
Here range does what xrange does in Python 2.7 and xrange function is not available

Some of the above differences are explained in detail below.

1) Print Statement -> Print Functions

In Python 2, print is a statement. To print a word, the syntax used is print “word” and to print multiple words, the syntax is print “word1”, “word2”

# Printing in python 2print "IM Prep"print "IM Prep", "Python"
Output:
IM Prep
IM Prep Python

Whereas in Python, print is a function and the syntax is print (“word”). If you emit the parenthesis, then you will end up getting an error.

# Printing in python 3print ("IM Prep");
print ("IM Prep", "Python")

Output: IM PrepIM Prep Python

2) Integer Division

In Python 2, the division of two integers will by default result in an integer value. Whereas in Python 3, the result is a float value by default.

# Printing in python 2.7
a = 10/3print "a =", a

# Printing in python 3
b = 10/3print ("b =", b)

Output:
a = 3
b = 3.3333333333333335

3) Unicode

In Python 2, strings are stored as 8-bit ASCII values by default. To store them as unicodes, you explicitly need to mention “u” before the string. Whereas in Python 3, they are stored as Unicode by default. Unicode is better as it is more versatile than ASCII. Unicode strings will allow you to store symbols, emojis, foreign language letter, roman letters etc.

#Unicodein Python 2 & 3print " I am shukla U0001f44D"
Output in Python 2: I am shukla U0001f44D 
Output in Python 3:am shukla

4) Xrange & Range

Python 2.x has both range and x range functions where as in Python 3, only range function is available and this is similar to x range in Python 2.x.Click here to understand the difference between range and x range with examples.

These are some of the major changes in Python 3 in comparison with Python 2. However, if you want to know all the changes, then check out complete Python 2 and 3 differences.

InfyTQ Questions and Answers | Python Qualifying Round

InfyTQ Questions and Answers | Python Qualifying Round

In this article, we will be discussing some of the InfyTQ questions asked in the InfyTQ sample test released officially by Infosys. These InfyTQ sample questions will give you a fair idea about the difficulty level of the Infytq exam.

Have you registered for the Infosys InfyTQ certification exam? If you haven’t, here’s your chance.

Check out InfyTQ Final Round Python Coding Questions here

InfyTQ Questions | Official Sample Paper Python Qualifying Round

Q1. 

Consider the Python code below.

Assume that the necessary imports have been done.

class Shape (metaclass-ABCMeta) :def _init_(self) :print ( “I am in init”)
  	def draw_shape(self) :passdef set_color(self) :passclass Circle(Shape) :def draw_shape(self) :
          		print(“Draw Circle”)

Which of the following statement(s) is/are TRUE?

i) Class Circle cannot be instantiated as it does not implement the set_color() method

ii) The above code will not compile because class Shape has two abstract methods

A. Both i) and ii) are True

B. Neither of i) or ii) is True

C. Only i) is True

D. Only ii) is True

Answer: C

Explanation:

The abstract base class may have more than one abstract method.

Here class Shape has more than one abstract method. It is totally possible for a base class to have more than one abstract method but all these methods have to be implemented by the child class or a TypeError would occur.

Statement 1 says that the child class Circle cannot be instantiated which is true, as it does not implement all the abstract methods of the base class.

Statement 2 says the code will not compile because of the base class having more than one abstract method which is false.

Q.2

Consider the below code snippet.

Identify the most efficient test data set for testing the below code using the ‘Logic Coverage’ technique.

if previous_year_percentage>=75 and previous_year_percentage<=85:
    scholarship=5000elif previous_year_percentage>85 and previous_year_percentage<=95:
    scholarship=8000elif previous_year_percentage>95:
    scholarship=1000else:
    scholarship=0

A. 79, 87, 91, 99

B. 78, 80, 92, 99

C. 74, 77, 90, 100

D. 74, 75, 76, 84, 85, 86, 94, 95, 96, 97

Answer: C

Explanation:

Logic corresponds to the internal structure of the code and this testing is adopted for safety-critical applications such as software used in the aviation industry. This Test verifies the subset of the total number of truth assignments to the expressions.

Basically, you would be testing all the conditional statements for their respective True and False inputs. Here option C and option D provide logic coverage but the efficient one among them would be option C.

Q3.

Consider the following Python code snippet.

class ClassA :
  	_param1=200def _init_(self) :
        	self._param1 = 100def  method1(self) :
         	#Line1____________
  	@staticmethod
  	def method2( ) :
         	#Line2_____________
obj1=ClassA( )
obj1.method1( )
#Line3_____________________

Note: Line numbers are for reference only.

Fill in the blanks at Line1, Line2, and Line3 to get the output as 302.

Choose TWO CORRECT options

A: Line1:ClassA._param1=(ClassA._param1+1)+self._param1 Line2:print(self._param 1+1) Line3:self.method2()

B: Line1:ClassA._param1=(ClassA._param1+2)+ClassA._param1 Line2:print(ClassA._param1) Line3:ClassA.method2()

C: Line1:ClassA._param1=(ClassA._param1+1)+self._param1 Line2:print(ClassA._param1+1) Line3:ClassA.method2()

D: Line1:ClassA._param1=(ClassA._param1+2)+self._param1 Line2:print(ClassA._param 1) Line3:method2()

E: Line1:ClassA._param1=ClassA._param 1 +(self._param1+2) Line2:print(ClassA._param 1) Line3:ClassA.method2()

Answer: You are supposed to select C and E

Explanation:

A:

There will be an error because of a self._param1 call outside the class

B:

This option calls for ClassA.method2()

and method2 is defined as → print(ClassA._param1)

but the method2 is a static method and the values for ClassA.param1 has already been initialized in method1→ (ClassA._param1+2)+ClassA._param1

which is equivalent to → (200+2)+200

That ends up giving us 402 as the output.

C:

This option calls for ClassA.method2()

and method2 is defined as → print(ClassA._param1+1)

but the method2 is a static method and the values for ClassA.param1 has already been initialized in method1→ (ClassA._param1+1)+self._param1

which is equivalent to → (200+1)+100

That ends up giving us 302 as the output.

D:

This option calls for method2()

and method2 is not defined outside the classes so basically it would not return anything

E:

This option again would be a call for the method2→ ClassA.method2()

and method2 is defined as → print(ClassA._param1)

but the method2 is a static method and the values for ClassA.param1 has already been initialized in method1→ ClassA._param1+(self._param1+2)

which is equivalent to → 200+(100+2)

That ends up giving us 302 as the output.

So you can choose C and E.

Q4.

What is the output of the code given below?

def fun(input_list,index):try:
        output_list = [ 0 ]*len(input_list)
        output_list [index] = input_list[index]/int(input_list[index+1])
        return output_list
    except ValueError :
        print("Invalid value")
    except ZeroDivisionError :
        print("Division by zero")
    finally :
        print("End of function")
try :
    list1 = [2,4,'6',2,8]
    list2 = fun(list1,  4except TypeError :
    print ("Invalid type")
except IndexError :
    print ("Invalid index")
finally :
    print ("End of program")

A: 

Invalid value

End of function

End of program

B:

Division by zero

End of function

End of program

C:

End of function

Invalid index

End of program

D:

End of function

Invalid type

End of program

Answer: C

Explanation: The syntax of the try-catch block would basically be:

try:

# Some Code….

except:

# optional block

# Handling of exception (if required)

finally:

# Some code …..(always executed)

So here, the list is passed to the function and the execution of the fun method begins, but there would be an index error because of output_list [index] = input_list[index]/int(input_list[index+1]), this would be caught in the second try-catch block. Since there is nothing to be caught in the first try-catch block it would execute and print the statement in the finally block of the first try-catch block which is End of function.

Next up, the index error will be handled and the respective statement Invalid index will be printed.

In the end, the finally block of the second try-catch block will be executed to print End of program.

So the order of the output would be:

End of function

Invalid index

End of program

Q5.

Consider the Python code below

class ClassA:def first_method(self):
        print("Johnny Johnny..., ")
    def second_method (self):
        print ("Yes Papa. ")
    def third_method (self):
        print("Eating Sugar..., ")
class ClassB (ClassA):def second_method (self):
        super () .first_method ()
        super ().second_method ()
        super() .third_method ()
        print("No Papa. ")
    def third_method (self):
        print("Telling Lies..., ")
class ClassC (ClassB):def first_method (self):
        print("Open your mouth..., Ha. Ha. Ha.")
    def second_method (self):
        print ("No Papa. ")
    def third_method (self):
        super().second_method()
        super() .third_method()
        self. second_method()
obj_A=ClassA()
obj_B=ClassB()
obj_C=ClassC()
#Line 1

 

Which among the below options if written at #Line 1, prints the rhyme correctly?

Choose TWO CORRECT options.

The expected output for your reference:

Johnny Johnny…,

Yes Papa.

Eating Sugar…,

No Papa.

Telling Lies…,

No Papa.

Open your mouth…,

Ha. Ha. Ha.

A:

obj_A.third_method()

obj_B.second_method()

obj_C.first_method()

obj_A.second_method()

B:

obj_C.third_method()

obj_B.second_method()

obj_A.first_method()

obj_C.first_method()

C:

obj_C.third_method()

obj_C.first_method()

D:

obj_B.second_method()

obj_B.third_method()

obj_C.second_method()

obj_C.first_method()

Answer: C

Explanation:

The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class. In Python, super() has two major use cases. Allows us to avoid using the base class name explicitly and working with Multiple Inheritance.

In this particular case, the base class methods would be called whenever there is a super keyword used. The correct order of the execution would be when the instance is created related to ClassC and the method in the base class is used via C by the super keyword.

Q6.

Number 14 needs to be searched using BINARY SEARCH in the following sorted list of numbers:

1, 3, 7, 9, 14, 19, 45

How many comparisons will be required to conclude that the number 14 is found at 5th position?

Note: We have used integer division for finding the middle element and the index starts with 0 (zero)

A. 2

B. 3

C. 4

D. 1

Answer: B

Explanation:

1st iteration: low= 0

high= 6

mid= (0+6)//2 = 3

a[3]<key, which means 9<14

2nd iteration: low = mid+1 = 4

high = 6

mid = (4+6)//2 = 5

a[5]>key, which means 19>14

3rd iteration: low = 4

high = mid – 1 = 4

mid = (4+4)//2 = 4

a[4]==key, which means 14==14.

Q7.

What will be the output of the following Python code snippet?

def func (var1, var2, var3):if(var1<=var2):
        if(var3>-var2):
            if(var1+var2>-var3):
                print(-1)
            else:
                print(-2)
        else:
            if(var1+var3>var2):
                print (-3)
            else:
                print (-4)

func(156,2100,9500)

A. -2

B. -3

C. -4

D. -1

Answer: D

Explanation: 

The first condition is if(var1<=var2) → 156 <= 2100 #True

It will get inside to the next condition if(var3>-var2) → 9500 > (-2100) #True

It will get inside the next condition if(var1+var2>-var3) → (156+2100) > (-9500) #True

Final the last statement print will be executed which prints -1.

Q8.

Consider the below inputs:

input_linked_list (Head to Tail): 1 -> 2 -> 5 -> 3

input_stack (Top to Bottom): 4, 2, 5, 10

def generate (input_linked_list , input_stack):
    temp= input_linked_list.get_head ( )
    element=0while(temp.get_next ( ) is not None):
        temp.set_data (temp.get_data ( )+temp.get_next ( ). get_data ( )+element)
        if temp.get_data ( ) %2 !=0:
            temp.set_data(temp.get_data ( ) +input_stack.pop ( ) )
            element=temp.get_data ( )
        else:
            input_stack.push (element )
            element=temp.get_next ( ).get_data ( )
        temp=temp.get_next ( )
    temp.set_data(temp.get_data ( )+input_stack.pop ( ) )

What will be the content of Input_linked_list from head to tail and input_stack from top to bottom after the execution of the function generate?

Assumption: Stack and LinkedList classes, with the necessary methods, are available

A:

input_linked_list (Head to Tail): 7 -> 14 -> 20 -> 5

input_stack (Top of Bottom): 5, 10

B:

input_linked_list (Head to Tail): 5 -> 7 -> 10 -> 5

input_stack (Top of Bottom): 2, 5, 10

C:

input_linked_list (Head to Tail): 7 -> 14 -> 20 -> 3

input_stack (Top of Bottom): 5, 10

D:

input_linked_list (Head to Tail): 7 -> 14 -> 20 -> 5

input_stack (Top of Bottom): 10

Answer: B

Explanation:

All the nodes are checked for the values to be a multiple of 2 and when they are not a value of the stack is popped and added to them and the previous values are overwritten.

Q9.

Consider the following Python code. Choose the correct option with respect to the number of static, instance and local variables in ClassOne:

Class ClassOne :
    	__var_one=1001
    	def__init__(self,var_two) :
	          	self.__var_two=var_two
          		self.__var_five=5def method_one(self) :
          		var_four=50self.__var_five=ClassOne.__var_one+self.__var_two+var_four

A. 0 static variable, 3 instance variables, 2 local variables

B. 1 static variable, 2 instance variables, 2 local variables

C. 1 static variable, 3 instance variables, 1 local variables

D. 2 static variable, 2 instance variables, 1 local variables

Answer: C

Explanation:

static variables: __var_one

instance variables: var_two, __var_five, var_four

local variables: var_four

Q 10.

Consider the following code snippet written in Python:

def fun(num) :if num<1 :
         	return 0elif num%2 == 0 :
         	return fun (num-1)
   	else :
         	return num+fun(num-2)
print (fun (8) )

A. 8

B. 12

C. 20

D. 16

Answer: D

Q 11.

What will be the output of below Python code?

class Vehicle ( ):def __init__(self, color):
        self.color=color
class FourWheeler(Vehicle):def __init__(self,no_of_gears,color):
        super().__init__(color)
        self.no_of_gears=no_of_gears
class TwoWheeler(Vehicle):def __init__(self,engine_cc):
        super().__init__("Red")
        self.engine_cc=engine_cc
        self.color="Blue"
 
maruti=FourWheeler(4, "Red")
print (maruti.color,maruti.no_of_gears)
activa=TwoWheeler(80)
print(activa.color, activa.enigne_cc)

A:

Error as object of TwoWheeler class cannot be created since required number of arguments have not been passed

B:

Red 4

Red 80

C:

Error: Cannot modify the value of attribute color inside TwoWheeler class

D:

Red 4

Blue 80

Answer: C

Explanation: We will not be able to modify the value of attribute colour inside TwoWheeler class, it would indirectly throw an error as ‘TwoWheeler’ object has no attribute ‘enigne_cc’

Q 12.

Consider the following Python function for a vehicle management system. Objective of the code is to record details of vehicles-

def vehicle_record(reg_no,mileage,veh_type,purpose,kickstart,no_of_gears,miles_run) :
    	record=””
    	if(veh_type = = “TwoWheeler”) :
   record=reg_no+”:TwoWheeler:”+ str(mileage)+”:”+kickstart
    	elif(veh_type = = “FourWheeler”) :
               record=reg_no+”:FourWheeler:”+str(mileage)+”:”+no_of_gears
           	if(purpose = = “Commercial”):
                      record=record+”:Commercial FourWheeler:”+miles_run
    	return record
record=vehicle_record(“KA09Z7211”,15,”FourWheeler”,”Commercial”,”No”,”4”,”89000”)

What will be the optional class structure if this was to be re-written in Object-oriented programming?

A. 4 independent classes: Vehicle, TwoWheeler, FourWheeler, CommercialFourWheeler

B. 3 classes with inheritance: TwoWheeler and FourWheeler inherit from Vehicle

C. 4 classes with inheritance: TwoWheeler, FourWheeler and CommercialFourWheeler which inherit from Vehicle

D. 4 classes with inheritance: TwoWheeler and FourWheeler inherit from Vehicle; CommercialFourWheeler inherit from FourWheeler

Answer: D

Explanation: The main objective of object-oriented programming is code reusability and in the above case it can be done by segregation the parameters into parent-child class pairs. The optimum design would be as given below:

So in this segregation the common features of vehicle class can be used by all its child classes and likewise the common features of four wheeler class can be used by the commercial class.

This arrangement is suggested in option D

Q 13.

Consider the code given below.

def display_cat_details(color, name1, name2=none, name3=None) : #Line 1pass
display_cat_details(“Brown”, “Fluffy”,”Snow”) 

Which of the following function signatures when replaced in Line 1 would continue to execute successfully?

Choose two correct answers

A. def display_cat_details(color, *names,name1)

B. def display_cat_details(color, name_list)

C. def display_cat_details(color, *names)

D. def display_cat_details(color, name1,*names)

Answer: Option C and D are supposed to be selected

Explanation:

A. Is again a invalid syntax as display_cat_details() takes 2 positional arguments but 3 were given

B. Same reason as A

C. This would take in all the 3 respective parameters and execute successfully

D. This also would take all the 3 parameters even though there are only 2 parameters given in the function definition, because of *names

Q 14.

Consider the below code:

my_queue1 = Queue(3)
my_queue2 = Queue(3)
for index in range(0, 3):
    my_queue.enqueue(index *3)
for index in range(0, 3):
    if(index == 2):
        break
    my_queue2.enqueue(my_queue1.dequeue ( ) )
my_queue2.enqueue(12)

Assumption: Queue class, with the necessary methods, is available

What is the status of my_queue1 and my_queue2 after the execution of above code?

A:

my_queue1(front->rear):0, 3, 6

my_queue2(front->rear):0, 3, 12

B:

my_queue1(front->rear):6

my_queue2(front->rear):0, 3,

C:

my_queue1(front->rear):6

my_queue2(front->rear):0, 3, 12

D:

my_queue1(front->rear):Queue is empty.

my_queue2(front->rear):0, 3, 12

Answer: C

Explanation: Here the queue1 is being filled as 0, 3, 6 (front to rear). When this is dequeued the order would be 0 first, then 3 and finally 6. So the 1st dequeue would give us 0, so now queue2 becomes 0 (front to rear). Next dequeue of queue1 would give us 3, which would be the 2nd enqueue for queue2. So now queue2 would be 0, 3 (front to rear). The dequeue of queue1 would stop here as the index reaches 2. Final enqueue of queue2 would happen with a 12. So finally queue2 becomes 0, 3, 12 (front to rear).

Q 15.

The following numbers are to be stored in a hash table(arriving in the order shown) using the hash function.

h(k)=k%4

4, 7, 16, 9, 17, 22

Identify for which numbers collision will NOT occur after mapping the numbers with the given hash function.

A. 4, 7, 16 and 9

B. 7, 9, 17 and 22

C. 7 and 22

D. 4, 16, 9 and 17

Answer: C

Explanation:

A. There would be a collision between 4 and 16 which would both give the value 0 for 4%4 and 16%4.

B. There would be a collision between 9 and 7 which would both give the value 1.

C. There would be no collision between 7 and 22.

D. All four numbers would end up in a collision.

Q 16. 

Alister is a Python developer who has written the below code.

He desires the output to be 123 Volvo, but, he is unable to proceed due to an error

class Car:def ___init__(self,car_id,car_name) :
         	self.__car_id=car_id                                             #Line 1self.car_name=car_name                                    #Line 2
carl1=Car(123, “Volvo”)                                                  #Line 3
print(car1.car_id,car1.car_name)                                   #Line 4

Choose two options from below which he should implement to get the desired output?

Note: Line numbers are for reference only.

A. Add a method to the Car class as follows:def get_car_id(self): return car_id

B. Add a method to the Car class as follows:def get_car_id(self): return self._ car_id

C. Change Line 4 to : print(car1.get_car_id(),car1.car_name)

D. Change Line 4 to : print(car1.___car_id,car1.car_name)

Answer: Option B and C supposed to be selected

Explanation: Here we are asked to print 123 Volvo  which is being sent as an argument to the function present inside the class Car. But there are 2 problems here.

  • The car_id is a private variable inside class Car which means that you would have to define a function inside class Car to access the variable.
  • The print statement has car1.car_id  which is again not possible as the simple object created for a class cannot access the private variables inside the class

The solutions for these are as follows:

  • Defining a function to access the private variable, which is given in option B→ Add a method to the Car class as follows:def get_car_id(self): return self._ car_id
  • Use the print statement to access the private variable using the function in class Car which is given in option C→ Change Line 4 to : print(car1.get_car_id(),car1.car_name)

Hence, Option B and C supposed to be selected

Q 17.

Given the following linked_list:

linked_list(Head to Tail): 1->4->6->7->9

What would be the state of the linked list after the following Python function is executed when the head node of the above-given linked_list and num=5 are passed as input to the function?

def func(head, num) :
   	temp = head
   	if(head == None) :
          	returnelse :
          	index = 1while(index < num) :
              val = temp.get_data ( )
           	#get_data ( ) returns the data of the node
           	temp = temp.get_next ( )
           	#get_next ( ) returns the link to the next node
           	head.set_data ( val )
            	index +=1
   	temp1 = head.get_data ( )
   	temp.set_data(temp 1)

Assumption: LinkedList class, with the necessary methods, is available.

A. Linkedlist data(Head to Tail): 7 4 6 7 9

B. Linkedlist data(Head to Tail): 1 4 6 7 7

C. Linkedlist data(Head to Tail): 7 4 6 7 7

D. Linkedlist data(Head to Tail): 1 4 6 7 9

Answer: B

Explanation:

The iteration stops when the index value is greater than or equal to 5. Hence the last value 9 will be overwritten with 7.

Q 18.

How many ‘*’(stars)will be printed after executing the below Python code?

num1=5
num2=4while (num2 >= 1) :
     	print (“*”)
     	for index in range (1, num1+1) :
           	print (“*”)
           	num2 -= 1print (“*”)

A. 6

B. 5

C. Infinite loop

D. 7

Answer: D

Explanation: In the beginning of while loop 1 star will be printed. After the control enters the for loop star will be printed 5 times and 1 last star will be printed when the for loop breaks. So altogether 7 stars will be printed.

Q 19.

Consider the below code:

def vending_machine(insert_money,item_id) :if item_id == 101 and insert_money :
          	#Line1#Line2
insert money= True
item_id = 101
print(vending_machine(insert_money.item_id))

Identify the statements to be replaced in Line 1 and Line 2 respectively such that the output is as below:

Disperse the product

Function executed successfully

A:

Line1 : return “Disperse the product”

Line2 : return “Function executed successfully”

B:

Line1 : print (“Disperse the product”)

Line2 : return “Function executed successfully”

C:

Line1 : return “Disperse the product”

Line2 : print (“Function executed successfully”)

D:

Line1 : print (“Disperse the product”)

Line2 : print (“Function executed successfully”)

Answer: B

Explanation:

A. Would just give Disperse the product as the output. As item ID would match.

B. Would first print Disperse the product and then return Function executed successfully

C. Would just give Disperse the product as the output. As item ID would match.

D. Would first print Disperse the product and then print Function executed successfully and the return none to the function call and the same would be printed to the output screen.

Q 20.

John is visiting a zoo. After roaming for sometime, he finds that he has lost his way. John wants to reach the entry/exit gate. He remembers ‘Vans Ice-Cream’, a landmark which he saw while strolling in the zoo. John finds that there are 3 ways to reach Vans Ice-Cream from his current location and from Vans Ice-Cream there are 4 ways to reach the entry/exit gate.

Considering the above scenario, identify the most suitable data structure that can represent all possible ways to reach the entry/exit gate from John’s current location?

A. Graph

B. Tree

C. Stack

D. Queue

Answer: A

Explanation: Graphs are awesome data structures that you use every day through Google Search, Google Maps, GPS, and social media. They are used to represent elements that share connections. The elements in the graph are called Nodes and the connections between them are called Edges. This is a similar instance.

Did you know that Infosys will be conducting their coding contest, i.e HackWithInfy for the 2022 batch?

 

Introduction to Arrays | Types of Arrays and their Representation

Introduction to Arrays | Types of Arrays and their Representation

An Array is a Linear data structure which is a collection of data items having similar data types stored in contiguous memory locations. By knowing the address of the first item we can easily access all items/elements of an array.

Arrays and its representation is given below

  • Array Index: The location of an element in an array has an index, which identifies the element. Array index starts from 0.
  • Array element: Items stored in an array is called an element. The elements can be accessed via its index.
  • Array Length: The length of an array is defined based on the number of elements an array can store. In the above example, array length is 6 which means that it can store 6 elements.

When an array of size and type is declared, the compiler allocates enough memory to hold all elements of data.

For example, an array IM [10] will have 10 elements with index starting from 0 to 9 and the memory allocated contiguously will be 20 bytes. The compiler knows the address of the first byte of the array only. Also, the address of the first byte is considered as the memory address for the whole array.

Normal variables (a1, a2, a3, ….) can be used when we have a small number of elements, but if we want to store a large number of elements, it becomes difficult to manage them with normal variables. Representing many elements with one variable name is the basic idea of arrays.

Why does Array Indexing start with 0?

Let’s try to understand this by taking one example. Assume, we can declare an array of size 10 in the following way.

int a[10];

Here a itself is a pointer which contains the memory location of the first element of the array. Now for accessing the first element, we will write a[0] which is internally decoded by the compiler as *(a + 0).

In the same way, the second element can be accessed by a[1] or *(a + 1). As a contains the address of the first element so for accessing the second element we have to add 1 to it. That’s why here we have written *(a +1). In an array, the index describes the offset from the first element, i.e. the distance from the first element.

Now let’s assume that array indexing starts at 1 instead of 0. In this case for accessing the first element, we have to write a[1] which is internally decoded as *(a + 1 – 1).

Observe here that we have to perform one extra operation i.e. subtraction by 1. This extra operation will greatly decrease the performance when the program is big. That’s why to avoid this extra operation and improve the performance, array indexing starts at 0 and not at 1.

 

Array Operation

Now that we know the basic idea behind an array, let us now look at the various operations that can be performed on arrays.

  • Traverse − Print all the elements in the array one by one.
  • Insertion − Adds an element at the given index.
  • Deletion − Deletes an element at the given index.
  • Search − Searches an element in the array using the given index or the value.
  • Update − Updates an element at the given index.

 

Types of Arrays

The various types of arrays are as follows.

  • One dimensional array
  • Multi-dimensional array

One-Dimensional Array

A one-dimensional array is also called a single dimensional array where the elements will be accessed in sequential order. This type of array will be accessed by the subscript of either a column or row index.

Multi-Dimensional Array

When the number of dimensions specified is more than one, then it is called as a multi-dimensional array. Multidimensional arrays include 2D arrays and 3D arrays.

A two-dimensional array will be accessed by using the subscript of row and column index. For traversing the two-dimensional array, the value of the rows and columns will be considered. In the two-dimensional array IM [3] [4], the first index specifies the number of rows and the second index specifies the number of columns and the array can hold 12 elements (3 * 4).

Similarly, in a three-dimensional array, there will be three dimensions. The array IM [5] [10] [15] can hold 750 elements (5 * 10 * 15).

 

Declaration/Initialization of Arrays

// A sample program for Array Declaration
#include <stdio.h>
int main()
{
int one_dim [10];    # declaration of 1D array
int two_dim [2][2];  #declaration of 2D array
int three_dim [2][3][4] = { 
                     { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
                     { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
                 }; #declaration of 3D array. Here the elements are also defined.return 0;
}
7 Body Language Tips to Ace Your Job Interview

7 Body Language Tips to Ace Your Job Interview

Maintaining a nice, professional, and courteous body language is the single most crucial thing to remember during a job interview. Keep in mind that your behaviour will make an impression even before you begin the interview. Here are a few pointers to help you keep a positive body language throughout your job interview.

Give a power-packed handshake:

The first interaction you will have with the interviewer will be a handshake. A strong and confident handshake will demonstrate to the interviewer that you are not apprehensive about the interview, which is a trait that most candidates who are rejected display. Make sure your hands aren’t sweaty and that your nails are clipped properly.

Maintain eye contact: 

When you’re being interviewed, don’t be hesitant or look away. Make conscious efforts to stare into the interviewer’s eyes while speaking, even if you don’t feel compelled to do so with someone you’ve just met. If there are multiple interviewers, address each one equally and maintain constant eye contact.

Mind your posture:

Wait until you are requested to take a seat before you do so. Maintain a straight posture while sitting while remaining calm. Make it a point to remind yourself not to slouch or lounge. You should keep your legs straight and not cross them. When you’re nervous, don’t fidget with your foot.

Gesture right:

Keep your arms crossed during the interview because it is viewed as resistant to opinions and feedback. Some interviewers, particularly the older ones, regard such a position to be impolite and disrespectful. Another motion to avoid is putting your hands in your pockets, which is perceived as haughty. Instead, make use of your hands by gesturing while speaking, which is a sign of confidence and intellect.

Be interactive: 

Demonstrate your excitement and establish a positive relationship with the interviewer. This shows your self-assurance and ability to quickly adapt to new situations. It also demonstrates that you are not stressed by the interviewer’s pressure, which is a quality that all candidates should possess.

Stay focused: 

Don’t start fiddling with your pen, file, phone, or anything else you’re holding inadvertently. These movements are a sign of worry and anxiety, which interviewers may easily detect. This is interpreted by interviewers as a symptom of your inability to deal with stress. Also, staring around the room is an extremely impolite behaviour.

Manners matter:

Throughout the interview, keep in mind that you should treat the interviewer with as much respect as possible. Make a point of greeting the interviewer both when you enter the room and when you leave. When you sneeze, ask for their forgiveness and thank them.

5 Tips to Build a Top Notch LinkedIn Profile

5 Tips to Build a Top Notch LinkedIn Profile

LinkedIn has revolutionised professional networking in the last decade. It allows you to highlight your primary competencies while also allowing other experts to read your profile and endorse your abilities on a worldwide basis. However, failing to maintain a proper LinkedIn page may not be a good idea. Regularly optimising and adjusting your profile can greatly improve your professional prospects. It’s all about catching the attention of potential employers and business partners with your profile.

Here are 5 tips to increase your profile’s strength on LinkedIn:

1. Add a Professional Profile Picture and Cover Picture

When people look at a profile, the profile image is the first thing they notice. A profile with a professional profile photo receives at least 12 times the number of views as a profile without one. When you update your profile image, it is visible to everyone of your LinkedIn connections in their news feed. It’s crucial to remember that the image should be clean and presentable from the perspective of a colleague.

Including a cover photo can be a game-changer. It’s a great way to show off your professional identity. To come up with the finest possible way to express the professional in you, knock on the creative door of your brain.

2. Write a Sleek Headline

The 120 characters of your profile’s headline should be able to speak volumes of your professional experience. 10 seconds is all you’ve got to sell yourself to your profile’s visitors when they read your headline. Throw in keywords and remodel it to be compelling and interesting.

3. Update Your Profile Continuously

LinkedIn gives you a variety of sections to fill out on your profile to reflect all of your accomplishments and certifications. Using these fields and updating them on a regular basis with accurate and genuine information is very helpful in making your profile visible to a large number of people.

4. Post Engaging Content

To establish your brand image in your professional network, share articles, preferably written by you, photographs, and other types of media that reflect your career and hobbies. The more unique and relevant stuff you produce, the more your fans will notice you.

5. Endorse and Get Endorsed

Recruiters may be interested in hearing about your abilities from people you’ve worked with. It gives your profile more credibility. As a result, LinkedIn Recommendations and Endorsements have taken on a vital role and have grown in popularity. To receive significant Recommendations and Endorsements, approach your supervisors and close coworkers. Returning the favour by honestly complimenting their abilities is a wonderful practise.

Your skills are grouped in a hierarchical order based on the endorsements you receive. Office tools like Microsoft Excel and Microsoft PowerPoint, as well as programming languages like Java and Python, are among the most popular skills on LinkedIn. These are simple to learn on the internet.

Get Access To Our Premium Courses
Install our application from PlayStore and get discounts on our new courses.

Pin It on Pinterest