Author name: Prasanna

Selenium IDE Tutorial For Beginners | What Is Selenium IDE

Selenium Python – Selenium IDE

In this chapter, we will discuss the Selenium IDE component. This component allows us to record and playback our tests. It is an integral component of the Selenium project and has been recently upgraded and brought back into function with the help of the organization Appiitools.

Selenium IDE, also known as SIDE stands for Selenium Integrated Development Environment. It is one of the four projects of the Selenium ecosystem. The earlier version of Selenium IDE worked only on the Firefox browser. But the changes in the Firefox browser from version 55 didn’t allow Selenium IDE integration. At this juncture, Appiitools helped the Selenium community with a group of dedicated engineers (https://github.com/seleniumHQ/selenium-ide/graphs/ contributors) and brought back Selenium IDE. The current version supports both Firefox and Chrome browsers.

Structure

  • Installing Selenium IDE • Walkthrough of the demo application
  • Creating our first test
  • Selenium IDE commands

Objective

The Selenium IDE component is used to record and play backtests. The current version, which supports both Firefox and Chrome browsers, has a rich feature list. It now allows running tests in parallel, supports JavaScript execution, allows usage of if conditions, and many such cool things. To know more about it, read the article available here:

https://applitools.com/blog/why-Selenium-ide-20197utm_referrer=https://www.google.com/

Installation of Selenium IDE

To install Selenium IDE, we have to follow the below-mentioned instructions:
1. Open the Chrome browser and follow this link:
https://www.seleniumhq.org/selenium-ide/
2. Here, we need to select the choice, Chrome or Firefox download.
3. It will open a new browser window, with the option asking Add to Chrome as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 1

4. You need to select it.
5. It will launch a popup, asking permission. Select Add extension as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 2

6. You will now be able to see the Selenium IDE icon in your browser menu bar. N

After installing the Selenium IDE, we need to have a look at a demo web application. We will need this application to understand a few concepts of test automation using Selenium. So let us get introduced to it.

Introduction to demo web application

We will consider a demo web application, which is an e-commerce website. As we learn the concepts of test automation with Selenium using Python as a programming language, we will use functional flows from the web application. We will also look at a few other web applications as we learn to handle some specific Html elements and deal with some specific scenarios.

The URL of the demo application is http://practice.bpbonline.com/ catalog/index.php
As you follow the URL, you will see the following screen:

Selenium Python - Selenium IDE chapter 2 img 3

Following are some of the specific functional flows in the application:

  • Register the user
  • Login and logout of the user
  • Change profile of the user
  • Change the password of the user
  • Buy product
  • Search product

From the previous list of application business scenarios, we will take the login-logout business scenario as a sample one for our first record and playback script in Selenium IDE. Record script basically means with the help of Selenium IDE, we will capture the user actions as we perform the steps to login and then log out from the application. These will be captured by the Selenium IDE, as commands. It will then be played back, where Selenium IDE will launch the browser and will be able to perform the exact steps to log in and log out of the application without any user intervention.

Let’s perform the following steps for login-logout:
1. Open the application using the URL: http://practice. bpbonline.com/catalog/index.php
2. Click on the My Account link.
3. Fill in the user details; you can use the following user credentials:

Or you can also create your own account, by registering yourself and then using those credentials.
4. Click on the Sign-in button
5. Click on the Log Off link
6. Click on the Continue link
Please note the above scenario is not a test case, as we have added no steps for the validation. There are only test steps.

Record and playback in Selenium IDE

The following are the steps we need to perform for recording and playing back in Selenium IDE:
1. Open Chrome browser.
2. On it, click on the Selenium IDE icon. It will popup Selenium IDE window as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 4

3. Here, we will select Record a new test in a new project.
4. Provide a project name on the next screen.
5. Then in the next screen, provide the base URL for recording:

Selenium Python - Selenium IDE chapter 2 img 5

6. Click here on START RECORDING.
7. This will launch the browser with the application URL, and a message Selenium IDE is recording… Now, whatever steps we perform on the browser, will all be captured by the IDE. Check the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 6

7. After performing all the steps, close the browser, and on the Selenium IDE, click the OP (stop button).
8. Provide a name to the test, and save the project at a location in your system.
9. After the login logout steps are captured, your text should look as follows:

Selenium Python - Selenium IDE chapter 2 img 7

It could be possible that Selenium IDE may capture some other locator value for the same object which you see in the target field, which is absolutely fine, as long as you are able to replay the test successfully.

There could be some other extra steps captured as Selenium IDE captures every mouse action, we need to delete those extra steps and only have those steps that match our manual action.

Structure of Selenium IDE Test

If we look at the above image, there are three columns that form a Selenium IDE test:
• Command, which provides information of the action being performed.
• Target, which talks about the object on which the action is to be performed.
• Value, which talks about the data which will be used in the test.
The commands of Selenium IDE fall under three categories, as follows:
• Action: Those commands, which change the state of the application.
• Assertion: Those commands which verify the state of the application after it is performed. There are two types of assertion commands that are as follows:

  1. Verify: These commands, if they fail, still allow execution of the next step in the test case.
  2. Assert: These commands, if they fail, don’t allow the execution of the next step in the test case.

• Accessor: Those commands which allow storage of value, or creation of variables to be used in the test.

Let us write the login-logout scenario, this time with the validation steps:

  1. Open the application.
  2. Click the My Account link.
  3. Type the E-mail address and Password.
  4. Click the Sign In button.
  5. Verify the My Account Information text on the screen.
  6. Click on the Log Off link.
  7. Click on the Continue link.
  8. Verify Welcome to BPB Online text on the screen.

To record the above scenario, we will perform the same steps as we did for the login-logout one, except for steps 5 and 8, where we will perform the following.
9. Add the Command verify text during the recording after you have logged in. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 8

10. Now we will select the Target for that we click on the icon
[↵]and highlight and click the element, whose text we need to capture for verification. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 9

11. We copy the text from here and put it in the Value field. So finally, our command would look like the following:

Selenium Python - Selenium IDE chapter 2 img 10

12. We will perform a similar action for step 8.
13. Complete the steps of recording, and save the test for playback. As you playback the test, you will see all the steps in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 11

14. Now, for the same test, if we change the command from verifying the text, to assert text We will see that the execution will get halted at the step of failure. This is shown as follows:
in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 12

14. Now, for the same test, if we change the Command from verifying ‘ text, to assert text we will see that the execution will get halted at the step of failure. This is shown as follows:

Selenium Python - Selenium IDE chapter 2 img 13

So there are three states of execution here:

  • Green: All pass
  • Red: Fail
  • White: Not executed

Conclusion

In this chapter, we discussed the Selenium IDE component. We saw how we could use it for recording and playing backtests. We could use Selenium IDE for proofing concepts, to see if our application supports Selenium or not. Sometimes we struggle to find a locator for an object, in such cases recording the scenario in Selenium IDE is also helpful. In our next chapter, we will discuss the concept of locators, what techniques Selenium uses to recognize objects on web applications.

Related Articles:

Selenium IDE Tutorial For Beginners | What Is Selenium IDE Read More »

Python Interview Questions on HR Questions

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on HR Questions

Question 1:
Tell me about a time when you worked additional hours to finish a project.
Answer:
It’s important for your employer to see that you are dedicated to your work, and willing to put in extra hours when required or when a job calls for it. However, be careful when explaining. why you were called to work additional hours – for instance, did you have to stay late because you set goals poorly earlier in the process? Or on a more positive note, were you working additional hours because a client requested for a deadline to be moved up on short notice? Stress your competence and willingness to give 110% every time.

Question 2:
Tell me about a time when your performance exceeded the duties and requirements of your job.
Answer:
If you’re a great candidate for the position, this should be an easy question to answer – choose a time when you truly went above and beyond the call of duty, and put in additional work or voluntarily took on new responsibilities. Remain humble, and express gratitude for the learning opportunity, as well as confidence in your ability to give a repeat performance.

Question 3:
What is your driving attitude about work?
Answer:
There are many possible good answers to this question, and the interviewer primarily wants to see that you have a great passion for the job and that you will remain motivated in your career if hired. Some specific driving forces behind your success may include hard work, opportunity, growth potential, or success.

Question 4:
Do you take work home with you?
Answer:
It is important to first clarify that you are always willing to take work home when necessary, but you want to emphasize as well that it has not been an issue for you in the past. Highlight skills such as time management, goal-setting, and multitasking, which can all ensure that work is completed at work.

Question 5:
Describe a typical workday to me.
Answer:
There are several important components in your typical workday, and an interviewer may derive meaning from any or all of them, as well as from your ability to systematically lead him or her through the day. Start at the beginning of your day and proceed chronologically, making sure to emphasize steady productivity, time for review, goal-setting, and prioritizing, as well as some additional time to account for unexpected things that may arise.

Question 6:
Tell me about a time when you went out of your way at your previous job.
Answer:
Here it is best to use a specific example of the situation that required you to go out of your way, what your specific position would have required that you did, and how you went above that. Use concrete details, and be sure to include the results, as well as reflect on what you learned in the process.

Question 7:
Are you open to receiving feedback and criticisms on your job performance, and adjusting as necessary?
Answer:
This question has a pretty clear answer – yes – but you’ll need to display knowledge as to why this is important. Receiving feedback and criticism is one thing, but the most important part of that process is to then implement it into your daily work. Keep a good attitude, and express that you always appreciate constructive feedback.

Question 8:
What inspires you?
Answer:
You may find inspiration in nature, reading success stories, or mastering a difficult task, but it’s important that your inspiration is positively based and that you’re able to listen and tune into it when it appears. Keep this answer generally based in the professional world, but where applicable, it may stretch a bit into creative exercises in your personal life that, in turn, help you in achieving career objectives.

Question 9:
How do you inspire others?
Answer:
This may be a difficult question, as it is often hard to discern the effects of inspiration on others. Instead of offering a specific example of a time when you inspired someone, focus on general principles such as leading by example that you employ in your professional life. If possible, relate this to a quality that someone who inspired you possessed, and discuss the way you have modified or modeled it in your own work.

Question 10:
How do you make decisions?
Answer:
This is a great opportunity for you to wow your interviewer with your decisiveness, confidence, and organizational skills. Make sure that you outline a process for decision-making, and that you stress the importance of weighing your options, as well as in trusting intuition. If you answer this question skillfully and with ease, your interviewer will trust in your capability as a worker.

Question 11:
What are the most difficult decisions for you to make?
Answer:
Explain your relationship to decision-making, and a general synopsis of the process you take in making choices. If there is a particular type of decision that you often struggle with, such as those that involve other people, make sure to explain why that type of decision is tough for you, and how you are currently engaged in improving your skills.

Question 12:
When making a tough decision, how do you gather information?
Answer:
If you’re making a tough choice, it’s best to gather information from as many sources as possible. Lead the interviewer through your process of taking information from people in different areas, starting first with advice from experts in your field, feedback from coworkers or other clients, and looking analytically at your own past experiences.

Question 13:
Tell me about a decision you made that did not turn out well.
Answer:
Honesty and transparency are great values that your interviewer will appreciate – outline the choice you made, why you made it, the results of your poor decision – and finally (and most importantly!) what you learned from the decision. Give the interviewer reason to trust that you wouldn’t make a decision like that again in the future.

Question 14:
Are you able to make decisions quickly?
Answer:
You may be able to make decisions quickly, but be sure to communicate your skill in making sound, thorough decisions as well. Discuss the importance of making a decision quickly, and how you do so, as well as the necessity for each decision to first be well-informed.

Question 15:
Ten years ago, what were your career goals?
Answer:
In reflecting back on what your career goals were ten years ago, it’s important to show the ways in which you’ve made progress in that time. Draw distinct links between specific objectives that you’ve achieved, and speak candidly about how it felt to reach those goals. Remain positive, upbeat, and growth-oriented, even if you haven’t yet achieved all of the goals you set out to reach.

Question 16:
Tell me about a weakness you used to have, and how you changed it.
Answer:
Choose a non-professional weakness that you used to have, and outline the process you went through in order to grow past it. Explain the weakness itself, why it was problematic, the action steps you planned, how you achieved them, and the end result.

Question 17:
Tell me about your goal-setting process.
Answer:
When describing your goal-setting process, clearly outline the way that you create an outline for yourself. It may be helpful to offer an example of a particular goal you’ve set in the past, and use this as a starting point to guide the way you created action steps, check-in points, and how the goal was eventually achieved.

Question 18:
Tell me about a time when you solved a problem by creating actionable steps to follow.
Answer:
This question will help the interviewer to see how talented you are in outlining, problem resolution, and goal-setting. Explain thoroughly the procedure of outlining the problem, establishing steps to take, and then how you followed the steps (such as through check-in points along the way, or intermediary goals).

Question 19:
Where do you see yourself five years from now?
Answer:
Have some idea of where you would like to have advanced to in the position you’re applying for, over the next several years. Make sure that your future plans line up with you still working for the company, and stay positive about potential advancement. Focus on future opportunities, and what you’re looking forward to – but make sure your reasons for advancement are admirable, such as greater experience and the chance to learn, rather than simply being out for a higher salary.

Question 20:
When in a position, do you look for opportunities to promote?
Answer:
There’s a fine balance in this question – you want to show the interviewer that you have the initiative and motivation to advance in your career, but not at the expense of appearing opportunistic or selfishly motivated. Explain that you are always open to growth opportunities, and very willing to take on new responsibilities as your career advances.

Question 21:
On a scale of 1 to 10, how successful has your life been?
Answer:
Though you may still have a long list of goals to achieve, it’s important to keep this answer positively focused. Choose a high number between 7 and 9, and explain that you feel your life has been largely successful and satisfactory as a result of several specific achievements or experiences. Don’t go as high as a 10, as the interviewer may not believe your response or in your ability to reason critically.

Question 22:
What is your greatest goal in life?
Answer:
It’s okay for this answer to stray a bit into your personal life, but best if you can keep it professionally focused. While specific goals are great, if your personal goal doesn’t match up exactly with one of the company’s objectives, you’re better off keeping your goal a little more generic and encompassing, such as “success in my career” or “leading a happy and fulfilling life.” Keep your answer brief, and show a decisive nature – most importantly, make it clear that you’ve already thought about this question and know what you want.

Question 23:
Tell me about a time when you set a goal in your personal life and achieved it.
Answer:
The interviewer can see that you excel at setting goals in your professional life, but he or she also wants to know that you are consistent in your life and capable of setting goals outside of the office as well. Use an example such as making a goal to eat more healthily or to drink more water, and discuss what steps you outlined to achieve your goal, the process of taking action, and the final results as well.

Question 24:
What is your greatest goal in your career?
Answer:
Have a very specific goal of something you want to achieve in your career in mind, and be sure that it’s something the position clearly puts you in line to accomplish. Offer the goal as well as your plans to get there, and emphasize clear ways in which this position will be an opportunity to work toward the goal.

Question 25:
Tell me about a time when you achieved a goal.
Answer:
Start out with how you set the goal, and why you chose it. Then, take the interviewer through the process of outlining the goal, taking steps to achieve it, the outcome, and finally, how you felt after achieving it or the recognition you received. The most important part of this question includes the planning and implementation of strategies, so focus most of your time on explaining these aspects. However, the preliminary decisions and end results are also important, so make sure to include them as well.

Question 26:
What areas of your work would you still like to improve in? What are your plans to do this?
Answer:
While you may not want the interviewer to focus on things you could improve on, it’s important to be self-aware of your own growth opportunities. More importantly, you can impress an interviewer by having specific goals and actions outlined in order to facilitate your growth, even if your area of improvement is something as simple as increasing sales or finding new ways to create greater efficiency.

Question 27:
Tell me about your favorite book or newspaper.
Answer:
The interviewer will look at your answer to this question in order to determine your ability to analyze and review critically. Additionally, try to choose something that is on a topic related to your field or that embodies a theme important to your work, and be able to explain how it relates. Stay away from the controversial subjects matter, such as politics or religion.

Question 28:
If you could be rich or famous, which would you choose?
Answer:
This question speaks to your ability to think creatively, but your answer may also give great insight into your character. If you answer rich, your interviewer may interpret that you are self-confident and don’t seek approval from others and that you like to be rewarded for your work. If you choose famously, your interviewer may gather that you like to be well-known and to deal with people, and have the platform to deliver your message to others. Either way, it’s important to back up your answer with sound reasoning.

Question 29:
If you could trade places with anyone for a week, who would it be and why?
Answer:
This question is largely designed to test your ability to think on your feet, and to come up with a reasonable answer to an outside-the-box question. Whoever you choose, explain your S. answer in a logical manner, and offer specific professional reasons that led you to choose the individual.

Question 30:
What would you say if I told you that just from glancing over your resume, I can already see three spelling mistakes?
Answer:
Clearly, your resume should be absolutely spotless – and you should be confident that it is. If your interviewer tries to make you second-guess yourself here, remain calm and poised and assert with a polite smile that you would be quite surprised as you are positive that your resume is error-free.

Question 31:
Tell me about your worldview.
Answer:
This question is designed to offer insight into your personality, so be aware of how the interviewer will interpret your answer.
Speak openly and directly, and try to incorporate your own job skills into your outlook on life. For example, discuss your
beliefs on the ways that hard work and dedication can always bring success, or in how learning new things is one of life’s greatest gifts. It’s okay to expand into general life principles here, but try to keep your thoughts related to the professional field as well.

Question 32:
What is the biggest mistake someone could make in an interview?
Answer:
The biggest mistake that could be made in an interview is to be caught off guard! Make sure that you don’t commit whatever you answer here, and additionally be prepared for all questions. Other common mistakes include asking too early in the hiring process about job benefits, not having questions prepared when the interviewer asks if you have questions, arriving late, dressing casually or sloppily, or showing ignorance of the position.

Question 33:
If you won the $50m lotteries, what would you do with the money?
Answer:
While a question such as this may seem out of place in a job interview, it’s important to display your creative thinking and your ability to think on the spot. It’s also helpful if you choose something admirable, yet believable, to do with the money such as donate the first seventy percent to a charitable cause, and divide the remainder among gifts for friends, family, and of course, yourself.

Question 34:
Is there ever a time when honesty isn’t appropriate in the workplace?
Answer:
This may be a difficult question, but the only time that honesty isn’t appropriate in the workplace is perhaps when you’re feeling anger or another emotion that is best kept to yourself. If this is the case, explain simply that it is best to put some thoughts aside, and clarify that the process of keeping some thoughts quiet is often enough to smooth over any unsettled emotions, thus eliminating the problem.

35: If you could travel anywhere in the world, where would it – be?
Answer:
This question is meant to allow you to be creative – so go ahead s and stretch your thoughts to come up with a unique answer. However, be sure to keep your answer professionally-minded. For example, choose somewhere rich with culture or that would expose you to a new experience, rather than going on an. expensive cruise through the Bahamas.

Question 36:
What would I find in your refrigerator right now?
Answer:
An interviewer may ask a creative question such as this in order to discern your ability to answer unexpected questions calmly, or, to try to gain some insight into your personality. For example, candidates with a refrigerator full of junk food or \ take-out may be more likely to be under stress or have health issues, while a candidate with a balanced refrigerator full of nutritious staples may be more likely to lead a balanced mental life, as well.

Question 37:
If you could play any sport professionally, what would it be and what aspect draws you to it?
Answer:
Even if you don’t know much about professional sports, this question might be a great opportunity to highlight some of your greatest professional working skills. For example, you may choose to play professional basketball, because you admire the teamwork and coordination that goes into creating a solid play. Or, you may choose to play professional tennis, because you consider yourself to be a go-getter with a solid work ethic and great dedication to perfecting your craft. Explain your choice simply to the interviewer without elaborating on drawn-out sports metaphors, and be sure to point out specific areas or skills in which you excel.

Question 38:
Who were the presidential and vice-presidential candidates in the 2008 elections?
Answer:
This question, plain and simple, is intended as a gauge of your intelligence and awareness. If you miss this question, you may well fail the interview. Offer your response with a polite smile, because you understand that there are some individuals who probably miss this question.

Question 39:
Explain X task in a few short sentences as you would to a second-grader.
Answer:
An interviewer may ask you to break down a normal job task that you would complete in a manner that a child could understand, in part to test your knowledge of the task’s inner workings – but in larger part, to test your ability to explain a process in simple, basic terms. While you and your coworkers may be able to converse using highly technical language, being able to simplify a process is an important skill for any employee to have.

Question 40:
If you could compare yourself to any animal, what would it be?
Answer:
Many interviewers ask this question, and it’s not to determine which character traits you think you embody – instead, the interviewer wants to see that you can think outside the box and that you’re able to reason your way through any situation. Regardless of what animal you answer, be sure that you provide a thorough reason for your choice.

Question 41:
Who is your hero?
Answer:
Your hero may be your mother or father, an old professor, someone successful in your field, or perhaps even Wonder Woman – but keep your reasoning for your chosen profession, and be prepared to offer a logical train of thought. Choose someone who embodies values that are important in your chosen career field, and answer the question with a smile and a sense of passion.

Question 42:
Who would play you in the movie about your life?
Answer:
As with many creative questions that challenge an interviewee to think outside the box, the answer to this question is not as important as how you answer it. Choose a professional, and relatively non-controversial actor or actress, and then be prepared to offer specific reasoning for your choice, employing important skills or traits you possess.

Question 43:
Name five people, alive or dead, that would be at your ideal dinner party.
Answer:
Smile and sound excited at the opportunity to think outside the box when asked this question, even if it seems to come from left field. Choose dynamic, inspiring individuals who you could truly learn from, and explain what each of them would have to offer to the conversation. Don’t forget to include yourself, and to talk about what you would bring to the conversation as well!

Question 44:
What is customer service?
Answer:
Customer service can be many things – and the most important consideration in this question is that you have a creative
answer. Demonstrate your ability to think outside the box by offering a confident answer that goes past a basic definition, and that shows you have truly considered your own individual view of what it means to take care of your customers. The thoughtful consideration you hold for customers will speak for, itself.

Question 45:
Tell me about a time when you went out of your way for a customer.
Answer:
It’s important that you offer an example of a time you truly went out of your way – be careful not to confuse something that felt like a big effort on your part, with something your employer would expect you to do anyway. Offer an example of the customer’s problems, what you did to solve them, and the way the customer responded after you took care of the situation.

Question 46:
How do you gain confidence from customers?
Answer:
This is a very open-ended question that allows you to show your customer service skills to the interviewer. There are many possible answers, and it is best to choose something that you’ve had a great experience with, such as “by handling situations with transparency,” “offering rewards,” or “focusing on great communication.” Offer specific examples of successes you’ve had.

Question 47:
Tell me about a time when a customer was upset or agitated – how did you handle the situation?
Answer:
Similarly to handling a dispute with another employee, the most important part to answering this question is to first set up the scenario, offer a step-by-step guide to your particular conflict resolution style, and end by describing the way the conflict was resolved. Be sure that in answering questions about your own conflict resolution style, that you emphasize the importance of open communication and understanding from both parties, as well as a willingness to reach a compromise or other solution.

Question 48:
When can you make an exception for a customer?
Answer:
Exceptions for customers can generally be made when in accordance with company policy or when directed by a supervisor. Display an understanding of the types of situations in which an exception should be considered, such as when a customer has endured a particular hardship, had a complication with an order, or at a request.

Question 49:
What would you do in a situation where you were needed by both a customer and your boss?
Answer:
While both your customer and your boss have different needs of you and are very important to your success as a worker, it is always best to try to attend to your customer first – however, the key is explaining to your boss why you are needed urgently. by the customer, and then to assure your boss that you will attend to his or her needs as soon as possible (unless it’s absolutely an urgent matter).

Question 50:
What is the most important aspect of customer service?
Answer:
While many people would simply state that customer satisfaction is the most important aspect of customer service, it’s important to be able to elaborate on other important techniques in customer service situations. Explain why customer service is such a key part of business, and be sure to expand on the aspect that you deem to be the most important in a way that is reasoned and well-thought-out.

Question 51:
Is it best to create low or high expectations for a customer?
Answer:
You may answer this question either way (after, of course, determining that the company does not have a clear opinion on the matter). However, no matter which way you answer the question, you must display a thorough thought process and very clear reasoning for the option you chose. Offer pros and cons of each, and include the ultimate point that tips the scale in favor of your chosen answer.
And Finally Good Luck!

Python Interview Questions on HR Questions Read More »

Python Interview Questions on HTML/XML in Python

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on HTML/XML in Python

Question 1:
What module is used to handle URLs?
Answer:
urlparse.

Question 2:
Illustrate parsing a URL into a tuple.
Answer:
Import urlparse
myTuple = urlparse.urlparse( “http://wivzv.example.com/mydirectory/ myfile.html”)

Question 3:
What modules does Python provide for opening and fetching data from URLs?
Answer:
urllib and urllib2.

Question 4:
What is the main difference between the urllib and urllib2 modules?
Answer:
The urllib2 module can accept a Request object, which allows the specification of headers.

Question 5:
Illustrate opening and printing a web-based URL.
Answer:
import urllib ,
myURL =urllib.urlopen(“http:/lwww.example.org/myfile.html”)
myBuffer = myURL.read( )
print myBuffer

Question 6:
How is the request information retrieved?
Answer:
Using the .info( ) method on an open URL.

Question 7:
To process the contents of an HTML file, what module is used?
Answer:
HTMLParser.

Question 8:
How is the HTMLParser used?
Answer:
By subclassing the HTMLParser.HTMLParser class, and inserting processing for the tags of interest, instantiating it, then by calling the .feed method of the resulting object.

Question 9:
What modules are used to manage cookies?
Answer:
The urllib and cookielib modules.

Question 10:
Illustrate retrieving a cookies from a URL.
Answer:
Import urllib2
Import cookielib
myjar= cookielib.LWPCookieJar( )
myOpener = urllib2.build_opener(
urllib2.HTTPCookieProcessor(myJar))
urllib2. ins tall_opener( myOpener)
myRequest =urllib2. RequestC’http:!/www.example.org/”)
myHTML = urllib2.urlopen(my Request)
for cookie in enumerate(myjar)
print cookie

Question 11:
In managing XML documents, what is the module most often used?
Answer:
xml.dom Also, the minidom class within xml.dom

Question 12:
Illustrate opening an xml document.
Answer:
from xml.dom import minidom myTree = minidom.parse(‘myXML.xml’) print myTree.toxmlO

Question 13:
What tools are available to determine if an xml file is well formed?
Answer:
Using a try, except block, and attempting to parse the xml file through the generic parser available in xml.sax

Question 14:
How are xml element attributes accessed?
Answer:
Using the minidom parser, then the .getAttribute method on returned child nodes.

Question 15:
What method is used to determine if a child node includes a particular attribute?
Answer:
Using the .hasAttribute method which will return true if the attribute is defined.

Question 16:
What is the difference between the .toxml and .toprettyxml methods?
Answer:
The .toprettyxml method will indent the node contents appropriately.

Question 17:
What is expat module and what is it used for?
Answer:
The expat module is a non-validating XML parser. It is used to process XML very quickly, with minimal regard for the formal correctness of the XML being parsed.

Question 18:
What does the .dom stand for in the xml.dom module?
Answer:
Document Object Model.

Question 19:
What parsers are available for XML?
Answer:
Sax, expat, and minidom

Question 20:
Illustrate direct node access in an XML file.
Answer:
from xml.dom import minidom myXML = minidom.parse(”myXML.xml”)
myNodes = myXML.childNode s print childNodes[0].toprettyxml()

Python Interview Questions on HTML/XML in Python Read More »

Python Interview Questions on Python Internet Communication

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Python Internet Communication

Question 1:
What are some supported socket communications protocol families?
Answer:
AF_INET (IPV4, TCP, UDP), AF_INET6 (IPV6, TCP, UDP), AF_UNIX

Question 2:
What are some socket types in Python?
Answer:
SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET

Question 3:
Illustrate opening a server side socket for incoming packets.
Answer:
import socket
mySock = socket.socket.(AFJNET, SOCK_STREAM)
mySock.bind((interfaceName, portNumber))
mySock.listen(3)

Question 4:
Illustrate opening a client-side socket for sending data.
Answer:
import socket
mySock = socket.socket.(AFJNET, SOCK_STREAM)
my Sock ,connect((interfaceName, portNumber))
mySock.send(data)

Question 5:
What module is used to send email?
Answer:
smtplib.

Question 6:
Illustrate connecting to a mail server, in preparation for sending an email.
Answer:
import smtplib
mySMTP = smtplib.SMTP(‘mail.example.org’)

Question 7:
Illustrate sending an email, then closing the connection.
Answer:
import smtplib
mySMTP = smtplib.SMTP(‘mail.example.org’)
myResult = mySMTP.sendmail(‘[email protected]’,
[email protected]’, message)
mySMTP.quit( )

Question 8:
What module is used to retrieve email from a server?
Answer:
poplib.

Question 9:
Illustrate retrieving the number of messages available on a mail server.
Answer:
Import poplib .
myPOP = poplib.POP3(‘mail.example.org’)
mPOP.user(“[email protected]’)
mPOP.pass_(“myPassword”)
myMessageCount = len(mPOP.list()[l])

Question 10:
What module is used to support file transfers?
Answer:
ftplib.

Question 11:
Illustrate opening a FTP connection.
Answer:
import ftplib
myFTP = ftplib.FTP(/ftp.example.org,/ ‘anonymous’, ‘[email protected]’)

Question 12:
What method is used to retrieve a list of files on an active FTP connection?
Answer:
•dir( )

Question 13:
Illustrate using FTP to retrieve a file and write it to the local disk.
Answer:
import ftplib
myFTP = ftplib.FTP(‘ftp.example.org’, ‘anonymous’,
[email protected]’)
myFile = openC’localfile.txt”, “wb”)
myFTP.retbinaryCRETR remotefile.txt’, myFile.write)
myFTP.quit( ) .
myFile.close( )

Question 14:
What happens if the .quit() method is not called on FTP connections.
Answer:
A resource leak can occur if multiple FTP connections are opened but never closed.

Question 15:
Illustrate retrieving a list of files from an FTP server
Answer:
import ftplib
myFTP = ftplib.FTP(ftp.example.org’, ‘anonymous’,
‘myemail@example. org’)
myFileList = myFTP.dirO
print myFileList
myFTP.quit()

Question 16:
What does the SOCK_STREAM socket type signify?
Answer:
This is a TCP Socket type.

Question 17:
What does the SOCK_DGRAM signify?
Answer:
This is a UDP socket type.

Question 18:
How is the .shutdown method used?
Answer:
.shutdownO is called before .close to flush buffers and ensure a timely shutdown of the connection. It can be called using SHUTRD, SHUT_WR or SHUT_RDWR to end receiving, sending, or both.

Question 19:
What does socket.accept() return?
Answer:
The conn and address objects. Conn is a new socket object able to send or receive data, and the address object is the address of the remote host.

Question 20:
How is the remote address of a socket returned?
Answer:
Using the .getpeernameQ method of the connected socket.

Python Interview Questions on Python Internet Communication Read More »

Python Interview Questions on Python Database Interface

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Python Database Interface

Question 1:
What is the generic Python “built-in” database module called?
Answer:
DBM

Question 2:
What are some advantages of using DBM?
Answer:
No back-end database is required. The files are portable and work with the pickle and shelve modules to store Python objects.

Question 3:
What does it mean to pickle and unpickle a Python object?
Answer:
Using the pickle module, allows the writing of Python objects to a file. Unpickling is the reverse, reading a file containing a pickled Python object and re-instantiating it in the running program.

Question 4:
What is the difference between the pickle and cPickle Python modules?
Answer:
cPickle is much faster, but it cannot be subclassed like pickle can.

Question 5:
What is the shelve module, and how is it different from pickle?
Answer:
Shelving an object is a higher-level operation that pickles, in that the shelve module provides its own open method and pickles objects behind the scene. Shelve also allows the storage of more complex Python objects.

Question 6:
Illustrate creating a DBM file.
Answer:
import anydbm
myDB = anydbm.open(“newDBFile.dbm”, ‘n’)

Question 7:
Illustrate writing a list to a DBM file.
Answer:
import anydbm
my List = [“This”, “That”, “Something Else”]
myDB = anydbm.open(“newDBFile.dbm”, ‘w’)
mylndex = 0
for myltem in myList:
myDB[my!tem] = myList[myIndex]
mylndex += 1 myDB.close( )

Question 8:
Illustrate pickling a list.
Answer:
import cPickle .
myList = [“This”, “That”, “Something Else”]
myFile = open(“myPickleFile.dat”, “w”)
myPickler = cPickle.Pickler(myFile)
myPickler.dump(myList)
myFile.close( )

Question 9:
Illustrate shelving a dictionary.
Answer:
import shelve
myDict = {“name”: “John Doe”, “Address” : “1234 Main street”}
my Shelf = shelve.open(” my ShelveFile.dat”, “n”)
my Shelfl” Dictionary”] = myDict
my Shelf. close( )

Question 10:
Illustrate retrieving a dictionary from a shelf file Answer:
import shelve
myShelf= shelve.open(” my ShelveFile.dat”, “r”)
myDict = my Shelfl “Dictionary”]
myShelf.close( )

Question 11:
What Python module is used to work with a MySQL database?
Answer:
MySQLdb.

Question 12:
Illustrate connecting to a MySQL database on the local host, with a username and a password.
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=”127.0.0.1″, user=”username”, passwd=”password”)

Question 13:
What is a MySQLdb cursor?
Answer:
It is a handle that lets you send SQL commands to MySQL and retrieve the result.

Question 14:
Illustrate creating a cursor, then sending a select
command to MySQL
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=” 127.0.0.1″, usem”username”,
passwd= “password “)
my Cursor = myDB.cursorO
myCursor.execute(” select * from tablename”)
myResults = myCursor.fetchall( )

Question 15:
How are databases and tables created in MySQL from Python?
Answer:
Using a database connection and cursor to execute the appropriate CREATE DATABASE and CREATE TABLE SQL commands.

Question 6:
How is the currently selected database name retrieved?
Answer:
Using a database connection and cursor to execute a SELECT DATABASE() SQL command.

Question 17:
What is the .fetchall( ) method of the cursor object?
Answer:
It is used to retrieve all of the results of the executed SQL command. It returns a series of one or more lists depending on the results available.

Question 18:
Illustrate adding a row to a MySQL database
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=”127.0.0.1”, user=”username”, passwd= “password “)
myCursor = myDB.cursor( )
my Cursor. execute(” INSERT INTO tablename VALUES ‘Vail’, ‘Val2’, ‘etc.'”)
myDB. commit( )

Question 19:
What does the .commit method of the database object do?
Answer:
It flushes the pending request buffer and ensures that the transactions are all written to disk.

Question 20:
Illustrate retrieving a list of available tables in a MySQL database.
Answer: „
import MySQLdb
myDB = MySQLdb.connect(host=” 127.0.0.1″, user=”username”, passwd= “password “)
myCursor = myDB.cursor ( )
myCursor.executeC’SHOW TABLES “)
myResults = myCursor.fetchall( )

Python Interview Questions on Python Database Interface Read More »

Python Interview Questions on String Manipulation

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on String Manipulation

Question 1.
Is .len( ) a valid string method?
Answer:
No. To get the length of a string using the function len( ), as in len(string)

Question 2.
What does the .title( ) method do?
Answer:
It returns a title-cased string, words start with upper case and everything else is lower case.

Question 3:
Given a string with leading and trailing spaces, illustrate how to return a string without the leading and trailing spaces.
Answer:
string.strip(”)

Question 4:
What is the difference between the find( ) and index( ) string methods?
Answer:
If the substring is not found, find( ) will return -1, and index( ) will raise a ValueError.

Question 5:
Illustrate breaking a comma-separated string into a list of individual tokens.
Answer:
string.split(‘/)

Question 6:
How is a slice of a string specified?
Answer:
Using the colon in the form of start: end index. 2:5 would specify the third through sixth characters in a string.

Question 7:
Given a multiple-line string, how is a list of individual lines obtained?
Answer:
string. splitlines( ) Line breaks are removed unless split lines are called with (True).

Question 8:
What method is used to determine if a string contains any special characters or punctuation?
Answer:
string.alnum( ) If it returns true, there are no special characters in the string.

Question 9:
What method is used to determine if a string contains only numbers?
Answer:
string.isdigit( ) Any other values in the string will cause this to return False.

Question 10:
What is the purpose of the count!) string method?
Answer:
The count method counts the number of occurrences of a substring within the string. Not the number of characters in the string.

Question 11:
What does the partition( ) string method do?
Answer:
Partition breaks a string into two parts and returns a tuple containing the substring before the separator, the separator itself, and the substring after the separator.

Question 12:
In the string “Fred Flintstone drinks at a foo. A fluorometer measures pressure.” How would you change every occurrence of foo with bar?
Answer:
string.replace^foo’/bar’)

Question 13:
Illustrate converting tabs to 12 spaces each in a string.
Answer:
string.expand tabs(12)

Question 14:
Given a list of words, combine them into one string.
Answer:
myString = “.join(wordlist)

Question 15:
How is the center string method used?
Answer:
It positions a string centered in a field of a specified width, padded by spaces on either side.

Question 16:
How can code inside a string be executed?
Answer:
exec(string) The string is interpreted as Python code.

Question 17:
How are string templates created?
Answer:
By using the $ prefix on variable names within the template string.

Question 18:
Illustrate creating a template string, and then printing it with a variable substituted.
Answer:
import string
myTemp late = string.Template! “A template… The variable = $v”)
print myTemplate.substitute(v=”my variable”)

Question 19:
How is a Unicode string specified?
Answer:
By adding a ‘u’ before the string definition

Question 20:
How is Unicode converted to a local string?
Answer:
Using the string’s encode method. An example might be string.encode(‘utf-8′)

Python Interview Questions on String Manipulation Read More »

Python Interview Questions on Python Conditionals

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Python Conditionals

Question 1.
What constitutes “True” in Python?
Answer:
A true expression is any expression that does not evaluate to 0, the empty list [ ], tuple ( ), dictionary { } or the objects None or False.

Question 2:
What are the three main conditional statements in Python?
Answer:
if, elif, and else

Question 3:
What are the comparison operators in Python?
Answer:
< Less than, > Greater than, <= Less than or equal to, >= Greater than or equal to, = Equal to, != not equal, o alternative not equal. Note a single = is NOT a Python comparison operator, it is an assignment operator only.

Question 4:
Illustrate a basic if, elif, else structure.
Answer:
if <condition>:
. . .
elif<another condition>:
. . .
else:
. . .
Question 5:
In Python 2.5+, the equivalent of a tertiary operator has been added to the language. Provide an example of its use.
Answer:
myValue = ‘Positive’ if myNumber > 0 else ‘Negative or Zero’

Question 6:
What does elif mean?
Answer:
It means else if. It is used after an if statement, to do another comparison.

Question 7.
What would the output be from the following code? a =4 If a = 5:
Print “True”
Else:
Print “False”
Answer:
This is a trick question. The a = 5 is not a comparison operator, but an assignment. It will yield “True”. The correct coding would be a == 5.

Question 8:
How are if, elif, and else blocks defined?
Answer:
All blocks in Python are defined by indenting. All lines of a particular code block must have the same level of indenting.

Question 9:
Illustrate a switch-case equivalent using if-elif-else.
Answer:
if item=valueA:
. . .
elif item == valueB:
. . .
elif item = =  valueC:
. . .
elifitem = valueN:
. . .
else:
… #default code

Question 10:
How is the Python switch statement used?
Answer:
This is a trick question, there is no built-in switch statement in Python, which is unusual. A switch statement can be easily created using if-elif using lambda or with Python dictionaries.

Question 11:
Using a dictionary, create an equivalent to a switch case statement.
Answer:
deffunc1( ):
. . .
deffunc2( ):
. . .
switch = {
‘Aardvark’: fund1,
‘Armadillo’: fund2,
}
mySwi tchKey= “Armadillo ”

switch[mySwitchKey]( ) #callsJunc2( )
switch[‘Aardvark’]( ) #calls func1( )

Question 12:
Illustrate comparing two strings for equality in a case insensitive manner.
Answer:
if stringl. lower ( ) = string2.lower ( ):
#Note: .upper( ) is equally valid.

Question 13:
Illustrate comparing two strings, printing if the first string is longer, equal, or shorter than the second string.
Answer:
if len(stringl) > len(string2):
print “Stringl is longer than string2.”
elif len(stringl) < len(string2):
print “String1 is shorter than string2.”
else:
print “String1 is the same length as string2.”

Question 14:
When comparing two d^tes, what method is used?
Answer:
Date.toordinal( ) Otherwise, Python would compare the dates by their object address.

Question 15:
In comparing dates and DateTime objects, what happens when one comparand is naive and the other aware?
Answer:
A TypeError is raised.

Question 16:
What happens when you try to compare a DateTime object with other classes of objects?
Answer:
A TypeError is raised.

Question 17:
When are dictionaries considered equal?
Answer:
If and only if their sorted lists compare equally.

Question 18:
How is collection membership determined?
Answer:
Using the in and not in operators.

Question 19:
Illustrate how collection membership determination would be written.
Answer:
if x in collection:
print “It is in the collection”
else:
print “Not in the collection.”

Question 20:
How is object identity tested? Illustrate with an example.
Answer:
Using the is and is not operators.
if x is objecttype:
print “x is the type you thought it was.
else:
print “x isn’t an objecttype.”

Python Interview Questions on Python Conditionals Read More »

Python Interview Questions on Searching and Sorting

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Searching and Sorting

Sequential Search

In the chapter based on Python operators, we have seen that we can make use of the membership operator ‘in’ to check if a value exists in a list or not.

    >>> list.1 = [1,2,3,4,5,6,71
    >>> 3 in list1
   True
    >>> 8 in list1
    False
    >>>

This is nothing but searching for an element in a list. We are going to look at how elements can be searched and how process efficiency can be improved. We start by learning about sequential search.

The simplest way of searching for an element in a sequence is to check every element one by one. If the element is found then the search ends and the element is returned or else the search continues till the end of the sequence. This method of searching is known as linear search or sequential search. It follows a simple approach but it is quite an inefficient way of searching for an element because we move from one element to the other right from the beginning to end and if the element is not present in the sequence we would not know about it till we reach the last element.

Time analysis for sequential search:

  • Best scenario is that the element that we are looking for is the very first element in the list. In this case, the time complexity will be 0(1).
  • The worst scenario would be if we traverse throughout the entire sequence and realize that the element that we are looking for, does not exist. In this case, the time complexity will be O(n).

Python Interview Questions on Searching and Sorting chapter 14 img 1

Question 1.
Sequential search is also known as _______
Answer:
Linear Search

Question 2.
How are the elements reviewed in sequential search?
Answer:
The elements are reviewed one at a time in sequential terms.

Question 3.
When does the sequential search end?
Answer:
The sequential search ends when an element is found or when the end of the sequence is reached.

Question 4.
Write code to implement sequential search.
Answer:
The sequential search can be implemented as follows:

  • The function takes two values: seq list which is the list and target_ num which is the number to search in the list.
  • We set search_flag = 0 if the target number is found in the list we will set the search_flag to 1 else we let it be 0.
  • We iterate through the list comparing each element in the list with the target_num.
  • If a match is found we print a message and update the search_flag to 1.
  • After the “for” loop if the search_flag is still 0 then it means that the number was not found.

Code

def sequential__search (seq_list, target_num) :
    search_flag = 0
    for i in range(len(seq_list)):
        if seq_list[i] == target_num:
           print("Found the target number ", target_num, " at index", i,".")
            search_flag = 1;
    if search_flag == 0:
       print("Target Number Does Not Exist.Search Unsuccessful.")

Execution

seq_list = [1,2,3,4,5,6,7,8,2,9,10,11,12,13,14,15, 16]
target__num = input ("Please enter the target number : ")
sequential_search(seq_list, int(target_num))

Output 1

Please enter the target number: 5
Found the target number 5 at index 4.

Output 2

Please enter the target number: 2
Found the target number 2 at index 1.
Found the target number 2 at index 8.

Output 3

Please enter the target number: 87
Target Number Does Not Exist. Search Unsuccessful.

Question 5.
How would you implement a sequential search for an ordered list?
Answer:
When elements in a list are sorted, then many times there may not be the need to scan the entire list. The moment we reach an element that has a value greater than the target number, we know that we need not go any further.

Step 1: We define a function sequential_search() that takes two arguments – a list (seq_list) and the number that we are looking for (target num).

def sequential_search(seq_list, target_num):

Step 2: The first thing we do is set define a flag (search_flag) and set it to “False’’ or “0” value. The flag is set to “True” or “1” if the element is found. So, after traversing through the list if the search_flag value is still “False” or “0”, we would know that the number that we are looking for does not exist in the list.

def sequential__search (seq_list, target_num) :
    search_flag = 0

Step 3: Now, it’s time to check the elements one by one so, we define the for loop:

def sequential_search(seq_list, target_num):
    search_flag = 0
    for i in range(len(seq_list)):

Step 4: We now define how the elements are compared. Since it is an ordered list for every “i” in seq_list we have to check if i > target_num. If yes, then it means that there is no point moving further as it is an ordered list and we have reached an element that is greater than the number that we are looking for. However, if seq_list[i] == target_num then, the search is successful and we can set the search_flag to 1.

def sequential_search(seq_list, target^num):
    search_flag = 0
    for i in range(len(seq_list)):
        if seq_list[i] > target_num:
           print("search no further.")
           break;
       elif seq_list[i] == target_num:
            print("Found the target number ", target_num, " at index", i,".")
            search_flag = 1;

Step 5: After the for loop has been executed if the value of search_flag is still 0 then a message stating that the target number was not found must be displayed.

Code

def sequential_search(seq_list, target_num):
      search_flag = 0
      for i in range(len(seq_list)):
          if seq_list[i] > target_num:
             print("search no further.")
             break;
         elif seq_list[i] == target_num:
              print("Found the target number ", target_num, " at index", i,".")
              search_flag = 1 ;

      if search_flag == 0 ;
      print ("Target Number Does Not Exist. search Unsuccessful.")

Execution

seq_list = [1,2,3,4,5,6,7,8,2,9,10,11,12,13,14,15, 16]
target_num = input ("Please enter the target number : ")
sequential_search(seq_list, int(target_num))

Output 1

Please enter the target number: 2
Found the target number 2 at index 1.
Found the target number 2 at index 2.
search no further.
>>>

Output 2

Please enter the target number: 8
Found the target number 8 at index 8.
Search no further.
>>>

Output 3

Please enter the target number: 89
Target Number Does Not Exist. Search Unsuccessful.
>>>

Binary Search

A binary search is used to locate a target value from a sorted list. The search begins from the center of the sequence. The element present at the center is not equal to the target number it is compared with the target number. If the target number is greater than the element at the center then it means that we need to search for the number in the right half of the list and the left half need not be touched. Similarly, if the target number is less than the element present in the center then we will have to direct our search efforts towards the left. This process is repeated till the search is completed. The beauty of binary search is that in every search operation the sequence is cut into half and focus is shifted to only that half that has chances of having the value.

Python Interview Questions on Searching and Sorting chapter 14 img 2

Question 6.
Write a code to implement the binary search function.
Answer:
The binary search can be implemented in the following manner:
Step 1: Define the binary_search function. It takes 4 parameters:

  • sorted list: the input list that is in sorted form
  • target_num: the number that we are looking for
  • starting_point: the place from where we want to start searching, default value = 0
  • end_point: The endpoint for search, default value = None

Note that the list will be split in half in every step so the starting and ending point may change in every search operation.

def binary_search(sorted_list, target_num, start_ point=0, end_point=None):

Step 2: Do the following:

  • Set the search_flag to “False”
  • If the end_point is not provided, it would have the default value of “None”, set it to the length of the input list.
def binary_search(sorted_list, target_num, 
start_point=0, end_point=None):
     search_flag = False
     if end_point == None:
        end_point = len(sorted_list)-1

Step 3: Check, the start_point should be less than the endpoint. If that is true, do the following:

  • Get midpoint index value: mid_point = (end_point+start_point)//2
  • Check the value of the element at mid_point. Is it equal to the target_ num?
  • If sorted_lLst[midjioint] == target num1
  • Set search flag to True
  • If not check if the value at mid_point is greater than target_num :
  • sorted_list[mid_point] > target num
  • If yes, then we can discard the right side of the list now we can repeat the search from beginning to mid_point-1 value. Set
    endpoint to mid_point – 1. The starting point can remain the same(0).
  • The function should now call itself with:
  • sorted_list: same as before
  • target_num: same as before
  • starting point: same as before
  • endpoint: mid_point – 1
  • If not check if the value at mid_point is lesser than target num :
  • sorted_list[mid_point] < target_num
  • If yes, then the left side of the list is not required. We can repeat the search from mid_point+1 to the end of the list. Set starting point to mid_point+1. The ending_point can remain the same.
  • The function should now call itself with:
  • sorted_list: same as before
  • target_num: same as before
  • starting point: mid_point+l
  • end_point: same as before
  • If at the end of this procedure the search_flag is still set to “False”, then it means that the value does not exist in the list.

Code

def binary_search(sorted_list, target_num, start_ point=0, end_point=None):
       search_flag = False
       if end_point == None:
          end_point = len(sorted_list)-1
       if start_point < end_point:
          mid_point = (end_point+start_point)//2
          if sorted_list[mid_point] == target_num:
             search_flag = True
             print(target_num," Exists in the list at ",sorted_list.index(target_num))
             elif sorted_list[mid_point] > target_num:
                  end_point = mid_point-l 
                  binary_search(sorted_list, target_ num,start_point, end_point)
            elif sorted_list[mid_point] < target_num:
            start_point = mid_point+l 
            binary_search(sorted_list, target_num, start_point, end_point)
       elif not search_flag:
             print(target_num," Value does not exist")

Execution

sorted_list=[ 1,2,3,4,5,6,7,8,9,10,11,12,13]
binary_search(sorted_list, 14)
binary_search(sorted_list,0)
binary_search(sorted_list,5)

Output

14 Value does not exist 
0 Value does not exist 
5 Exists in the list at 4

Hash Tables

Hash Tables are data structures where a hash function is used to generate the index or address value for a data element. It is used to implement an associative array that can map keys to values. The benefit of this is that it allows us to access data faster as the index value behaves as a key for data value. Hash tables store data in key-value pairs but the data is generated using the hash function. In Python, the Hash Tables are nothing but Dictionary data type. Keys in the dictionary are generated using a hash function and the order of data elements in Dictionary is not fixed. We have already learned about various functions that can be used to access a dictionary object but what we actually aim at learning here is how hash tables are actually implemented.

We know that by binary search trees we can achieve the time complexity of O(logn) for various operations. The question that arises here is that can search operations be made faster? Is it possible to reach a time complexity of 0(1)11 This is precisely why hash tables came into existence? Like in a list or an array if the index is known, the time complexity for search operation can become 0(1). Similarly, if data is stored in key-value pairs, the result can be retrieved faster. So, we have keys and we have slots available where the values can be placed. If we are able to establish a relationship between the slots and the key it would be easier to retrieve the value at a fast rate. Look at the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 3

The key value is not always a nonnegative integer, it can be a string also, whereas the array has an index starting from 0 to length_of_array -1. So there is a need to do prewashing in order to match the string keys to indexes. So, for every key, there is a need to find an index in an array where the corresponding value can be placed. In order to do this, we will have to create a hash( ) function that can map a key of any type to a random array index.

During this process, there are chances of collision. Collision is when we map two keys to the same index as shown in the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 4

To resolve collision we can use chaining. Chaining is when values are stored -in the same slot with the help of a linked list as shown in the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 5

However, there can be cases of more than one collision for the same spot, and considering the worst-case scenario where there is a need to insert all values as elements of a linked list, it can be a tough situation that will have a severe impact on the time complexity. Worst case scenario will be if we land up placing all values as linked list elements at the same index.

To avoid this scenario we can consider the process of open addressing. Open addressing is the process of creating a new address. Consider a case where if there is a collision we increment the index by 1 and place the value there as shown below, there is collision while placing val3, as val2 already exists at index 1. So, the index value is incremented by 1 (1+1 =2) and val3 is placed at the index

Python Interview Questions on Searching and Sorting chapter 14 img 6

Had there been any other value at index 2 then the index would have incremented again and val3 could be placed at index 3. This means that this process of incrementing the index is continued till an empty slot is spotted. This is called Linear probing. Quadratic probing on the other hand increments by two times the index value. So, the search for the empty slots is done at a distance of 1,2,4,8, and so on. Rehashing is the process of hashing the result obtained again to find an empty slot.

The purpose of the hash function is to calculate an index from which the right value can be found therefore its job would be:

  1. To distribute the keys uniformly in the array.
  2. If n is the number of keys and m is the size of an array, the hash( ) = n%m(modulo operator) in case we use integers as keys.
  3. Prefer to use prime numbers both for array and the hash function for uniform distribution
  4. For string keys, you can calculate the ASCII value of each character and add them up and make a modulo operator on them

In many scenarios, hash tables prove to be more efficient than the search trees and are often used in caches, databases, and sets.
Important points:

  1. You can avoid clustering by using prime numbers.
  2. The number of entries divided by the size of the array is called the load factor.
  3. If the load factor increases the number of collisions will increase. This will reduce the performance of the hash table.
  4. Resize the table when the load factor exceeds the given threshold. However, this would be an expensive option as the hashes of the values entered will change whenever resizing is done and this can take O(n) to complete. Hence dynamic size array may be inappropriate for real-time scenarios.

Question 7.
What does the hash function do?
Answer:
The purpose of a hash function is to map the values or entries into the slots that are available in a hash table. So, for every entry, the hash function will compute an integer value that would be in the range of 0 to m-1 where m is the length of the array.

Question 8.
What is a remainder hash function? What are the drawbacks? Write the code to implement the remainder hash function.
Answer:
The remainder hash function calculates the index value by taking one item at a time from the collection. It is then divided by the size of the array and the remainder is returned.
h(item) = item% m, where m = size of the array Let’s consider the following array:
[18, 12,45,34, 89, 4]
The above array is of size 8.

Python Interview Questions on Searching and Sorting chapter 14 img 7

Drawback: You can see here that 18 and 34 have the same hash value of 2 and 12 and 4 have the same hash value of 4. This is a case of collision as a result when you execute the program, values 18 and 12 are replaced by 34 and 4 and you will not find these values in the hash table.

Let’s have a look at the implementation:

Step1: Define the hash function that takes a list and size of the array as input.
def hash(list_items, size):

def hash(list items, size) :

Step2: Do the following:

  • Create an empty list.
  • Now populate this key ‘from the numbers 0 to size mention. This
    example takes a list of 8 elements so we are creating a list [0, 1, 2, 3, 4, 5,6, 7].
  • Convert this list to diet using from keys( ). We should get a dictionary object of form {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None}. This value is assigned to hash_table.
def hash(list_items, size):
temp_list =[ ]
for i in range(size):
      temp_list.append(i)
'hash_table = diet.fromkeys(temp_list)

Step3:

  • Now iterate through the list.
  • Calculate the index for every item by calculating item%size.
  • For the key value in the hash_table = index, insert the item.

Code

def hash(list_items, size):
     temp_list =[ ]
     for i in range(size):
          temp_list.append(i)
     hash_table = diet.fromkeys(temp_list)
     for item in list_items:
         i = item%size
         hash_table[i] = item
    print("value of hash table is : ",hash_table)

Execution

list_items = [18,12,45,34,89,4]
hash(list_items, 8)

Output

value of hash table is : {0: None, 1: 89, 2: 34,
3: None, 4: 4, 5: 45, 6: None, 7: None}
>>>

Question 9.
What is a folding hash function?
Answer:
The folding hash function is a technique used to avoid collisions while hashing. The items are divided into equal-size pieces, they are added together and then the slot value is calculated using the same hash function (item%size).

Suppose, we have a phone list as shown below:

phone_list= [4567774321, 4567775514, 9851742433, 4368884732]

We convert every number to a string, then each string is converted to a list, and then each list is appended to another list and we get the following result:
[[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7\ ‘4’, ‘3’, ‘2’, ‘1’], [‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’’, ‘1’, ‘4’], [‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’], [‘4’, ‘3’, ‘6’, ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’]]

Now from this new list, we take one list item one by one, for every item we concatenate two characters convert them to integer, and then concatenate next to characters convert them to integer, and add the two values and continue this till we have added all elements. The calculation will be something like this:
[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘4’, ‘3’, ‘2’, ‘1’]

1. items =45
string val = 45
integer value = 45
hash value= 45

2. items =67
string val = 67
integer value = 67
hash value= 45+67 =112

3. items =77
string val = 77
integer value = 77
hash value= 112+77 =189

4. items =43
string val = 43
integer value = 43
hash value= 189+43 = 232

5. items =21
string val = 21 ,
integer value = 21
hash value= 232+21 = 253 Similarly,
[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’, ‘1’, ‘4’] will have a hash value of 511.
[‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’] will have a hash value of 791.
[‘4’, ‘3’, ‘6\ ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’] will have a hash value of 1069.
We now call the hash function for [253, 531, 791, 1069] for size 11.
Python Interview Questions on Searching and Sorting chapter 14 img 8

So, the result we get is:
{0: 253, 1: None, 2: 1069, 3: None, 4: None, 5: 511, 6: None, 7: None, 8: None, 9: None, 10: 791}

Question 10.
Write the code to implement the coding hash function.
Answer:
Let’s look at the execution statements for this program:

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = convert_to_string(phone_list)
folded_value = foldingjiash(str_phone_values)
folding_hash_table = hash(folded_value,11)
print(folding_hash_table)

1. A list of phone numbers is defined: phonejist = [4567774321, 4567775514, 9851742433, 4368884732]
2. The next statement “str_phonepy allies = convert_to_string(phone_ list)” calls a function convert to_string( ) and passes the phone_list as argument. The function in turn returns a list of lists. The function takes one phone number at a time converts it to a list and adds to new list. So, we get the output as: [[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘4’, ‘3’, ‘2’, M’], [‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’, ‘1’, ‘4’], [‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’], [‘4’, ‘3’, ‘6’, ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’]]. The following steps are involved in this function:

a. Define two lists a phone_list[ ]
b. For elements in phone_list, take every element i.e. the phone number one by one and:
i. convert the phone number to string: temp_string = str(i)
ii. Convert each string to list: tempjist = list (temp_string)
iii. Append the list obtained to the phone_list defined in previous step.
iv. Return the phone_list and assign values to str_phone_ values

def convert_to_string(input_list):
phone_list=[ ]
for i in input_list:
temp_string = str(i)
temp_list = list(temp_string)
phone_list.append(temp_list)
return phone_list

3. The list str_phone_values is passed on to folding_hash( ). This method takes a list as input.
a. It will take each phone list element which is also a list.
b. Take one list item one by one.
c. For every item concatenate first two characters convert them to integer and then concatenate next to characters convert them to integer and add the two values.
d. Pop the first two elements from thr list.
e. Repeat c and d till we have added all elements.
f. The function returns a list of hash values.

def folding_hash(input_list):
    hash_final = [ ]
    while len(input_list) > 0:
         hash_val = 0
         for element in input_list:
             while len(element) > 1:
                 stringl = element[0]
                 string2 = element[1]
                 str_contbine = string1 + string2
                 int_combine = int(str_combine)
                 hash_val += int_combine
                 element.pop(0)
                 element.pop(0)
             if len(element) > 0:
                hash_val += element[0]
             else:
                pass
             hash_final. append (hash_val)
        return hash final

4. Call hash function for size 11. The code for the hash function is same.

def hash(list_items, size):
    temp_list =[ ]
    for i in range (size) :
        temp_list.append(i)
    hash_table = diet.fromkeys(temp_list)
    for item in list_items:
        i = item%size
        hash_table[i] = item
    return hash_table

Code

def hash(list_items, size):
    temp_list =[ ]
    for i in range(size):
        temp_list.append(i)
    hash_table = diet.fromkeys(temp_list)
    for item in list_items:
        i = item%size
        hash_table[i] = item
   return hash_table
def convert_to_string(input_list):
    phone_list=[ ]
    for i in input_list:
        temp_string = str(i)
        temp_list = list(temp_string)
        phone_list.append(temp_list)
   return phone_list
def folding_hash(input_list):
    hash_final = [ ]
    while len(input_list) > 0:
         hash_val = 0
         for element in input_list:
             while len(element) > 1:
                 string1 = element[0]
                 string2 = element[1]
                 str_combine = string1 + string2
                 int_combine = int(str_combine)
                 hash_val += int_combine
                 element.pop(0)
                 element.pop(0)
            if len(element) > 0:
                hash_val += element[0]
           else:
              pass
           hash_final. append (hash_val)
    return hash_final

Execution

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = convert_to_string(phone_list)
folded_value = folding_hash (str_phone_valu.es)
folding_hash_table = hash(folded_value,11)
print(folding_hash_table)

Output

{0: 253, 1: None, 2: 1069, 3: None, 4: None, 5:
511, 6: None, 7: None, 8: None, 9: None, 10: 791}

In order to store phone numbers at the index, we slightly change the hash() function;

  1. The hash( ) function will take one more parameter : phone_list
  2. After calculating the index the corresponding element from the phone_list is saved instead of the folded_value.
def hash(list_items,phone_list, size):
    temp_list =[ ]
    for i in range(size):
        temp_list.append(i)
   hash_table = diet.fromkeys(temp_list)
   for i in range(len(list_items)):
       hash_index = list_items[i]%size
       hash_table[hash_index] = phone_list[i]
   return hash_table

Execution

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = ‘convert_to_string(phone_list)
folded_value = folding_hash(str_phone_values)
folding_hash_table = hash (folded_value,phone_ list,11)
print(folding_hash_table)

Output

{0: 4567774321, 1: None, 2: 4368884732, 3: None,
4: None, 5: 4567775514, 6: None, 7: None, 8: None,
9: None, 10: 9851742433}

Bubble sort

Bubble sort is also known as sinking sort or comparison sort. In bubble sort, each element is compared with the adjacent element, and the elements are swapped if they are found in the wrong order. However, this is a time-consuming algorithm. It is simple but quite inefficient.

Python Interview Questions on Searching and Sorting chapter 14 img 9

Question 10.
How will you implement bubble sort in Python?
Answer:
The code for a bubble sort algorithm is very simple.
Step 1: Define the function for bubble sort. It would take the list that needs
to be sorted as input.

def bubble_sort(input_list):

Step 2:
1. Set a loop for i in range len(input_list)
a. Inside this for loop set another loop for j in range len(input_ list)-i-1).
b. For every i, in the nested loop value at index j, is compared with the value at index j+1. If the value at index j+1 is smaller than the value at index j then the values are swapped.
c. After the for loop is overprint the sorted list.

Code

def bubble_sort(input_list):
    for i in range(len(input_list)):
        for j in range(len(input_list)-i-1):
            if input_list[j]>input_list[j+1]:
               temp = input_list[j]
               input_list[j]=input_list[j+1]
               input_list[j+1]= temp
    print(input_list)

Execution

x = [7,1,3,6,2,4]
print("Executing Bubble sort for ",x)
bubble_sort(x)

y = [23,67,12,3,45,87,98,34]
print("Executing Bubble sort for ",y)
bubble_sort(y)

Output

Executing Bubble sort for [7, 1, 3, 6, 2, 4]
[1, 2, 3, 4, 6, 7] 
Executing 98, 34] Bubble sort for [23, 67, 12, 3, 45, 87,
[3, 12, 23 , 34, 45, 67, 87, 98]

Question 11.
Write code to implement selection sort.
Answer:
Step 1: Define the function for selection_sort. It would take the list that
needs to be sorted as input.

def selection_sort(input_list):

Step 2:
1. Set a loop for i in range len(input_list)
a. Inside this for loop set another loop for j in range (i+1, len(input_ list)-i-l))
b. For every i, in the nested loop value at index j is compared with the value at index i. If the value at index j is smaller than the value at index i then the values are swapped.
c. After the for loop is overprint the sorted list.

Code

def selection_sort(input_list):
    for i in range(len(input list)-1) :
        for j in range(i+1,len(input list)):
            if input_list[j] < input_list[i]:
               temp = input_list[j]
               input_list[j] = input_list[i]
               input list[i] = temp
  print(input list)

Execution

selection_sort([15,10,3,19,80,85])

Output

[3, 10, 15, 19, 80, 85]

Insertion Sort

In insertion sort, each element at position x is compared with elements located at position x-1 to position 0. If the element is found to be less than any of the values that it is compared to then the values are swapped. This process is repeated till the last element has been compared.

Python Interview Questions on Searching and Sorting chapter 14 img 10

Question 12.
Write code to implement insertion sort.
Answer:
It is very easy to implement insertion sort:
Consider a list [7,1,3,6,2,4]
Let indexi = i
indexj = indexi + 1

Python Interview Questions on Searching and Sorting chapter 14 img 11

Step 1: Define the insert_sort( ) function. It will take input ist as input.

def insertion_sort(input_list):

Step 2: for i in range(input_list)-1), set indexi =1, indexj = i+1

for i in range(len(input_list)-1):
indexi = i
indexj = i+1

Step 3: set while loop, condition inaexi>=0

  • if input_list[indexi]>input_list[indexj]
  • swap values of input list [indexi] and input_list[indexj]
  • set indexi = indexi -1
  • set indexj = indexj -1
  • else
  • set indexi = indexi -1
while indexi >= 0:
            if input list[indexi]>input
list[indexj]:
               print("swapping")
               temp = input list indexi]
               input list[indexi] = input
list[indexj]
               input list[indexj] = temp
               indexi = indexi - 1
               indexj = indexj - 1
         else:
               indexi = indexi - 1

Step 4: Print updated list

Code

def insertion_sort(input_list):
    for i in range(len(input_list)-1):
        indexi = i
        indexj = i+1
        print("indexi = ", indexi)
        print("indexj = ", indexj)
        while indexi >= 0:
              if input_list[indexi]>input_ list[indexj]:
                            print("swapping")
                            temp = input_list[indexi]
                            input_list[indexi] = input
list[indexj]
                            input_list[indexj] = temp
                            indexi = indexi - 1
                            indexj = indexj - 1
                      else :
                            indexi = indexi - 1
                 print("list update:",input_list)
        print ("final list = ", input_list)

Execution

insertion_sort([9,5,4,6,7,8,2])

Output

[7, 1, 3, 6, 2, 4 ]
indexi = 0
indexj = 1
swapping
list update: [1, 7, 3, 6, 2, 4 ]
indexi = 1
indexj = 2
swapping
list update: [1, 3, 7, 6, 2, 4 ]
indexi = 2
indexj = 3
swapping
list update: [1, 3, 6, 7, 2, 4 ]
indexi = 3
indexj = 4
swapping
swapping
swapping
list update: [ 1, 2, 3,6,7,4]
indexi = 4
indexj = 5
swapping
swapping
list update: [1, 2, 3, 4, 6, 7]
final list = [1, 2, 3, 4, 6, 7]
>>>

Shell Sort

  • Shell sort is a very efficient sorting algorithm.
  • Based on insertion sort.
  • Implements insertion sort on widely spread elements at first and then in each step space or interval is narrowed down.
  • Great for medium size data set.
  • Worst case time complexity: O(n)
  • Worst-case space complexity : 0(n)

I Consider a list: [10,30,11,4,36,31,15,1]
Size of the list, n = 8
Divide n/2 = 4, let this value be named k
Consider every kth(in this case 4th) element and sort them in the right order.

Python Interview Questions on Searching and Sorting chapter 14 img 12

II. do the following:
k = k/2 = 4/2 = 2
consider every kth element and sort the order.

Python Interview Questions on Searching and Sorting chapter 14 img 13

III. Do the following:
k = k/2 = 2/ 2 = 1
This is the last pass and will always be an insertion pass.

Python Interview Questions on Searching and Sorting chapter 14 img 14

Question 13.
Write code to implement the shell sort algorithm.
Answer:
The following steps will be involved:
Step1: Define the shell_sort( ) function to sort the list. It will take the list(input_list) that needs to be sorted as the input value.

def shell_sort(input_list):

Step2:
Calculate size, n = len(inputjist)
Number of steps for the while loop, k = n/2

def shell_sort(input_list):
n = len(input_list)
k = n//2

Step 3:

  • While k > 0:
  • for j in range 0, size of input list
  • for i in range (k, n)
  • if the value of element at i is less than the element located at index i-k, then swap the two values
  • set k = k//2
while k > 0:
     for j in range(n):
         for i in range(k,n):
             temp = input_list[i]
             if input_list[i] < input_list[i-k]:
                input_list[i] = input_list[i-k]
                input_list[i-k] = temp
    k = k//2

Step 4: Print the value of the sorted list.

Code

def shell_sort(input_list):
    n = len(input_list)
    k = n//2
    while k > 0:
         for j in range.(n) :
             for i in range(k,n):
                 temp = input_list[i]
                 if input_list[i] < input_list[i-k]:
                     input_list[i] = input_list[i-k]
                     input_list[i-k] = temp
        k = k//2
   print(input_list)

Execution

shell_sort ([10, 30, 11, 1,36, 31, 15, 4)]

Output

[1, 4, 10, 11, 15, 30, 31, 36]

Quick sort

  • In quicksort, we make use of a pivot to compare numbers.
  • All items smaller than the pivot are moved to its left side and all items larger than the pivot are moved to the right side.
  • This would provide a left partition that has all values less than the pivot and a right partition having all values greater than the pivot.
  • Let’s take a list of 9 numbers: [15, 39, 4, 20, 50, 6, 28, 2, 13].
  • The last element ‘ 13 ’ is taken as the pivot.
  • We take the first element ‘15’ as the left mark and the second last element ‘2’ as the right mark.
  • If left mark > pivot and Highmark <pivot then swap left a mark and right mark and increment left mark by 1 and decrement right make by 1.
  • If leftmark> pivot and rightmark> pivot then only decrement the right mark.
  • Same way if leftmark<pivot and rightmark< pivot then only increment the left mark.
  • If left mark <pivot and rightmark>pivot, increment leftmark by 1 and decrement right mark by 1.
  • When the left mark and right mark meet at one element, swap that element with the pivot.

I
The updated list is now [2, 6, 4, 13, 50, 39, 28, 15, 20]:

  • Take the elements to the left of 13, takin 4 as a pivot, and sort them in the same manner.
  • Once the left partition is sorted take the elements on the right and sort them taking 20 as a pivot.

Python Interview Questions on Searching and Sorting chapter 14 img 15

II.

Python Interview Questions on Searching and Sorting chapter 14 img 16

Question 14.
Write the code to implement the quicksort algorithm.
Answer:
Step: Decide upon the Pivot

  • This function takes three parameters, the list(input list), starting (fast) and ending (last) index for the list that has to be sorted.
  • Take the input_list. pivot = input_list[last]. We set the pivot to the last value of the list.
  • Set the left_pointer to first.
  • Set right_pointer to last -1, because the last element is the pivot.
  • Set pivot flag to True.
  • While pivot_flag is true:
  • If left mark > pivot and right mark <pivot then swap left mark and right mark and increment left mark by 1 and decrement right mark by 1.
  • If leftmark> pivot and rightmark> pivot then only decrement the rightmark.
  • Same way if leftmark<pivot and rightmark< pivot then only increment the leftmark.
  • If leftmark <pivot and rightmark>pivot, increment leftmark by 1 and decrement right mark by 1.
  • When left mark and rightmark meet at one element, swap that element with the pivot.
  • When, leftmark >= rightmark, swap the value of the pivot with the element at left pointer, set the pivot_flag to false.
def find_pivot (input_list, first, last):
    pivot = input_list[last]
    print("pivot =", pivot)
    left_pointer = first
    print("left pointer = ", left_pointer, " ",input_list[left_pointer])
    right_pointer = last-1
    print("right pointer = ", right_pointer, " ",input_list[right_pointer])
    pivot_flag = True

   while pivot_flag:
         if input_list[left_pointer]>pivot:
            if input_list[right_pointer]<pivot:
                temp = input_list[right_pointer]
                input_list[right_pointer]=input_ list[left_pointer]

                input_list[left_pointer]= temp
                right_pointer = right_pointer-1
                left_pointer = left_pointer+1

       else:
                right_pointer = right_pointer-1
  else:
        left_pointer = left_pointer+1
        right_pointer = right_pointer-1
  if left_pointer >= right_pointer:
        temp = input_list[last]
  input_list[last] = input_list[left_pointer]
  input_list[left_pointer] = temp
  pivot_flag = False
print(left_pointer)
return left_pointer

Step 2:
Define quicksort(input list) function.

  • This function will take a list as input.
  • Decides the starting point(O) and end point(length_of_the_list-1) for sorting.
  • Call the qsHelper( ) function.
def quicksort(input_list):
    first = 0
    last = len(input_list)-1
    qsHelper (input_list,first, last)

Step 3:
Define the qsHelper( ) function

This function checks the first index and last index value, it is a recursive function, it calls the find_pivot method where left mark is incremented by 1 and the right mark is decremented by 1. So, as long as the left mark(which is parameter first in this case) is less than the right mark(which is parameter last in this case) the while loop will be executed where qsHelper finds a new value of pivot, creates; eft and right partition and calls itself.

def qsHelper (input_list,first, last) :
    if first<last:
         partition = find_pivot (input_ list, first, last)
         qsHelper(input_list, first,partition-1)
         qsHelper(input_list,partition+l,last)

Code

def find_pivot (input_list, first, last):
    pivot = input_list[last]
    left_pointer = first
    right_pointer = last-1
    pivot_flag = True

    while pivot_flag:
          if input_list[left_pointer]>pivot:
             if input_list[right_pointer]<pivot:
                temp = input_list[right_pointer]
                input_list[right_pointer]=input_ list[left_pointer]
                input_list[left_pointer]= temp
                right_pointer = right_pointer-l left_pointer = left_pointer+l 
        else:
                right_pointer = right_pointer-l
        else:
               if input_list[right_pointer]<pivot:
                 left_pointer = left_pointer+l 
              else:
                 left_pointer = left_pointer+l 
                 right_pointer = right_pointer-1
            if left_pointer >= right_pointer: 
            temp = input_list[last]
            input_list[last] = input_list[left_pointer]

            input_list[left_pointer] = temp 
            pivot_flag = False 
            return left_pointer 
def quicksort(input_list): 
first = 0 
last = len(input_list)-1 
qsHelper (input_list, first, last)
def qsHelper (input_list,first, last) : 
if firstclast:
partition = find_pivot (input_list,first, last) 
qsHelper (input_list, first, partition-1) 
qsHelper(input_list,partition+1,last)

Execution

input_list=[15,39,4,20, 50, 6,28,2, 13]
quicksort(input_list)
print(input list)

Output

[2,4, 6, 13, 15, 20, 28, 39, 50]

Python Interview Questions on Searching and Sorting Read More »

Python Interview Questions on Trees

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Trees

There are several types of data structures that can be used to tackle application problems. We have seen how linked lists work in a sequential manner, we have also seen how stacks and queues can be used in programming applications but they are very restricted data structures. The biggest problem while dealing with linear data structure is that if we have to conduct a search, the time taken increases linearly with the size of the data. Whereas there are some cases where linear structures can be really helpful but the fact remains that they may not be a good choice for situations that require high speed.

So, now let’s move on from the concept of linear data structures to nonlinear data structures called trees. Every tree has a distinguished node called the root. Unlike the trees that we know in real life the tree data structure branches downwards from parent to child and every node except the root is connected by a direct edge from exactly one other node.

Python Interview Questions on Trees chapter 13 img 1

Look at the figure given above:
A is the root and it is parent to three nodes – B, C, and D.
Same way B is a parent to E and C is a parent to F and G.

Nodes like D, E, F, and G that have no children are called leaves or external nodes.
Nodes that have at least child such as B and C are called internal nodes.
The number of edges from the root to the node is called the depth or level of a
node. The depth of B is 1 whereas the depth of G is 2.
The height of a node is the number of edges from the node to the deepest leaf.
B, C, and D are siblings because they have the same parent A. Similarly, F and
G are also siblings because they have the same parent C.
Children of one node are independent of children of another node.
Every leaf node is unique.

  • The file system that we use on our computer machines is an example of the tree structure.
  • Additional information about the node is known as payload. Payload is not given much importance in algorithms but it plays a very important role in modem day computer applications.
  • An edge connects two nodes to show that there is a relationship between them.
  • There is only one incoming edge to every node (except the root). However, a node may have several outgoing edges.
  • The root of the tree is the only node of the tree that has no incoming edges as it marks the starting point for a tree.
  • Set of nodes having incoming edges from the same node are the children of that node.
  • A node is a parent of all the nodes that connect to it by the outgoing edges.
  • A set of nodes and edges that comprises a parent along with all its descendants are called subtrees.
  • A unique path traverses from the root to each node.
  • A tree that has a maximum of two children is called a binary tree.

Recursive definition of a tree

A tree can be empty, or it may have a root with zero or more subtree. The root of every subtree is connected to the root of a parent tree by an edge.

Simple Tree Representation

Have a look at the following tree. Here, we are considering the case of a binary tree.

Python Interview Questions on Trees chapter 13 img 2

In the case of a binary tree, a node cannot have more than two children. So, for ease of understanding, we can say that the above scenario is similar to something like this:

Python Interview Questions on Trees chapter 13 img 3

In this diagram, left and right are references to the instances of the node that are located on the left and right of this node respectively. As you can see, every node has three values:

  1. Data
  2. Reference to the child on left
  3. Reference to the child on the right

Python Interview Questions on Trees chapter 13 img 4

So, the constructor for the node class to create a Node object will be as follows:

class Node(object):
     def_init_(self, data_value):
         self.data_value = data_value
         self.left = None
         self.right = None

So, this is how a root node is created:

# Root_Node
print ("Create Root Node")
root = Node("Root_Node")
print("Value of Root = ",root.data_value," left =",root.left, " right = ", root.right)

When we execute this block of code, the output is as follows:
Create Root Node

Value of Root = Root_Node left = None right = None
Value of Node = Tree Left left = None right = None

Now, we write code for inserting values to the left or right. When a node is created, initially it’s left and right reference point to None. So, to add a child to left we just need to say:
self. left = child_node
and a child can be added to right in a similar way:
self.left = child_node
However, if the root node is already pointing to some existing child and we try to insert a child node then the existing child should be pushed down one level and the new object must take its place. So, the reference of the existing child stored in self.left is passed on to child.left and then self.help is assigned the reference to child. This can be achieved in the following manner:

def insert_left (self, child):
     if self.left is None :
        self.left = child
else:
     child.left = self.left
     self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else :
    child.right = self.right
    self.right = child

Code

class Node(object):
     def_init_(self, data__value) :
        self . data_value = data_value
        self.left = None
        self.right = None

def insert_left(self, child):
     if self.left is None:
         self.left = child
else:
     child.left = self.left
     self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else:
    child.right = self.right
    self.right = child

Execution

# Root_Node
print ("Create Root Node")
root = Node("Root_Node")
print("Value of Root = ",root.data_value," left = ",root.left, " right = ", root.right)
#Tree_Left
print("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
print ("Value of Node = ", tree__left. data_value, " left =",tree_left.left, " right = ",tree_left. right)
print("Value of Root = ", root,data_value," left = ",root.left, " right = ", root.right)
#Tree_Right
print("Create Tree_Right")
tree__right = Node ("Tree_Right")
root.insert_right(tree_right)
print("Value of Node = ",tree_right.data_value, " left =",tree_right.left, " right = ",tree_right. right)
print("Value of Root = " , root. data__value, " left = ",root.left, " right = ", root.right)
#TreeLL
print("Create TreeLL") tree11 = Node("TreeLL")
tree_left.insert_left(tree11)
print("Value of Node = ",tree11.data_value," left =",tree11.left, " right = ",tree11.right)
print("Value of Node = ",tree_left.data_value," left =",tree_left.left, " right = ",tree_left. right)
print("Value of Root = ", root.data_value," left =",root.left, " right = ", root.right)

Output

Create Root Node
Value of Root = Root_Node left = None right = None
Create Tree_Left
Value of Node = Tree_Left left = None right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = None Create Tree_Right
Value of Node = Tree_Right left = None right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = < main
Node object at 0x000000479ED05E80>
Create TreeLL
Value of Node = TreeLL left = None right =
None
Value of Node = Tree_Left left = < main .Node
object at 0x000000479ED0F160> right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = < main .
Node object at 0x000000479ED05E80>

Question 1.
What is the definition of a tree?
Answer.
A tree is a set of nodes that store elements. The nodes have a parent-child relationship such that:

  • If the tree is not empty, it has a special node called the root of the tree. The root has no parents.
  • Every node of the tree different from the root has a unique parent node.

Question 2.
Write a code to represent a tree through lists or a list of lists.
Answer:
In the list of lists, we shall store the value of the node as the first element. The second element will be the list that represents the left subtree and the third element represents the right subtree. The following figure shows a tree with just the root node.

Python Interview Questions on Trees chapter 13 img 5
Now, suppose we add a node to the left.
Python Interview Questions on Trees chapter 13 img 6
Now, adding another subtree to the right would be equal to:
Python Interview Questions on Trees chapter 13 img 7
Same way adding a node to the left of Tree Left would mean:

Implement Trees with Lists

Python Interview Questions on Trees chapter 13 img 8

Here you can see that the tree can be defined as follows:
binary_tree = [ ‘Root_Node’ , [ ‘Tree_Left’ ,[ ‘TreeLL’,[ ],[ ] ],[ ] ], [ ‘Tree_Right’,[ ],[ ] ] ]

Here, the root is Root_Node which is located at binary_tree[0].
Left subtree is at binary_tree[1].
The right subtree is at binary_tree[2].
Now let’s write the code for this.

Step 1:

Define Class

class Tree:

Step 2:

Create Constructor

Now let’s write the code for the constructor. Here, when we create an object we pass a value. The constructor creates a list where the value is placed at index 0 and at index 1 and 2 we have two empty lists. If we have to add subtree at the left side we will do so at index 1 and for the right subtree, we will insert values in the list at index 2.

def_init_(self, data):
self.tree = [data, [ ],[ ] ]

Step 3:

Define a function to insert left and right subtree

If you have to insert a value in the left subtree then pop the element at index 1 and insert the new list at that place. Similarly, if you have to insert a child on the right-hand side, pop the value at index 2 and insert the new list.

def left_subtree(self,branch):
        left_list = self . tree.pop(1)
        self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
    self.tree.insert(2,branch.tree)

Now, let’s execute the code:

Code

class Tree:
     def_init_(self,data):
         self.tree = [data, [ ],[ ] ]

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
     self.tree.insert(2,branch.tree)

Execution

print("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ", root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ", root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ", root.tree)
Create Root Node
Value of Root = ['Root_node', [ ], [ ] ]
Create Left Tree
Value of Tree_Left = ['Root_node', ['Tree_Left', [ ] ]/ [ ] ]
Create Right Tree
Value of Tree_Right = ['Root_node', [ 'Tree_Left', [ ], [ ] ], ['Tree_Right', [ ], [ ] ] ]
Create Terrell
Value of Tree_Left = ['Root_node', ['Tree_Left', [ 'TreeLL', [ ], [ ] ], [ ] ], ['Tree_Right', [ ], [ ] ] ]
>>>

There is however one thing ignored in this code. What if we want to insert a child somewhere in between? Here, in this case the child will be inserted at the given location and the subtree existing at that place will be pushed down.

For this we make changes in the insert functions.

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    if len(left_list) > 1:
        branch.tree[1]=left_list
        self.tree.insert (1,branch.tree)
  else:
        self.tree.insert(1,branch.tree)

If we have to insert a child in the left then first we pop the element at index 1. If the length of element at index 1 is 0 then, we simply insert the list. However, if the length is not zero then we push the element to the left of the new child. The same happens in case of right subtree.

def right_subtree(self,branch):
       right_list = self.tree.pop (2)
       if len(right_list) > 1:
          branch.tree[2]=right_list
          self.tree.insert(2,branch.tree)
    else:
         self.tree.insert(2,branch.tree)
print ("Create TreeLL")
tree11 = Tree("TreeLL")
tree_left.left_subtree(tree11)
print("Value of Tree_Left = ", root.tree)

Code

class Tree:
   def_init_(self,data) :
      self.tree = [data, [ ], [ ] ]

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    if len(left_list) > 1:
       branch.tree[1]=left_list
       self.tree.insert (1,branch.tree)
  else:
       self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
    if len(right_list) > 1:
        branch.tree[2]=right_list
        self.tree.insert(2,branch.tree)
   else:
      self.tree.insert(2,branch.tree)

Execution

print ("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ", root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ", root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ", root.tree)
print("Create Left Inbetween")
tree_inbtw = Tree("Tree left in between")
root.left_subtree(tree_inbtw)
print("Value of Tree_Left = ", root.tree)
print("Create TreeLL")
treell = Tree("TreeLL")
tree_left.left_subtree(tree11)
print("Value of TREE = ", root.tree)

Output

Create Root Node
Value of Root = ['Root node', [ ], [ ] ]
Create Left Tree
Value of Tree Left = [ 'Root node', [ 'Tree Left', [ ], [ ] ], [ ] ]
Create Right Tree
Value of Tree Right = [ 'Root node' , [ 'Tree Left', [ ] , [lie 1 'Tree Right', [], [ ] ] ]
Create Left Inbetween
Value of Tree Left = [ 'Root node' , [ 'Tree left in between' , [ 'Tree Left', [ ] , [ ] ] , [ ] ] ,
['Tree_Right', [ ], [ ] ] ]
Create TreeLL
Value of TREE = [ 'Root node', [ 'Tree left in between' , ['Tree Left' , [ 'TreeLL', [ ], [ ] ], [ ]], ['Tree_Right', [ ], [ ] ] ]
>>>

Question 3.
What is a binary tree? What are the properties of a binary tree?
Answer:
A data structure is said to be a binary tree if each of its nodes can have at most two children. The children of the binary tree are referred to as the left child and the right child.

Question 4.
What are tree traversal methods?
Answer:
Traversals
Preorder Traversal: First visit the root node, then visit all nodes on the left followed by all nodes on the right.

Code

class Node(object) :
     def_init_(self, data_value):
         self.data_value = data_value
         self.left = None
         self.right = None
def insert_left(self, child):
     if self.left is None:
        self.left = child
else:
      child.left = self.left
      self.left = child
def insert_right(self, child):
      if self.right is None:
         self.right = child
else:
     child.right = self.right
     self.right = child
def preorder(self, node):

res= [ ]
if node:
      res.append(node.data_value)
      res = res + self.preorder(node.left)
      res = res + self.preorder(node.right) 
   return res

Execution

# Root_Node
print("Create Root Node")
root = Node("Root_Node")
#Tree_Left
print ("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")
root.insert_right(tree_right)
#TreeLL
print ("Create TreeLL")
treell = Node("TreeLL")
tree_left.insert_left(treell)
print("*****Preorder Traversal*****")
print(root.preorder(root))

Output

Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Preorder Traversal*****
['Root_Node', 'Tree_Left', 'TreeLL', 'Tree_ Right']
>>>

In Order Traversal :First visit all nodes on the left then the root node and then all nodes on the right..

class Node(object):
     def_init_(self, data_value):
          self.data_value = data_value
          self.left = None
          self.right = None
   def insert_left(self, child):
       if self.left is None:
          self.left = child
   else:
      child.left = self.left
       self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else:
     child.right = self.right
     self.right = child
def inorder(self, node):
  res=[ ]
  if node:
       res = self.inorder(node.left)
       res.append(node.data_value)
        res = res + self.inorder(node.right)
  return res
# Root_Node
print("Create Root Node")
root = Node("Root_Node")
#Tree_Left
print ("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")
root.insert_right(tree_right)
#TreeLL
print("Create TreeLL")
treell = Node ("TreeLL")
tree_left.insert_left (treell)
print("*****Inorder Traversal*****)
print(root.inorder(root))

Output

Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
["TreeLL' , 'Tree_Left' , 'Root_Node' , 'Tree_Right']
>>>

Post order Traversal: Visit all nodes on the left, then visit all nodes on the right , then visit the root node.

code

class Node(object):
     def_init_(self, data_value):
        self.data_value = data_value
        self.left = None
        self.right = None
    def insert_left (self, child):
        if self.left is None:
           self.left = child
else:
     child.right = self.right
     self.right = child
def postorder (self, node):
res = [ ]
if node:
    res = self.postorder (node.left)
    res = res + self.postorder (node.right)
    res.append (node.data_value)

   return res

Execution

#Root_Node
print("Create Root Node")
root = Node ("Root_Node")
#Tree_Left
print("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")

root . insert_right(tree_right)
#TreeLL
print ("Create TreeLL")
tree11 = Node ("TreeLL")
tree_left . insert_left(tree11)
print("*****postorder Traversal *****")
print (root.postorder (root))
OUTPUT
Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Postorder Traversal*****
['TreeLL' , 'Tree_Left' , 'Tree_Right' , "Root_Node']

A binary heap is a binary tree. It is a complete tree, which means that all levels are completely filled except possibly the last level. It also means that the tree is balanced
As every new item is inserted next to the available space. A Binary heap can be stored in an array.

A binary heap can be of two types: Min Heap or Max Heap. In case of Min Heap binary heap, the root node is the minimum of all the nodes in the binary heap,all parent nodes are smaller than their children. On the other hand in case of Max Heap the root is the maximum among all the keys present in the heap and and all nodes are bigger than their children.

 

Python Interview Questions on Trees chapter 13 img 9

Heap has two important properties:
1. It is complete and is constructed from left to right across each row and the last row may not be completely full. Each row should be filled
up sequentially. So, the order of inserting values should be from left to right, row by row sequentially as shown in the following figure:

 

Python Interview Questions on Trees chapter 13 img 10

2. The parent must be larger (Max Heap)/smaller(Min Heap) than the children.

 

Python Interview Questions on Trees chapter 13 img 11

Look at the figure shown above, it is a case of Maximum heap because all parents are greater than their children.
The binary heap can be represented in an array as follows:
0 1 2 3 4 5

 

Python Interview Questions on Trees chapter 13 img 12

If you look at the array carefully you will realize that if a parent exists at location n then the left child is at 2n+l and the right child is at 2n + 2. ”
n= 0

 

Python Interview Questions on Trees chapter 13 img 13

So, if we know the location of the parent child we can easily find out the location of the left and right child.
Now suppose we have to build up a Max Heap using following values: 20,4, 90, 1, 125

Step 1:
Insert 20

 

Python Interview Questions on Trees chapter 13 img 14

Step 2:
Insert 4 -> Left to Right-> First element in second row

 

Python Interview Questions on Trees chapter 13 img 15

Since the parent is greater than the child, this is fine.

Step 3:
Insert 90 -> Left to Right -> Second element in second row
However when we insert 90 as the right child, it violates the rule of the max heap because the parent has a key value of 20. So, in order to resolve this problem it is better to swap places as shown in the following figure:

 

Python Interview Questions on Trees chapter 13 img 16

After swapping, the heap would look something like this:

 

Python Interview Questions on Trees chapter 13 img 17

Step 4:
Insert 1 -> left to right -> first element third row

 

Python Interview Questions on Trees chapter 13 img 18

Since 1 is smaller than the parent node, this is fine.
Step 5:
Insert 125

 

Python Interview Questions on Trees chapter 13 img 19

This violated the rule of Max Heap Swap 4 and 125

 

Python Interview Questions on Trees chapter 13 img 20

Not a heap still Swap 125 and 90

 

Python Interview Questions on Trees chapter 13 img 21

We now have a Max Heap.

Question 5.
Write python code to implement Max Heap. How would you insert a value so that the root node has the maximum value and all parents are greater than their children.
Answer:
Here we will write The code to implement Maxheap class. The class will have two functions:
Push( ) : To insert value.
FIoat_up( ): To place the value where it belongs.

Step 1

Define the class

class MaxHeap:

Step 2

Define The Constructor

def init (self):
self.heap = [ ]

Step 3

Define the push( ) function

The push function does two jobs:

  1. Appends the value at the end of the list. (We have seen earlier that the value has to be inserted first at the available location)
  2. After appending the value, the push() function will call the float_ up(index) function. The pushQ function passes the index of the last element to the float_up() function so that the float_up() function can analyse the values and do the needful as described in the next step.
def push(self,value):
                 self.heap.append(value)
                 self .floatj_up (len (self . heap) -1)

Step 4
Define the float_up function
1. The float_up( )function takes index value as parameter.

def float_up (self, index) :

2. The push( ) function passes the index value of the last element in the heap. The first thing that the float function does is that it checks if the element is at index 0 or not. If yes, then it is the root node. Root node has no parents and since it’s the last element of the heap it has no children either. So, we can return the value.

if index==0:
return

3. If the index is greater than 0 then we can proceed further. Look the following figure once again:

 

Python Interview Questions on Trees chapter 13 img 22

For programming, you need to understand few things:

The index 0 has two children at position 1 and 2. If I have an element at 1 then I can find the parent by calculating value of (1//2). Similarly for element at index 2, the parent’s index value can be found out by calculating value of (2//2 -1). So, we can say that if an element has an index value index and it is odd then it’s parent’s index value, parent_ ofindex = index//2. However, if index is even parentofindex will be (index//2)-1. This becomes the outer frame for the float_up function. The right child has an even number as index and the left child has an odd number as index.

if index==0:
         return
   else:
      if index%2==0:
         parent_of_index = (index//2)-l
         ----------write code----------
  else:
         parent_of_index = index//2
         ----------write code--------

4. Now, we compare the values of the child and the parent. If the child is greater than the parent, swap the elements.

def float_up (self, index) :
        if index==0:
              return
      else:
        if index%2==0:
           parent_of_index = (index//2)-1
           if self.heap[index]> self, heap[parent_of_index]:
          self.swap(index, parent_of_index)
     else:
          parent_of_index = index//2
          if self.heap[index]> self, heap[parent_of_index]:
         self.swap(index, parent_of_index)
         self.float_up (parent_of_index)

Step 5

Define the swap function

The swap( ) function helps in swapping the values of the parent and the child, the code for this is given as follows:

def swap(self,indexl, index2):
      temp = self.heap[index1]
      self.heap[index1] = self.heap[index2]
      self.heap[index2] = temp

Code

class MaxHeap:
      def_init_(self):
          self.heap = [ ]
     def push(self,value):
          self.heap.append(value)
          self .float_up (len (self .heap) -1)
    def float_up (self, index) :
         if index==0:
 return
    else:
            if index%2==0:
             parent_of_index = (index//2)-1
             if self.heap[index]> self, heap[parent_of_index]:
          self.swap(index, parent_of_ index)
  else:
            parent_of_index = index//2
            if self.heap[index]> self, heap[parent_of_index]:
            self.swap(index, parent_of_index)
           self .float_up (parent_of_index)
def peek(self):
      print(self.heap[0])
def pop(self):
        if len(self.heap)>=2:
           temp = self.heap[0]
             self.heap[0]=self.heap[len(self.heap)-1]
              self.heap[len(self.heap)-1]
             self.heap.pop( )
             self.down_adj( )
      elif len(self.heap)==1:
            self.heap.pop( )
  else:
            print("Nothing to pop")
 def swap(self,indexl, index2):
            temp = self.heap[index1]
            self.heap[indexl] = self.heap[index2]
            self.heap[index2] = temp

Execution

H = MaxHeap( )
print("*****pushing values***********")
print("pushing 165")
H.push(165)
print(H.heap)
print("pushing 60")
H.push (60)
print(H.heap)
print("pushing 179")
H.push(179)
print(H.heap)
print("pushing 400")
H.push(400)
print(H.heap)
print("pushing 6")
H.push(6)
print(H.heap)
print("pushing 275")
H.push(275)
print(H.heap)

Output

*****pushing values***********
pushing 165
[165]
pushing 60
[165, 60]
pushing 179
[179, 60, 165]
pushing 400
[400, 179, 165, 60]
pushing 6
[400, 179, 165, 60, 6]
pushing 275
[400, 179, 275, 60, 6, 165]
>>>

Question 6.
Write code to find out the maximum value in the Max heap.
Answer:
It is easy to find the max value in the max heap as the maximum value is available at the root node which is index 0 of the heap.

def peek(self):
print(self.heap[0])

Question 7.
Write the code to pop the maximum value from Max Heap.
Answer:
There are two steps involved:

  1. Swap the root with the last element in the array and pop the value.
  2. The root node now does have the maximum value. So, now we need to move downwards, comparing the parent with their left and right child to ensure that the children are smaller than the parent. If not we will have to swap places again.

Step 1

Define pop( ) function.

The pop( ) function which swaps the values of the root node with the last element in the list and pops the value. The function then calls the down_ adj( ) function which moves downwards and adjusts the values. The pop() function first checks the size of the heap. If the length of the heap is 1 then that means that it only contains one element that’s the root and there is no need to swap further.

def pop(self):
          if len(self.heap)>2:
              temp = self.heap[0]
              self.heap[0]=self.heap[len(self.heap)—1]
              self.heap[len(self.heap)-1]
              self.heap.pop ( )
              print("heap after popping largest value =", self.heap)
             self.down_adj( )
        elif len(self.heap)==1:
            self.heap.pop( )
     else:
          print("Nothing to pop")

Step 2:

Define downadj( ) function

Set Index Value To 0.
Index of left child = left_child = index*2+1 Index of right child = right child = index*2+2
Then we go through loop where we check the value of the parent with both left and right child. If the parent is smaller than the left child then we swap the value. We then compare the parent value with the right child, if it is less then we swap again.
This can be done as follows:

  • Check if parent is less than left child:
  • If yes, check if left child is less than the right child
  • if yes, then swap the parent with the right child
  • Change the value of index to value of right_child for further assessment
  • If no the just swap the parent with the left child
  • Set the value of index to value of left_child for further assessment
  • If the parent is not less than left child but only less than the right child then swap values with the right child
  • Change the value of index to right_child
def down_adj(self):
index = 0
for i in range(len(self.heap)//2):
left_child = index*2+1 .
if left_child > len (self.heap) :
return
print("left child = ", left_child)
right_child = index*2+2
if right_child > len (self.heap) :
return
print("right child = ", right_child)
if self.heap[index]<self.heap[left_child]:
temp = self.heap[index]
self.heap[index] = self.heap[left_child]
self.heap[left_child] = temp
index = left_child
if self.heap[index]<self.heap[right_child]:
temp = self.heap[index]
self.heap[index] = self.heap[right_child]
self.heap[right_child] = temp
index = right_child

Code

class MaxHeap:
      def_init_(self):
         self.heap = [ ]
    def push(self,value):
         self.heap.append(value)
         self .float_up (len (self, heap) -1)
def float_up (self, index) :
     if index==0:
           return
    else:
         if index%2==0:
               parent_of_index = (index//2)-1
               if self.heap[index]> self, heap[parent_of_index]:
                            temp = self.heap[parent_of_index]
                           self.heap[parent_of_index] =self.heap[index]
                              self.heap[index] = temp
         else:
               parent_of_index = index//2
               if self.heap[index]> self, heap[parent_of_index]:
                           temp = self.heap[parent_of_index]
                           self.heap[parent_of_index] = self.heap[index]
                           self.heap[index] = temp self.float_up (parent_of_index)
     def peek(self):
              print(self.heap [0])
     def pop(self):
           if len(self.heap)>=2:
                    temp = self.heap[0]
                    self.heap[0]=self.heap[len(self.heap)-1]
                    self.heap[len(self.heap)-1]
                    self.heap.pop( )
                    self.down_adj( )
                elif len(self.heap)==1:
                    self.heap.pop ( )
        else:
                 print ("Nothing to pop")
def swap(self,indexl, index2):
                temp = self.heap[index1]
                self.heap[indexl] = self.heap[index2]
                self.heap[index2] = temp

def down_adj(self):
       index = 0
       for i in range(len(self.heap)//2):
            left_child = index*2+1
            if left_child > len(self.heap)-1:
                 print(self.heap)
                 print("End Point")
                 print("Heap value after pop( ) =",self.heap)
     return
            right_child = index*2+2
            if right_child > len(self.heap)-1:
                   print ("right child does not exist")
                     if self.heap[index]<self.heap[left_child]:
                 self.swap(index,left_child)
                     index = left_child
                print("Heap value after pop( ) =", self.heap)
   return
                 if self.heap[index]<self.heap[left_child]:
                if self.heap[left_child]<self. heap[right_child]:
               self.swap(index,right_child) index = right_child 
      else:
                 self.swap(index,left_child) index = left_child
                  elif self.heap[index]<self.heap[right_child]:
           self.swap(index,right_child) index = right_child
   else:
           print("No change required" )
          print("Heap value after pop() = ", self.heap)

 

Execution

H = MaxHeap( )
print("*****pushing values***********")
H.push (165)
print(H.heap)
H.push(60)
print(H.heap)
H.push(179)
print(H.heap)
H.push(400)
print(H.heap)
H.push(6)
print(H.heap)
H.push(275)
print(H.heap)
print("*********popping values*******")
H.pop ( )
H.pop( )
H.pop ( )
H.pop ( )
H.pop ( )
H.pop ( )
H.pop ( )

Output

pushing values
[165]
[165, 60]
[179, 60, 165]
[400, 179, 165, 60]
[400, 179, 165, 60, 6]
[400, 179, 275, 60, 6, 165]
*********popping values*******
[275, 179, 165, 60, 6]
End Point
Heap value after pop( ) = [275, 179, 165, 60, 6]
right child does not'exist
Heap value after pop() = [179, 60, 165, 6]
Heap value after pop() = [165, 60, 6]
right child does not exist
Heap value after pop() = [60, 6]
Heap value after pop () = [6]
Nothing to pop
>>>

Question 8.
Time complexity for max heap:
Answer:

  • Insert: 0(log n)
  • Get Max: 0(1) because the maximum value is always the root at ‘ index( )
  • Remove Max: 0(log n)

The implementation of Min Heap is similar to Max Heap just that in this case the root has the lowest value and the value of parent is less than the left and right child.

Code

class MinHeap:
def_init_(self):
     self.heap = [ ]
def push(self,value):
      self.heap.append(value)
      self .float_up (len (self .heap) -1)
def float_up (self, index) :
   if index==0:
        return
else:
   if index%2==0:
        parent_of_index = (index//2)-1
        if self.heap[index]< self, heap[parent_of_index]:
        self.swap(index, parent_of_index)
else:
       parent_of_index = index//2
      if self.heap[index]< self, heap[parent_of_index]:
     self.swap(index, parent_of_index)
     self .floatyup (parent_of_index)
def peek(self) :
      print(self.heap [0])
def pop (self) :
     if len(self.heap)>=2:
     temp = self.heap[0]
     self.heap[0]=seIf.heap[len(self.heap)-1]
     self.heap[len(self.heap)-1]
     self.heap.pop ( )
     self.down_adj( )
  elif len(self.heap)==1:
     self.heap.pop()
else:
     print("Nothing to pop")
def swap(self,indexl, index2):
     temp = self.heap[index1]
     self.heap[indexl] = self.heap[index2]
     self.heap[index2] = temp

Execution

H = MinHeap( )
print("*****pushing values***********")
print("pushing 165")
H.push (165)
print(H.heap)
print("pushing 60")
H.push(60)
print(H.heap)
print("pushing 179")
H.push(179)
print(H.heap)
print("pushing 400")
H.push(400)
print(H.heap)
print("pushing 6")
H.push (6)
print(H.heap)
print("pushing 275")
H.push(275) '
print(H.heap)

Output

*****pushing values***********
pushing 165 [165]
pushing 60
[60, 165]
pushing 179
[60, 165, 179]
pushing 400
[60, 165, 179, 400]
pushing 6
[6, 60, 179, 400, 165]
pushing 275
[6, 60, 179, 400, 165, 275]
>>>

Question 9.
What are the applications of binary heap?
Answer:

  • Dijkstra Algorithm
  • Prims Algorithm
  • Priority Queue
  • Can be used to solve problems such as:
  • K’th Largest Element in an array
  • Sort an almost sorted array
  • Merge K Sorted Array

Question 10.
What is a priority queue and how can it be implemented?
Answer:
Priority queue is like a queue but it is more advanced. It has methods same as a queue. However, the main difference is that it keeps the value of higher priority at front and the value of lowest priority at the back. Items are added from the rear and removed from the front. In priority queue elements are added in order. So, basically there is a priority associated with every element. Element of highest priority is removed first. Elements of equal priority are treated ass per their order in queue.

Binary heap is the most preferred way of implementing priority queue as they can retrieve the element of highest priority in 0(1) time. Insert and delete can take O(logn) time. Besides that since, the binary heap use lists or arrays, it is easy to locate elements and the processes involved are definitely quite cache friendly. Binary heaps do not demand extra space for pointers and are much easier to insert.

Python Interview Questions on Trees Read More »

Python Interview Questions on Recursion

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Recursion

When a function makes a call to itself it is called recursion. The same sets of instructions are repeated again and again for new values and it is important to decide when the recursive call must end. For Example: Let’s look at the code to find the factorial of a number.
If we use a loop then a factorial function would look something like this:

Code

def factorial(number):
     j = 1
     if number==0|number==1:
        print(j)
     else:
           for i in range (1, number+1):
              print(j," * ",i," = ",j*i)
           j = j*i
    print(j)

Execution

factorial(5)

Output

1 * 1 = 1
1 * 2 = 2
2 * 3 = 6 
6 * 4 = 24
24 * 5 = 120
120 
>>>

Now, let’s have a look at how we can solve the same problem using a recursive algorithm.

Code

def factorial(number):
    j = 1
    if number==0 | number==1:
        return j
    else:
     return number*factorial(number-1)

Execution

print(factorial(4))

Output
24

Pros and Cons

Recursive functions make the code look neat, it helps in breaking a complex task into simpler sub-problems. It can be easier than implementing iterations. However, it can be a little difficult to understand the logic behind recursion. Recursion can consume more memory and time and can be hard to debug.

Question 1.
Write code to find the sum of natural numbers from 0 to the given number using recursion.
Answer:

IResult
00
11+0=i(1)+i(0)=1
22+1=i+i(1)=3
33+3=i+i(2)=6
44+6=i+i(3)=10
55+10=i+i(4)=15

Observe for i = 0, the result is 0, thereafter result = i(n)+i(n-l)

Code

def natural sum(num):
     if num == 0
          return 0
     else:
         return (num + natural sum(num-1) )

Execution

print (natural_sum(10))

Output

55

Question 2.
What would be the output for the following code?

def funny (x,y):
       if y == 1:
          return x [0]
      else:
           a = funny (x, y-1)
           if a>x [y-1]
            return a
     else:
         return x[y-1]
x = [1,5,3,6,7]
y = 3
print (funny (x,y) )

Answer:
If we insert a print statement in the code and execute the code again we can see the actual sequence in which it executes:

def funny(x,y):
   print("calling funny , y = ",y)
   if y == 1:
      return x[0]
else:

   print("inside else loop because y = ", y)
   a = funny(x, y-1)
   print("a = ", a)
   if a > x[y-1]:
       print("a = ",a, " Therefore a > ",x[y-1])
       return a
   else:
       print("a = ",a, " Therefore a < ",x[y-1])
return x[y-1]
x = [1,5,3,6,7]
y = 3
print(funny(x,y))

Output

calling funny , y = 3
inside else loop because y = 3
calling funny , y = 2
inside else loop because y = 2
calling funny , y = 1
a = 1
a = 1 Therefore a < 5
a = 5
a = 5 Therefore a > 3
5
The answer is 5

Question 3.
What would be the output of the following code?

def funny(x):
      if (x%2 == 1) :
         return x+1
     else:
        return funny(x-1)
print(funny(7))
print(funny(6))

Answer:
For x =7
1. x = 7
2. x % 2 is 1
return 7 + 1
For x = 6
1. x =6
2. x%2 = 0
3. Return funny(5)
4. x = 5 .
5. x%2 =1
6. Return x+1 = 6

Question 4.
Write Fibonacci sequence using recursion. Answer:
The Fibonacci sequence = 0, 1, 2, 3, 5, 8, 13 ……….

IResult
00
11
21+0=i(0)+i(1)=1
31+1=i(2)+i(1)=2
42+1=i(3)+i(2)=3
53+2=i(4)+i(3)=5

Observe for i = 0, the result is 0 and for i = 1, the result is 1. Thereafter, the value of i(n) = i(n-1) + i(n-2). We implement the same, when we try to find Fibonacci code using recursion.

  • The fibonacci_seq(num), takes a number as argument.
  • If num = 0, result is 0
  • If num = 1, result is 1
  • Else result is fibonacci_seq(num-l) + Fibonacci_seq(num-2)
  • If you want to find Fibonacci Sequence for 10 then:
  • For elements 0 to 10 o Call the fibonacci_seq( ) function
  • fibonacci_seq(0) = 0
  • fibonacciseq(l) = 1
  • fibonacci_seq(2) = fibonacci_seq(l)+ fibonacci_seq(0)
  • fibonacci_seq(3) = fibonacci_seq(2)+ fibonacci_seq(3)

Code

def fibonacci_seq (num) :
     if num <0:
          print("Please provide a positive integer value")
    if num == 0:
           return 0
    elif num == 1:
          return 1
   else:
        return (fibonacci_seq (num-1) +fibonacci_ seq(num-2))

Execution

for i in range(10):
     print (fibonacci_seq(i))

Output

0
1
1
2
3
5
8
13
21
34

Question 5.
What is memoization?
Answer:
Basically, in memoization, we maintain a look-up table where solutions are stored so that we don’t have to solve the same sub-problem again and again. Instead, we solve it once and store the values so that they can be reused.

We know that Fibonacci sequence is:
F(n) = F(n-1)+F(n-2) if n>1 = n if n =0,1
So,
F(n):
if n<1:
return n
else :
return F(n-1)+F(n-2)
Here, we are making two recursive calls and adding them up and the value is returned.
Look at the following diagram:

Python Interview Questions on Recursion chapter 12 img 1

Just to find Fibonacci(5), Fibonacci(2) is computed three times and Fibonacci (3) is computed two times. So, as n increases Fibonacci function’s performance will go down. The consumption of time and space would increase exponentially with an increase in n. In order to save time what we can do is save a value when it is computed for the first time. So, we can save F(2) when it is computed for the first time, the same way with F(3), F(4)… so on. So, we can say that:

F(n):
if n=<1:
return n
elif f(n) exist:
return F(n-1)
else:
F(n) = F(n-1) + F(n-2)
save F(n).
Return F(n).

In the code below:

  1. The function Fibonacci( ) takes a number and creates a list, fib_num of size num+1. This is because the Fibonacci series starts from 0.
  2. It calls the function fib_calculate( )which takes the number num and lists fib_num as a parameter.
  3. We have saved-I at all index in the list:

a. If fib_num[num] is>0, that means Fibonacci for this number already exists and we need not compute it again and the number can be returned.
b. If num <= 1 then return num.
c. Else if num >=2, calculate fib_calculate(num – 1, fib num) + fib_calculate(num – 2, fib_num). The value calculated must be stored in list fib_num at index num so that there is no need to calculate it again.

Code

def fibonacci (num) :

   fib_num = [-1] * (num + 1)
   return fib_calculate (num, fib_num)
def fib_calculate (num, fib_num) :
   if fib_num [num] >= 0:
        return fib_num[num]

if (num <= 1):
    fnum = num
else:
     fnum = fib_calculate (num - 1, fib_num) + fib_ calculate (num - 2, fib_num)
fib_num [num] = fnum

return fnum

Execution

num = int(input('Enter the number: '))
print ("Answer = ", fibonacci (num) )

Output

Enter the number: 15 
Answer = 610
>>>

Question 6.
What would be the output of the following program?

def test_function(i, j) :
      if i == 0:
          return j;
      else:
           return test_function(i-1, j+1)
    print (test_function(6,7) )

Answer:

IJI==0?Return
67NoTest_function(5,8)
58NoTest_function(4,9)
49NoTest_function(3,10)
310NoTest_function(2,11)
211NoTest_function(1,12)
112NoTest_function(0,13)
013Yes13

The output will be 13.

Question 7.
What will be the output for the following code:

def even(k):
    if k <= 0:
        print("please enter a positive value")
    elif k == 1:
           return 0
   else:
       return even(k-1) + 2
print(even(6))

Answer:

KK<=0K ==1Result
6noNoEven(5)+2
5NoNoEven(4)+2+2
4NoNoEven(3)+2+2+2
3NoNoEven(2)+2+2+2+2
2NoNoEven(1)+2+2+2+2+2
1Noyes0)+2+2+2+2+2

Question 8.
Write a code to find the n_power(n), of 3 using recursion. Answer:
1. Define function n_power(n), it takes the value of power and parameter(n).
2. If n = 0 then return 1 because any number raised to power 0 is 1.
3. Else return (n_power(n-1)).

NN<0N ==0Result
4NoNon_power(3)*3
3NoNon_power(2)*3*3
2NoNon_power(1)*3*3*3
1NoNon_power(0)*3*3*3*3
0NoYes1*3*3*3*3

Code

def n_power(n):
    if n < 0:
       print ("please enter a positive value")
   elif n == 0:
        return 1
   else:
       return n_power(n-1)*3

Execution

print(n_power(4))

Output

81

Python Interview Questions on Recursion Read More »