Learning Python
For the last couple of weeks I have been teaching myself Python outside of school. So far in my education through school I have taken CSC110 and CSC205 which are both Java classes. I started looking for internships and realized there is a high demand for developers who also know Python so I began to learn the basics of it. I attached a screenshot of my Visual Studio Code of a program I wrote from direct questions that are asked of you in coding interviews in jobs and internships. What they are trying to see is if you can manipulate data in an algorithm to return values from an array.
In the screenshot above the problem is that the user enters an array of different values inside of it. Then they give you a target sum as an integer and see if any two values in the array add up to the target sum that is given. If the target sum is found you have to return the value to the user in a new array. This is a useful technique in real life data structures since it gives you the basics of how to run through data in an algorithm. First I start by creating a function called twoNumberSum that takes in the array from the user and the target sum they choose. After that I initialize my array that will be returning outside of both of my loops. This is because you cant initialize a value inside of a loop otherwise it will just keep resetting. We then use a nice technique inside of Python called enumerate. This runs through an array but also keeps track of the index as well as the element in the index. In java you usually only have i as the index then you have to initialize the element inside of the loop but this lets you get both from the start. Once we do that we store the element in another temp called value1 and value2 to make our code more readable. We add both the values and store them in temp to run through an if condition. If both the temp value is equal to the target sum we then "append" these values to the array we initialized outside of the loop. In Python append is used to add something to our array. Once we run through both loops and all the elements we return the numbers list even if we didn't find any values that add up to the target sum.
Okay, now this is great! Keep it up!
ReplyDelete