Search

How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

Any coding interview is a test which primarily focuses on your technical skills and algorithm knowledge. However, if you want to stand out among the hundreds of interviewees, you should know how to use the common functionalities of Python in a convenient manner.The type of interview you might face can be a remote coding challenge, a whiteboard challenge or a full day on-site interview. So if you can prove your coding skills at that moment, the job letter will reach you in no time. You may go through some of the top Python interview questions and answers provided by experts which are divided into three levels- beginner, intermediate and advanced. A thorough practice of these questions and answers on Python will definitely help you achieve your dream job as a Python Developer, Full Stack engineer, and other top profiles.A Python coding interview is basically a technical interview. They are not just about solving problems, they are more about how technically sound you are and how you can write clean productive Python code. This will show your depth of knowledge about Python and how you can use Python’s built-in functions and libraries to implement your code. Go through our Python Tutorials to learn more about  concepts related to Python. Let us look into some of the built-in functions provided by Python and how to select the correct one, learn about the effective use of data structures, how standard libraries in Python can be utilized and so on.How to Select the Correct Built-in Function?Python’s library of built-in functions is small as compared to the standard library. The built-in functions are always available and are not needed to be imported. It is suggested to learn each function before sitting for the interview. Till then, let us learn a few built-in functions and how to use them and also what alternatives can be used.Perform iteration with enumerate() instead of range() Consider a situation during a coding interview: You have a list of elements and you have to iterate over the list with the access to both the indices and values. To differentiate between iteration with enumerate()  and iteration with range(), let us take a look at the classic coding interview question FizzBuzz. It can be solved by iterating over both indices and values. You will be given a list of integers and your task will be as follows:Replace all integers that are evenly distributed by 3 with “fizz”.Replace all integers divisible by 5 with “buzz”.Replace all integers divisible by 3 and 5 with “fizzbuzz”.Developers make use of range() in these situations which can access the elements by index:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i in range(len(list_num)):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz'   >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']Though range() can be used in a lot of iterative methods, it is better to use enumerate() in this case since it can access the element’s index and value at the same time:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i,num in enumerate(list_num):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz' >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']The enumerate() function returns a counter and the element value for each element. The counter is set to 0 by default which is also the element’s index.  However, if you are not willing to start your counter from 0, you can set an offset using the start parameter:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i, num in enumerate(list_num, start=11):       print(i, num) 11 30 12 29 13 10 14 65 14 95 16 99You can access all of the same elements using the start parameter. However, the count will start from the specified integer value.Using List Comprehensions in place of map() and filter()Python supports list comprehensions which are easier to read and are analogous in functionality as map() and filter(). This is one of the reasons why Guido van Rossum, the creator of Python felt that dropping map() and filter() was quite uncontroversial.An example to show  map() along with this equivalent list comprehension:>>> list_num = [1, 2, 3, 4, 5, 6] >>> def square_num(z): ...    return z*z ... >>> list(map(square_num, list_num)) [1, 4, 9, 16, 25, 36] >>> [square_num(z) for z in numbers] [1, 4, 9, 16, 25, 36]Though map() and list comprehension returns the same values but the list comprehension part is easier to read and understand.An example to show  filter() and its equivalent list comprehension:>>> def odd_num_check(z):       return bool(z % 2)   >>> list(filter(odd_num_check, num_list)) [1, 3, 5] >>> [z for z in numbers if odd_num_check(z)] [1, 3, 5]It is the same with filter()as it was with map(). The return values are the same but the list comprehension is easier to follow.List comprehensions are easier to read and beginners are able to catch it more intuitively.Though other programming language developers might argue to the fact but if you make use of list comprehensions during your coding interview, it is more likely to communicate your knowledge about the common functionalities to the recruiter.Debugging With breakpoint() instead of print() Debugging is an essential part of writing software and it shows your knowledge of Python tools which will be useful in developing quickly in your job in the long run. However, using print() to debug a small problem might be good initially but your code will become clumsy. On the other hand, if you use a debugger like breakpoint(), it will always act faster than print().If you’re using Python 3.7, you can simply call breakpoint() at the point in your code where you want to debug without the need of importing anything:# Complicated Code With Bugs ... ... ... breakpoint()Whenever you call breakpoint(), you will be put into The Python Debugger - pdb. However, if you’re using Python 3.6 or older, you can perform an explicit importing which will be exactly like calling breakpoint():import pdb; pdb.set_trace()In this example, you’re being put into the pdb by the pdb.set_trace().  Since it’s a bit difficult to remember, it is recommended to use breakpoint() whenever a debugger is needed. There are also other debuggers that you can try. Getting used to debuggers before your interview would be a great advantage but you can always come back to pdb since it’s a part of the Python Standard Library and is always available. Formatting Strings with the help of f-StringsIt can be confusing to know what type of string formatting should we use since Python consists of a number of different string formatting techniques. However, it is a good approach and is suggested to use Python’s f-strings during a coding interview for Python 3.6 or greater.Literal String Interpolation or f-strings is a powerful string formatting technique that is more readable, more concise, faster and less prone to error than other formatting techniques. It supports the string formatting mini-language which makes string interpolation simpler. You also have the option of adding new variables and Python expressions and they can be evaluated before run-time:>>> def name_and_age(name, age):       return f"My name is {name} and I'm {age / 10:.5f} years old."   >>> name_and_age("Alex", 21) My name is Alex and I'm 2.10000 years old.The f-string allows you to add the name Alex into the string and his corresponding age with the type of formatting you want in one single operation.Note that it is suggested to use Template Strings if the output consists of user-generated values.Sorting Complex Lists with sorted()There are a lot of interview questions that are mostly based on sorting and it is one of the most important concepts you should be clear about before you sit for a coding interview. However, it is always a better option to use sorted() unless you are asked to make your own sorting algorithm by the interviewer.Example code to illustrate simple uses of sorting like sorting numbers or strings:>>> sorted([6,5,3,7,2,4,1]) [1, 2, 3, 4, 5, 6, 7] >>> sorted(['IronMan', 'Batman', 'Thor', 'CaptainAmerica', 'DoctorStrange'], reverse=False) ['Batman', 'CaptainAmerica', 'DoctorStrange', 'IronMan', 'Thor']sorted() performs sorting in ascending order by default and also when the reverse argument is set to False. If you sorting complex data types, you might want to add a function which allows custom sorting rules:>>> animal_list = [ ...    {'type': 'bear', 'name': 'Stephan', 'age': 9}, ...    {'type': 'elephant', 'name': 'Devory', 'age': 5}, ...    {'type': 'jaguar', 'name': 'Moana', 'age': 7}, ... ] >>> sorted(animal_list, key=lambda animal: animal['age']) [     {'type': 'elephant', 'name': 'Devory', 'age': 5},     {'type': 'jaguar', 'name': 'Moana', 'age': 7},     {'type': 'bear, 'name': 'Stephan, 'age': 9}, ]You can easily sort a list of dictionaries using the lambda keyword. In the example above, the lambda returns each element’s age and the dictionary is sorted in ascending order by age.Effective Use of Data StructuresData Structures are one of the most important concepts you should know before getting into an interview and if you choose the perfect data structure during an interviewing context, it will certainly impact your performance. Python’s standard data structure implementations are incredibly powerful and give a lot of default functionalities which will surely be helpful in coding interviews.Storing Values with SetsMake use of sets instead of lists whenever you want to remove duplicate elements from an existing dataset.Consider a function random_word that always returns a random word from a set of words:>>> import random >>> words = "all the words in the world".split() >>> def random_word():       return random.choice(words)In the example above, you need to call random_word repeatedly to get 1000 random selections and then return a data structure that will contain every unique word.Let us look at three approaches to execute this – two suboptimal approaches and one good approach.Bad Approach An example to store values in a list and then convert into a set:>>> def unique_words():       words = []       for _ in range(1000):           words.append(random_word())       return set(words) >>> unique_words() {'planet', 'earth', 'to', 'words'}In this example, creating a list and then converting it into a set is an unnecessary approach. Interviewers notice this type of design and questions about it generally.Worse ApproachYou can store values into a list to avoid the conversion from list to a set. You can then check for the uniqueness by comparing new values with all current elements in the list:>>> def unique_words():       words = []       for _ in range(1000):     word = unique_words()     if word not in words:     words.append(word)       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach is much worse than the previous one since you have to compare every word to every other word already present in the list. In simple terms, the time complexity is much greater in this case than the earlier example.Good ApproachIn this example, you can skip the lists and use sets altogether from the beginning:>>> def unique_words():       words = set()       for _ in range(1000):           words.add(random_word())       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach differs from the second approach as the storing of elements in this approach allows near-constant-time-checks whether a value is present in the set or not whereas linear time-lookups were required when lists were used. The time complexity for this approach is O(N) which is much better than the second approach whose time complexity grew at the rate of O(N²).Saving Memory with GeneratorsThough lists comprehensions are convenient tools, it may lead to excessive use of memory.Consider a situation where you need to find the sum of the first 1000 squares starting with 1 using list comprehensions:>>> sum([z * z for z in range(1, 1001)])333833500Your solution returns the correct answer by making a list of every perfect square and then sums the values. However, the interviewer asks you to increase the number of perfect squares. Initially, your program might work well but it will gradually slow down and the process will be changed completely.  However, you can resolve this memory issue just by replacing the brackets with parentheses:>>> sum((z * z for z in range(1, 1001)))333833500When you make the change from brackets to parentheses, the list comprehension changes to generator expressions. It returns a generator object. The object calculates the next value only when asked. Generators are mainly used on massive sequences of data and in situations when you want to retrieve data from a sequence but don’t want to access all of it at the same time.Defining Default Values in Dictionaries with .get() and .setdefault()Adding, modifying or retrieving an item from a dictionary is one of the most primitive tasks of programming and it is easy to perform with Python functionalities. However, developers often check explicitly for values even its not necessary.Consider a situation where a dictionary named shepherd exists and you want to get that cowboy’s name by explicitly checking for the key with a conditional:>>> shepherd = {'age': 20, 'sheep': 'yorkie', 'size_of_hat': 'large'} >>> if 'name' in shepherd:       name = shepherd['name']     else:       name = 'The Man with No Name'   >>> nameIn this example, the key name is searched in the dictionary and the corresponding value is returned otherwise a default value is returned.You can use .get() in a single line instead of checking keys explicitly:>>> name = shepherd.get('name', 'The Man with No Name')The get() performs the same operation as the first approach does, but they are now handled automatically. However, .get() function does not help in situations where you need to update the dictionary with a default value while still accessing the same key. In such a case, you again need to use explicit checking:>>> if 'name' not in shepherd:       shepherd['name'] = 'The Man with No Name'   >>> name = shepherd['name']However, Python still offers a more elegant way of performing this approach using .setdefault():>>> name = shepherd.setdefault('name', 'The Man with No Name')The .setdefault() function performs the same operation as the previous approach did. If name exists in shepherd, it returns a value otherwise it sets shepherd[‘name’]  to The Man with No Name and returns a new value.Taking Advantage of the Python Standard LibraryPython’s functionalities are powerful on its own and all the things can be accessed just by using the import statement. If you know how to make good use of the standard library, it will boost your coding interview skills.How to handle missing dictionaries?You can use .get() and .setdefault() when you want to set a default for a single key. However, there will be situations where you will need to set a default value for all possible unset keys, especially during the context of a coding interview.Consider you have a  group of students and your task is to keep track of their grades on assignments. The input value is a tuple with student_name and grade. You want to look upon all the grades for a single student without iterating over the whole list. An example to store grade data using a dictionary:>>> grades_of_students = {} >>> grades = [       ('alex', 89),       ('bob', 95),       ('charles', 81),       ('alex', 94),       ] >>> for name, grade in grades:       if name not in grades_of_student:           grades_of_student[name] = []       grades_of_student[name].append(grade) >>> student_grades{'alex': [89, 94], 'bob': [95], 'charles': [81]}In the example above, you iterate over the list and check if the names are already present in the dictionary or not. If it isn’t, then you add them to the dictionary with an empty list and then append their actual grades to the student’s list of grades.However, the previous approach is good but there is a cleaner approach for such cases using the defaultdict:>>> from collections import defaultdict >>> student_grades = defaultdict(list) >>> for name, grade in grades:       student_grades[name].append(grade)In this approach, a defaultdict is created that uses the list() with no arguments. The list()returns an empty list. defaultdict calls the list() if the name does not exist and then appends the grade.Using the defaultdict, you can handle all the common default values at once and need not worry about default values at the key level. Moreover, it generates a much cleaner application code.How to Count Hashable Objects?Pretend you have a long string of words with no punctuation or capital letters and you are asked to count the number of the appearance of each word. In this case, you can use collections.Counter that uses 0 as the default value for any missing element and makes it easier and cleaner to count the occurrence of different objects:>>> from collections import Counter >>> words = "if I am there but if \ ... he was not there then I was not".split() >>> counts = Counter(words) >>> countsCounter({'if': 2, 'there': 2, 'was': 1, 'not': 2, 'but': 1, ‘I’: 2, ‘am’: 1, }When the list is passed to Counter, it stores each word and also the number of occurrences of that word in the list.If you want to know the two most common words in a list of strings like above, you can use .most_common() which simply returns the n most frequently inputs by count:>>> counts.most_common(2)[('if': 2), ('there': 2), ('not': 2), (‘I’: 2)] How to Access Common String Groups?If you want to check whether ‘A’ > ‘a’ or not, you have to do it using the ASCII chart. The answer will be false since the ASCII value for A is 65 and a is 97, which is clearly greater. However, it would be a difficult task to remember the ASCII code when it comes to lowercase and uppercase ASCII characters and also this method is a bit clumsy. You can use the much easier and convenient constants which are a part of the string module. An example to check whether all the characters in a string are uppercase or not:>>> import string >>> def check_if_upper(word):       for letter in word:           if letter not in string.ascii_uppercase:               return False       return True   >>> check_if_upper('Thanks Alex') False >>> check_if_upper('ROFL') TrueThe function check_if_upper iterates over the letters in words, and checks whether the letters are part of string.ascii_uppercase. It is set to the literal ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.There are a number of string constants that are frequently used for referencing string values that are easy to read and use. Some of which are as follows:string.ascii_lettersstring.ascii_upercasestring.ascii_lowercasestring.ascii_digitsstring.ascii_hexdigitsstring.ascii_octdigitsstring.ascii_punctuationstring.ascii_printablestring.ascii_whitespaceConclusionClearing interview with confidence and panache is a skill. You might be a good programmer but it’s only a small part of the picture. You might fail to clear a few interviews, but if you follow a good process, it will certainly help you in the long run. Being enthusiastic is an important factor that will have a huge impact on your interview results. In addition to that is practice. Practice always helps. Brush up on all the common interview concepts and then head off to practicing different interview questions. Interviewers also help during interviews if you can communicate properly and interact. Ask questions and always talk through a brute-force and optimized solution.Let us now sum up what we have learned in this article so far:To use enumerate() to iterate over both indices and values.To debug problematic code with breakpoint().To format strings effectively with f-strings.To sort lists with custom arguments.To use generators instead of list comprehensions to save memory.To define default values when looking up dictionary keys.To count hashable objects with collections.Counter class.Hope you have learned about most of the powerful Python’s built-in functions, data structures, and standard library packages that will help you in writing better, faster and cleaner code. Though there are a lot of other things to learn about the language, join our Python certification course to gain more skills and knowledge.
How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries
Priyankur
Rated 4.5/5 based on 14 customer reviews

How to Stand Out in a Python Coding Interview - Functions, Data Structures & Libraries

Any coding interview is a test which primarily focuses on your technical skills and algorithm knowledge. However, if you want to stand out among the hundreds of interviewees, you should know how to use the common functionalities of Python in a convenient manner.The type of interview you might face can be a remote coding challenge, a whiteboard challenge or a full day on-site interview. So if you can prove your coding skills at that moment, the job letter will reach you in no time. You may go through some of the top Python interview questions and answers provided by experts which are divided into three levels- beginner, intermediate and advanced. A thorough practice of these questions and answers on Python will definitely help you achieve your dream job as a Python Developer, Full Stack engineer, and other top profiles.A Python coding interview is basically a technical interview. They are not just about solving problems, they are more about how technically sound you are and how you can write clean productive Python code. This will show your depth of knowledge about Python and how you can use Python’s built-in functions and libraries to implement your code. Go through our Python Tutorials to learn more about  concepts related to Python. Let us look into some of the built-in functions provided by Python and how to select the correct one, learn about the effective use of data structures, how standard libraries in Python can be utilized and so on.How to Select the Correct Built-in Function?Python’s library of built-in functions is small as compared to the standard library. The built-in functions are always available and are not needed to be imported. It is suggested to learn each function before sitting for the interview. Till then, let us learn a few built-in functions and how to use them and also what alternatives can be used.Perform iteration with enumerate() instead of range() Consider a situation during a coding interview: You have a list of elements and you have to iterate over the list with the access to both the indices and values. To differentiate between iteration with enumerate()  and iteration with range(), let us take a look at the classic coding interview question FizzBuzz. It can be solved by iterating over both indices and values. You will be given a list of integers and your task will be as follows:Replace all integers that are evenly distributed by 3 with “fizz”.Replace all integers divisible by 5 with “buzz”.Replace all integers divisible by 3 and 5 with “fizzbuzz”.Developers make use of range() in these situations which can access the elements by index:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i in range(len(list_num)):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz'   >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']Though range() can be used in a lot of iterative methods, it is better to use enumerate() in this case since it can access the element’s index and value at the same time:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i,num in enumerate(list_num):       if list_num[i] % 3 == 0 and list_num[i] % 5 == 0:           list_num[i] = 'fizzbuzz'       elif list_num[i] % 3 == 0:           list_num[i] = 'fizz'       elif list_num[i] % 5 == 0:           list_num[i] = 'buzz' >>> list_num ['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']The enumerate() function returns a counter and the element value for each element. The counter is set to 0 by default which is also the element’s index.  However, if you are not willing to start your counter from 0, you can set an offset using the start parameter:>>> list_num = [30, 29, 10, 65, 95, 99] >>> for i, num in enumerate(list_num, start=11):       print(i, num) 11 30 12 29 13 10 14 65 14 95 16 99You can access all of the same elements using the start parameter. However, the count will start from the specified integer value.Using List Comprehensions in place of map() and filter()Python supports list comprehensions which are easier to read and are analogous in functionality as map() and filter(). This is one of the reasons why Guido van Rossum, the creator of Python felt that dropping map() and filter() was quite uncontroversial.An example to show  map() along with this equivalent list comprehension:>>> list_num = [1, 2, 3, 4, 5, 6] >>> def square_num(z): ...    return z*z ... >>> list(map(square_num, list_num)) [1, 4, 9, 16, 25, 36] >>> [square_num(z) for z in numbers] [1, 4, 9, 16, 25, 36]Though map() and list comprehension returns the same values but the list comprehension part is easier to read and understand.An example to show  filter() and its equivalent list comprehension:>>> def odd_num_check(z):       return bool(z % 2)   >>> list(filter(odd_num_check, num_list)) [1, 3, 5] >>> [z for z in numbers if odd_num_check(z)] [1, 3, 5]It is the same with filter()as it was with map(). The return values are the same but the list comprehension is easier to follow.List comprehensions are easier to read and beginners are able to catch it more intuitively.Though other programming language developers might argue to the fact but if you make use of list comprehensions during your coding interview, it is more likely to communicate your knowledge about the common functionalities to the recruiter.Debugging With breakpoint() instead of print() Debugging is an essential part of writing software and it shows your knowledge of Python tools which will be useful in developing quickly in your job in the long run. However, using print() to debug a small problem might be good initially but your code will become clumsy. On the other hand, if you use a debugger like breakpoint(), it will always act faster than print().If you’re using Python 3.7, you can simply call breakpoint() at the point in your code where you want to debug without the need of importing anything:# Complicated Code With Bugs ... ... ... breakpoint()Whenever you call breakpoint(), you will be put into The Python Debugger - pdb. However, if you’re using Python 3.6 or older, you can perform an explicit importing which will be exactly like calling breakpoint():import pdb; pdb.set_trace()In this example, you’re being put into the pdb by the pdb.set_trace().  Since it’s a bit difficult to remember, it is recommended to use breakpoint() whenever a debugger is needed. There are also other debuggers that you can try. Getting used to debuggers before your interview would be a great advantage but you can always come back to pdb since it’s a part of the Python Standard Library and is always available. Formatting Strings with the help of f-StringsIt can be confusing to know what type of string formatting should we use since Python consists of a number of different string formatting techniques. However, it is a good approach and is suggested to use Python’s f-strings during a coding interview for Python 3.6 or greater.Literal String Interpolation or f-strings is a powerful string formatting technique that is more readable, more concise, faster and less prone to error than other formatting techniques. It supports the string formatting mini-language which makes string interpolation simpler. You also have the option of adding new variables and Python expressions and they can be evaluated before run-time:>>> def name_and_age(name, age):       return f"My name is {name} and I'm {age / 10:.5f} years old."   >>> name_and_age("Alex", 21) My name is Alex and I'm 2.10000 years old.The f-string allows you to add the name Alex into the string and his corresponding age with the type of formatting you want in one single operation.Note that it is suggested to use Template Strings if the output consists of user-generated values.Sorting Complex Lists with sorted()There are a lot of interview questions that are mostly based on sorting and it is one of the most important concepts you should be clear about before you sit for a coding interview. However, it is always a better option to use sorted() unless you are asked to make your own sorting algorithm by the interviewer.Example code to illustrate simple uses of sorting like sorting numbers or strings:>>> sorted([6,5,3,7,2,4,1]) [1, 2, 3, 4, 5, 6, 7] >>> sorted(['IronMan', 'Batman', 'Thor', 'CaptainAmerica', 'DoctorStrange'], reverse=False) ['Batman', 'CaptainAmerica', 'DoctorStrange', 'IronMan', 'Thor']sorted() performs sorting in ascending order by default and also when the reverse argument is set to False. If you sorting complex data types, you might want to add a function which allows custom sorting rules:>>> animal_list = [ ...    {'type': 'bear', 'name': 'Stephan', 'age': 9}, ...    {'type': 'elephant', 'name': 'Devory', 'age': 5}, ...    {'type': 'jaguar', 'name': 'Moana', 'age': 7}, ... ] >>> sorted(animal_list, key=lambda animal: animal['age']) [     {'type': 'elephant', 'name': 'Devory', 'age': 5},     {'type': 'jaguar', 'name': 'Moana', 'age': 7},     {'type': 'bear, 'name': 'Stephan, 'age': 9}, ]You can easily sort a list of dictionaries using the lambda keyword. In the example above, the lambda returns each element’s age and the dictionary is sorted in ascending order by age.Effective Use of Data StructuresData Structures are one of the most important concepts you should know before getting into an interview and if you choose the perfect data structure during an interviewing context, it will certainly impact your performance. Python’s standard data structure implementations are incredibly powerful and give a lot of default functionalities which will surely be helpful in coding interviews.Storing Values with SetsMake use of sets instead of lists whenever you want to remove duplicate elements from an existing dataset.Consider a function random_word that always returns a random word from a set of words:>>> import random >>> words = "all the words in the world".split() >>> def random_word():       return random.choice(words)In the example above, you need to call random_word repeatedly to get 1000 random selections and then return a data structure that will contain every unique word.Let us look at three approaches to execute this – two suboptimal approaches and one good approach.Bad Approach An example to store values in a list and then convert into a set:>>> def unique_words():       words = []       for _ in range(1000):           words.append(random_word())       return set(words) >>> unique_words() {'planet', 'earth', 'to', 'words'}In this example, creating a list and then converting it into a set is an unnecessary approach. Interviewers notice this type of design and questions about it generally.Worse ApproachYou can store values into a list to avoid the conversion from list to a set. You can then check for the uniqueness by comparing new values with all current elements in the list:>>> def unique_words():       words = []       for _ in range(1000):     word = unique_words()     if word not in words:     words.append(word)       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach is much worse than the previous one since you have to compare every word to every other word already present in the list. In simple terms, the time complexity is much greater in this case than the earlier example.Good ApproachIn this example, you can skip the lists and use sets altogether from the beginning:>>> def unique_words():       words = set()       for _ in range(1000):           words.add(random_word())       return words >>> unique_words() {'planet', 'earth', 'to', 'words'}This approach differs from the second approach as the storing of elements in this approach allows near-constant-time-checks whether a value is present in the set or not whereas linear time-lookups were required when lists were used. The time complexity for this approach is O(N) which is much better than the second approach whose time complexity grew at the rate of O(N²).Saving Memory with GeneratorsThough lists comprehensions are convenient tools, it may lead to excessive use of memory.Consider a situation where you need to find the sum of the first 1000 squares starting with 1 using list comprehensions:>>> sum([z * z for z in range(1, 1001)])333833500Your solution returns the correct answer by making a list of every perfect square and then sums the values. However, the interviewer asks you to increase the number of perfect squares. Initially, your program might work well but it will gradually slow down and the process will be changed completely.  However, you can resolve this memory issue just by replacing the brackets with parentheses:>>> sum((z * z for z in range(1, 1001)))333833500When you make the change from brackets to parentheses, the list comprehension changes to generator expressions. It returns a generator object. The object calculates the next value only when asked. Generators are mainly used on massive sequences of data and in situations when you want to retrieve data from a sequence but don’t want to access all of it at the same time.Defining Default Values in Dictionaries with .get() and .setdefault()Adding, modifying or retrieving an item from a dictionary is one of the most primitive tasks of programming and it is easy to perform with Python functionalities. However, developers often check explicitly for values even its not necessary.Consider a situation where a dictionary named shepherd exists and you want to get that cowboy’s name by explicitly checking for the key with a conditional:>>> shepherd = {'age': 20, 'sheep': 'yorkie', 'size_of_hat': 'large'} >>> if 'name' in shepherd:       name = shepherd['name']     else:       name = 'The Man with No Name'   >>> nameIn this example, the key name is searched in the dictionary and the corresponding value is returned otherwise a default value is returned.You can use .get() in a single line instead of checking keys explicitly:>>> name = shepherd.get('name', 'The Man with No Name')The get() performs the same operation as the first approach does, but they are now handled automatically. However, .get() function does not help in situations where you need to update the dictionary with a default value while still accessing the same key. In such a case, you again need to use explicit checking:>>> if 'name' not in shepherd:       shepherd['name'] = 'The Man with No Name'   >>> name = shepherd['name']However, Python still offers a more elegant way of performing this approach using .setdefault():>>> name = shepherd.setdefault('name', 'The Man with No Name')The .setdefault() function performs the same operation as the previous approach did. If name exists in shepherd, it returns a value otherwise it sets shepherd[‘name’]  to The Man with No Name and returns a new value.Taking Advantage of the Python Standard LibraryPython’s functionalities are powerful on its own and all the things can be accessed just by using the import statement. If you know how to make good use of the standard library, it will boost your coding interview skills.How to handle missing dictionaries?You can use .get() and .setdefault() when you want to set a default for a single key. However, there will be situations where you will need to set a default value for all possible unset keys, especially during the context of a coding interview.Consider you have a  group of students and your task is to keep track of their grades on assignments. The input value is a tuple with student_name and grade. You want to look upon all the grades for a single student without iterating over the whole list. An example to store grade data using a dictionary:>>> grades_of_students = {} >>> grades = [       ('alex', 89),       ('bob', 95),       ('charles', 81),       ('alex', 94),       ] >>> for name, grade in grades:       if name not in grades_of_student:           grades_of_student[name] = []       grades_of_student[name].append(grade) >>> student_grades{'alex': [89, 94], 'bob': [95], 'charles': [81]}In the example above, you iterate over the list and check if the names are already present in the dictionary or not. If it isn’t, then you add them to the dictionary with an empty list and then append their actual grades to the student’s list of grades.However, the previous approach is good but there is a cleaner approach for such cases using the defaultdict:>>> from collections import defaultdict >>> student_grades = defaultdict(list) >>> for name, grade in grades:       student_grades[name].append(grade)In this approach, a defaultdict is created that uses the list() with no arguments. The list()returns an empty list. defaultdict calls the list() if the name does not exist and then appends the grade.Using the defaultdict, you can handle all the common default values at once and need not worry about default values at the key level. Moreover, it generates a much cleaner application code.How to Count Hashable Objects?Pretend you have a long string of words with no punctuation or capital letters and you are asked to count the number of the appearance of each word. In this case, you can use collections.Counter that uses 0 as the default value for any missing element and makes it easier and cleaner to count the occurrence of different objects:>>> from collections import Counter >>> words = "if I am there but if \ ... he was not there then I was not".split() >>> counts = Counter(words) >>> countsCounter({'if': 2, 'there': 2, 'was': 1, 'not': 2, 'but': 1, ‘I’: 2, ‘am’: 1, }When the list is passed to Counter, it stores each word and also the number of occurrences of that word in the list.If you want to know the two most common words in a list of strings like above, you can use .most_common() which simply returns the n most frequently inputs by count:>>> counts.most_common(2)[('if': 2), ('there': 2), ('not': 2), (‘I’: 2)] How to Access Common String Groups?If you want to check whether ‘A’ > ‘a’ or not, you have to do it using the ASCII chart. The answer will be false since the ASCII value for A is 65 and a is 97, which is clearly greater. However, it would be a difficult task to remember the ASCII code when it comes to lowercase and uppercase ASCII characters and also this method is a bit clumsy. You can use the much easier and convenient constants which are a part of the string module. An example to check whether all the characters in a string are uppercase or not:>>> import string >>> def check_if_upper(word):       for letter in word:           if letter not in string.ascii_uppercase:               return False       return True   >>> check_if_upper('Thanks Alex') False >>> check_if_upper('ROFL') TrueThe function check_if_upper iterates over the letters in words, and checks whether the letters are part of string.ascii_uppercase. It is set to the literal ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.There are a number of string constants that are frequently used for referencing string values that are easy to read and use. Some of which are as follows:string.ascii_lettersstring.ascii_upercasestring.ascii_lowercasestring.ascii_digitsstring.ascii_hexdigitsstring.ascii_octdigitsstring.ascii_punctuationstring.ascii_printablestring.ascii_whitespaceConclusionClearing interview with confidence and panache is a skill. You might be a good programmer but it’s only a small part of the picture. You might fail to clear a few interviews, but if you follow a good process, it will certainly help you in the long run. Being enthusiastic is an important factor that will have a huge impact on your interview results. In addition to that is practice. Practice always helps. Brush up on all the common interview concepts and then head off to practicing different interview questions. Interviewers also help during interviews if you can communicate properly and interact. Ask questions and always talk through a brute-force and optimized solution.Let us now sum up what we have learned in this article so far:To use enumerate() to iterate over both indices and values.To debug problematic code with breakpoint().To format strings effectively with f-strings.To sort lists with custom arguments.To use generators instead of list comprehensions to save memory.To define default values when looking up dictionary keys.To count hashable objects with collections.Counter class.Hope you have learned about most of the powerful Python’s built-in functions, data structures, and standard library packages that will help you in writing better, faster and cleaner code. Though there are a lot of other things to learn about the language, join our Python certification course to gain more skills and knowledge.
Rated 4.5/5 based on 14 customer reviews
5877
How to Stand Out in a Python Coding Interview - Fu...

Any coding interview is a test which primarily foc... Read More

How to use sorted() and sort() in Python

Whenever you visit a pharmacy and ask for a particular medicine, have you noticed something? It hardly takes any time for the pharmacist to find it among several medicines. This is because all the items are arranged in a certain fashion which helps them know the exact place to look for. They may be arranged in alphabetical order or according to their category such as ophthalmics or neuro or gastroenterology and so on. A proper arrangement not only saves time but also make operations simple and easy, hence sorting is essential.At some point or the other, every programmer needs to learn one of the most essential skills,  Sorting. Python sorting functions comprise of a lot of features to perform basic sorting or customize ordering according to the programmer’s needs.Basically, sorting is a technique that is used to arrange data in an increasing and decreasing fashion according to some linear relationship among the data elements. You can sort numbers, or names or records of any kind in any fashion according to your needs. Sorting techniques can be used to arrange a list of mail recipients in an alphabetical manner.There are a number of sorting algorithms in Python starting from Bubble Sort, Insertion Sort, Quick Sort, Merge Sort, Selection Sort and so on. In this article we will look into how to use sorted() and sort() in Python. To learn more about other concepts of Python, go through our Python Tutorials.What is the need for Sorting?In simple terms, sorting means arranging data systematically. If the data you want to work with  is not sorted you will face problems in finding your desired element.The main advantages of sorting elements in Python are:When you work with sorting modules, you will get to know about a large number of language components.Sorting Algorithms provide an abstract way of learning about the accuracy of your program without worrying about system developments or dependencies.It will help you in understanding the program complexity and speed and how to increase the efficiency.How to order values using sorted()?sorted() is a built-in function that accepts an iterable and returns the sorted values in ascending order by default which contains the iterable items.Sorting Numbers using sorted()Let us define a list of integers called num_list and pass it as an argument to sorted():>>> num_list = [4, 10, 1, 7] >>> sorted(num_list) [1, 4, 7, 10] >>> num_list [4, 10, 1, 7]Some of the insights we gain from the code above are:sorted() is a built-in function found in the Python Standard Library. It cannot be defined.sorted() orders the values in num_list in ascending order by default, i.e. smallest to largest.The original values of num_list are not changed.sorted() being called, returns an ordered list of values.Since sorted() function returns the list in order, we can assign the returned list to another variable:>>> num_list = [4, 10, 1, 7] >>> sorted_list = sorted(num_list) >>> sorted_list [1, 4, 7, 10] >>> num_list [4, 10, 1, 7]A new variable sorted_list is created which holds the output of sorted().You can also use sorted() to sort tuples and sets just like numbers:>>> tuples = (4, 10, 1, 7) >>> sets = {10, 5, 10, 0, 2} >>> sorted_tuples = sorted(numbers_tuple) >>> sorted_sets = sorted(numbers_set) >>> sorted_tuples [1, 4, 7, 10] >>> sorted_sets [0, 2, 5, 10]The definition of sorted() states that it will return a new list whatever the input may be. So even if the input variables are tuples and sets, sorted() always returns a list.You can also perform type casting in cases where you need to match the returned object with the input type:>>> tuples = (4, 10, 1, 7) >>> sets = {10, 5, 10, 0, 2} >>> sorted_tuples = sorted(numbers_tuple) >>> sorted_sets = sorted(numbers_set) >>> sorted_tuples [1, 4, 7, 10] >>> sorted_sets [0, 2, 5, 10] >>> tuples(sorted_tuples) (1, 4, 7, 10) >>> sets(sorted_sets) {0, 2, 5, 10}In the code above, you can see the sorted_tuples when cast to tuples is retained in an ordered manner whereas sorted_sets when casted does not return an order list since it is unordered by definition.Sorting Strings using sorted()Sorting of strings is just like sorting tuples and sets. sorted() iterates across each character of the input and returns a string order.An example of sorting str type using sorted():>>> num_string = '98765' >>> char_string = 'sorting is fun' >>> sorted_num_string = sorted(num_string) >>> sorted_char_string = sorted(char_string) >>> sorted_num_string ['5', '6', '7', '8', '9'] >>> sorted_char_string ['', '','f', 'g', 'i', 'i', 'n', 'n', 'o', 'r', 's', 's', 't','u']The str is treated as a list and sorted() iterates through each character including spaces.You can use .split() to change the behavior and clean the output and .join() to rejoin them together:>>> string = 'sorting is fun' >>> sorted_string = sorted(string.split()) >>> sorted_string ['fun', 'is', 'sorting'] >>> ' '.join(sorted_string) 'fun is sorting'The actual string is converted into a list of words using .split() and then it is sorted with sorted() and then again joined together using .join().How to use sorted() with a reverse Argument?The syntax of the sorted() function is sorted(iterable, /, *, key=None, reverse=False).The built-in function sorted() comprises of three parameters:iterable — Required. A sequence such as string, tuple or list and collection such as set or dictionary.key — Optional. A function that serves as a key or to customize the sort order. The argument is set to None by default.reverse — Optional. A boolean flag that reverses the order of sorting. If True, the sorted list is reversed. The default argument is False.reverse is an optional keyword argument that changes the sorting order according to the Boolean value assigned to it. The default value is False, which performs sorting in ascending order. However, if the value is given as True, descending sort occurs:>>> name_list = ['Markian', 'Alex', 'Suzzane', 'Harleen'] >>> sorted(name_list) ['Alex', 'Harleen', 'Markian', 'Suzzane'] >>> sorted(name_list, reverse=True) ['Suzzane', 'Markian', 'Harleen', 'Alex']In the example above, the sorting is done on the basis of the first alphabet. However, when sorted() encounters the reverse keyword with a True argument, the output is reversed.Another example to understand the behavior of the reverse keyword:>>> case_sensitive_names = ['Markian', 'alex', 'Suzzane', 'harleen'] >>> sorted(case_sensitive_names, reverse=True) ['harleen', 'alex', 'Suzzane', 'Markian'] >>> values_to_sort = [False, 1, 'A' == 'B', 1 >> sorted(values_to_sort, reverse=True) [1, False, False, False] >>> num_list = [7, 10, 0, 4] >>> sorted(num_list, reverse=False) [0, 4, 7, 10]How to use sorted() with a key Argument?The keyword argument key accepts a function and this function determines the resulting order by implementing itself in each value of the list.An example to illustrate sorting of a list using the function len(), which returns the length of the string, and providing the key argument as len:>>> word = 'pencil' >>> len(word) 6 >>> word_list = ['cherry', 'donut', 'Michigan', 'transcipt'] >>> sorted(word_list, key=len) ['donut', 'cherry', 'Michigan', 'transcript']The len() function determines the length of each item in the list and returns the list in ascending order (shortest to longest).Let us sort the earlier example using key where the first alphabet with different case was considered for the order:>>> case_sensitive_names = ['Markian', 'alex', 'Suzzane', 'harleen'] >>> sorted(case_sensitive_names, reverse=True) ['Markian', 'Suzzane', 'alex', 'harleen'] >>> sorted(case_sensitive_names, key=str.lower) ['alex', 'harleen', 'Markian', 'Suzzane']The key cannot make any changes to the original values in the list. So the final output will be the original sorted elements.Though key is considered as one of the most powerful components of sorted(), it has a number of limitations.The first limitation is that key accepts only single argument functions.An example of a function addition that accepts two arguments:>>> def addition(a, b):       return a + b >>> number_to_add = [1, 3, 5] >>> sorted(number_to_add , key=addition) Traceback (most recent call last):   File "stdin", line 5, in     sorted(number_to_add, key=addition) TypeError: addition() missing 1 required positional argument: 'b'The program fails because whenever addition() is called during sorting, it receives only one element from the list at a time. The second argument is always missing.The second limitation is that the key function that is used must be able to handle all types of iterable values.An example to illustrate the second limitation:>>> cast_values = ['4', '5', '6', 'seven'] >>> sorted(cast_values, key=int) Traceback (most recent call last):   File "", line 1, in ValueError: invalid literal for int() with base 10: 'seven'The example above contains a list of numbers to be used by sorted() as strings. The key will try to convert the numbers to int. Each of the numbers represented as strings can be converted to int, but four cannot be. So a ValueError gets raised since four is not valid to cast into an int.Let us see an example to arrange an iterable by the last letter of each string:>>> def reverse(word):       return word[::-1] >>> words = ['cherry', 'cake', 'Michigan', 'transcript'] >>> sorted(words, key=reverse) ['cake', 'Michigan', 'transcript', 'cherry']The function reverse is defined to reverse the input string and then the function is used as the key argument. The slice syntax word[::-1] reverses the string and then the function reverse() takes all the elements one at a time and sorts the list according to the last alphabet.You can also use lambda function in the key argument instead of defining a regular function. A lambda is an anonymous function that does not have a name and executes just like normal functions. Lambda functions do not contain any statements.An example to show the previous code using a lambda function:>>> words = ['cherry', 'cake', 'Michigan', 'transcript'] >>> sorted(words, key = lambda x: x[::-1]) ['cake', 'Michigan', 'transcript', 'cherry']Here, the key is defined with lambda with no name and x is the argument. The slice syntax word[::-1] reverses each of the element and the reversed output is then used for sorting.An example to use key along with reverse argument:>>> words = ['cherry', 'cake', 'Michigan', 'transcript'] >>> sorted(words, key = lambda x: x[::-1], reverse = True) ['cherry', 'transcript', 'Michigan', 'cake']In this example, the order is reversed into a descending manner.Lambda functions can also be used to sort class objects according to their properties.An example to sort a group of students based on their grade in descending order:>>> from collections import namedtuple >>> Student = namedtuple('Student', 'name grade') >>> alex = Student('Alex', 95) >>> bob = Student('Bob', 87) >>> charlie = Student('Charlie', 91) >>> students = [alex, bob, charlie] >>> sorted(students, key=lambda x: getattr(x, 'grade'), reverse=True) [Student(name='Alex', grade=95), Student(name='Charlie', grade=91), Student(name='Bob', grade=87)]The namedtuple is used to produce classes with name and grade attributes. The lambda is used to get the grade property of each student and reverse is used to reverse the output into descending order so that the highest grades are arranged first.There are a lot of possible techniques to arrange elements using sorted() with key and reverse arguments. Lambda functions can also be helpful during sorting by making your code simple and clean.You can also use operator module functions like itemgetter() and attrgetter() to make your sorting program simpler and faster. The operator module is used to export a set of accessor functions in correspondence to the operators of Python.An example to illustrate operator module functions using key:>>> tuples = [      ('alex', 'B', 13),      ('bob', 'A', 12),      ('charles', 'B', 10),      ]>>> from operator import itemgetter>>> sorted(tuples, key=itemgetter(2))>>>[('charles', 'B', 10), ('bob', 'B', 12), ('alex', 'A', 13)]tuples is declared with the name, grade and age of three persons. The function itemgetter is imported from the module operator and then it is sorted by age and the output displayed in ascending order.How to order values using sort()?The .sort() which is quite similar to sorted() in naming has few differences than sorted(). The help documentation of Python will clear out the two critical differences between .sort() and sorted():>>> help(sorted) Help on built-in function sorted in module builtins: sorted(iterable, /, *, key=None, reverse=False)     Return a new list containing all items from the iterable in ascending order.     A custom key function can be supplied to customize the sort order, and the     reverse flag can be set to request the result in descending order. >>> help(list.sort) Help on method_descriptor: sort(self, /, *, key=None, reverse=False)     Stable sort *IN PLACE*.Firstly, .sort() is not a built-in function unlike sorted(). It is a method of list class and works only with lists. You cannot pass iterables to .sort().Secondly, .sort()  returns None and changes the values.Let us see the differences of code for .sort() and what impact it has on the code:>>> sort_numbers = [10, 2, 7, 3] >>> sort(sort_numbers) Traceback (most recent call last):   File "", line 1, in NameError: name 'sort' is not defined >>> sort_tuples = (10, 2, 7, 3) >>> sort_tuple.sort()>>> sort_tuples = (10, 2, 7, 3) >>> sort_tuple.sort() Traceback (most recent call last):   File "", line 1, in AttributeError: 'tuple' object has no attribute 'sort' >>> sorted_values = sort_numbers.sort() >>> print(sorted_values) None >>> sorted_values = sort_numbers.sort() >>> print(sorted_values)int(sort_numbers) [1, 2, 5, 6]The code above highlights some operational differences between .sort() and sorted():When any assignment is done to a new variable, it returns a None type. This is because .sort() function has no ordered output. The original order of sort_numbers is not maintained and is changed in place..sort() also contains the key and reverse optional keyword arguments just like sorted() which produces the same functionality.An example of .sort() using lambda to sort a list of phrases by the first letter of the third word:>>> sort_phrases = ['welcome to python',       'python is fun',       'python is easy'       ] >>> sort_phrases.sort(key=lambda x: x.split()[2][1], reverse=False) >>> sort_phrases ['python is easy', 'python is fun', 'welcome to python']Here, lambda is used to split each phrase into a list of words and then find the second letter of the third element for each phrase.Disadvantages of  Python SortingPython has some limitations when you try to sort values besides integers.Non-Comparable Data TypesYou cannot use sort data types that are different from each other. Python raises an error when sorted() is used on non-comparable data.An example to illustrate sorting of values of different data types:>>> mixed_values = [None, 5] >>> sorted(mixed_values) Traceback (most recent call last):   File "", line 1, in TypeError: '
Rated 4.5/5 based on 12 customer reviews
8667
How to use sorted() and sort() in Python

Whenever you visit a pharmacy and ask for a partic... Read More

How to Round Numbers in Python

While you are dealing with data, sometimes you may come across a biased dataset. In statistics, bias is whereby the expected value of the results differs from the true underlying quantitative parameter being estimated. Working with such data can be dangerous and can lead you to incorrect conclusions. To learn more about various other concepts of Python, go through our  Python Tutorials.There are many types of biases such as selection bias, reporting bias, sampling bias and so on. Similarly, rounding bias is related to numeric data. In this article we will see:Why is it important to know the ways to round numbersHow to use various strategies to round numbersHow data is affected by rounding itHow to use NumPy arrays and Pandas DataFrames to round numbersLet us first learn about Python’s built-in rounding process.About Python’s Built-in round() FunctionPython offers a built-in round() function which rounds off a number to the given number of digits and makes rounding of numbers easier. The function round() accepts two numeric arguments, n and n digits and then returns the number n after rounding it to ndigits. If the number of digits are not provided for round off, the function rounds off the number n to the nearest integer.Suppose, you want to round off a number, say 4.5. It will be rounded to the nearest whole number which is 5. However, the number 4.74 will be rounded to one decimal place to give 4.7.It is important to quickly and readily round numbers while you are working with floats which have many decimal places. The inbuilt Python function round() makes it simple and easy.Syntaxround(number, number of digits)The parameters in the round() function are:number - number to be roundednumber of digits (Optional) - number of digits up to which the given number is to be rounded.The second parameter is optional. In case, if it is missing then round() function returns:For an integer, 12, it rounds off to 12For a decimal number, if the last digit after the decimal point is >=5 it will round off to the next whole number, and if =5 print(round(5.476, 2))     # when the (ndigit+1)th digit is  1 print(round("x", 2)) TypeError: type str doesn't define __round__ methodAnother example,print(round(1.5)) print(round(2)) print(round(2.5))The output will be:2 2 2The function round() rounds 1.5 up to 2, and 2.5 down to 2. This is not a bug, the round() function behaves this way. In this article you will learn a few other ways to round a number. Let us look at the variety of methods to round a number.Diverse Methods for RoundingThere are many ways to round a number with its own advantages and disadvantages. Here we will learn some of the techniques to rounding a number.TruncationTruncation, as the name means to shorten things. It is one of the simplest methods to round a number which involves truncating a number to a given number of digits. In this method, each digit after a given position is replaced with 0. Let us look into some examples.ValueTruncated ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34The truncate() function can be used for positive as well as negative numbers:>>> truncate(19.5) 19.0 >>> truncate(-2.852, 1) -2.8 >>> truncate(2.825, 2) 2.82The truncate() function can also be used to truncate digits towards the left of the decimal point by passing a negative number.>>> truncate(235.7, -1) 230.0 >>> truncate(-1936.37, -3) -1000.0When a positive number is truncated, we are basically rounding it down. Similarly, when we truncate a negative number, the number is rounded up. Let us look at the various rounding methods.Rounding UpThere is another strategy called “rounding up” where a number is rounded up to a specified number of digits. For example:ValueRound Up ToResult12.345Tens place2018.345Ones place1918.345Tenths place18.418.345Hundredths place18.35The term ceiling is used in mathematics to explain the nearest integer which is greater than or equal to a particular given number. In Python, for “rounding up” we use two functions namely,ceil() function, andmath() functionA non-integer number lies between two consecutive integers. For example, considering a number 5.2, this will lie between 4 and 5. Here, ceiling is the higher endpoint of the interval, whereas floor is the lower one. Therefore, ceiling of 5.2 is 5, and floor of 5.2 is 4. However, the ceiling of 5 is 5.In Python, the function to implement the ceiling function is the math.ceil() function. It always returns the closest integer which is greater than or equal to its input.>>> import math >>> math.ceil(5.2) 6 >>> math.ceil(5) 5 >>> math.ceil(-0.5) 0If you notice you will see that the ceiling of -0.5 is 0, and not -1.Let us look into a short code to implement the “rounding up” strategy using round_up() function:def round_up(n, decimals=0):     multiplier = 10 ** decimals     return math.ceil(n * multiplier) / multiplierLet’s look at how round_up() function works with various inputs:>>> round_up(3.1) 4.0 >>> round_up(3.23, 1) 3.3 >>> round_up(3.543, 2) 3.55You can pass negative values  to decimals, just like we did in truncation.>>> round_up(32.45, -1) 40.0 >>> round_up(3352, -2) 3400You can follow the diagram below to understand round up and round down. Round up to the right and down to the left.Rounding up always rounds a number to the right on the number line, and rounding down always rounds a number to the left on the number line.Rounding DownSimilar to rounding up we have another strategy called rounding down whereValueRounded Down ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34In Python, rounding down can be implemented using a similar algorithm as we truncate or round up. Firstly you will have to shift the decimal point and then round an integer. Lastly shift the decimal point back.math.ceil() is used to round up to the ceiling of the number once the decimal point is shifted. For “rounding down” we first need to round the floor of the number once the decimal point is shifted.>>> math.floor(1.2) 1 >>> math.floor(-0.5) -1Here’s the definition of round_down():def round_down(n, decimals=0):     multiplier = 10 ** decimals return math.floor(n * multiplier) / multiplierThis is quite similar to round_up() function. Here we are using math.floor() instead of math.ceil().>>> round_down(1.5) 1 >>> round_down(1.48, 1) 1.4 >>> round_down(-0.5) -1Rounding a number up or down has extreme effects in a large dataset. After rounding up or down, you can actually remove a lot of precision as well as alter computations.Rounding Half UpThe “rounding half up” strategy rounds every number to the nearest number with the specified precision, and breaks ties by rounding up. Here are some examples:ValueRound Half Up ToResult19.825Tens place1019.825Ones place2019.825Tenths place19.819.825Hundredths place19.83In Python, rounding half up strategy can be implemented by shifting the decimal point to the right by the desired number of places. In this case you will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5.You can add 0.5 to the value which is shifted and then round it down with the math.floor() function.def round_half_up(n, decimals=0):     multiplier = 10 ** decimals return math.floor(n*multiplier + 0.5) / multiplierIf you notice you might see that round_half_up() looks similar to round_down. The only difference is to add 0.5 after shifting the decimal point so that the result of rounding down matches with the expected value.>>> round_half_up(19.23, 1) 19.2 >>> round_half_up(19.28, 1) 19.3 >>> round_half_up(19.25, 1) 19.3Rounding Half DownIn this method of rounding, it rounds to the nearest number similarly like “rounding half up” method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Here are some examples:ValueRound Half Down ToResult16.825Tens place1716.825Ones place1716.825Tenths place16.816.825Hundredths place16.82In Python, “rounding half down” strategy can be implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding:def round_half_down(n, decimals=0):     multiplier = 10 ** decimals return math.ceil(n*multiplier - 0.5) / multiplierLet us look into some test cases.>>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0 >>> round_half_down(2.25, 1) 2.2In general there are no bias for both round_half_up() and round_half_down(). However, rounding of data with more number of ties results in bias. Let us consider an example to understand better.>>> data = [-2.15, 1.45, 4.35, -12.75]Let us compute the mean of these numbers:>>> statistics.mean(data) -2.275Now let us compute the mean on the data after rounding to one decimal place with round_half_up() and round_half_down():>>> rhu_data = [round_half_up(n, 1) for n in data] >>> statistics.mean(rhu_data) -2.2249999999999996 >>> rhd_data = [round_half_down(n, 1) for n in data] >>> statistics.mean(rhd_data) -2.325The round_half_up() function results in a round towards positive infinity bias, and round_half_down() results in a round towards negative infinity bias.Rounding Half Away From ZeroIf you have noticed carefully while going through round_half_up() and round_half_down(), neither of the two is symmetric around zero:>>> round_half_up(1.5) 2.0 >>> round_half_up(-1.5) -1.0 >>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0In order to introduce symmetry, you can always round a tie away from zero. The table mentioned below illustrates it clearly:ValueRound Half Away From Zero ToResult16.25Tens place2016.25Ones place1616.25Tenths place16.3-16.25Tens place-20-16.25Ones place-16-16.25Tenths place-16.3The implementation of “rounding half away from zero” strategy on a number n is very simple. All you need to do is start as usual by shifting the decimal point to the right a given number of places and then notice the digit d immediately to the right of the decimal place in this new number. Here, there are four cases to consider:If n is positive and d >= 5, round upIf n is positive and d < 5, round downIf n is negative and d >= 5, round downIf n is negative and d < 5, round upAfter rounding as per the rules mentioned above, you can shift the decimal place back to the left.There is a question which might come to your mind - How do you handle situations where the number of positive and negative ties are drastically different? The answer to this question brings us full circle to the function that deceived us at the beginning of this article: Python’s built-in  round() function.Rounding Half To EvenThere is a way to mitigate rounding bias while you are rounding values in a dataset. You can simply round ties to the nearest even number at the desired precision. Let us look at some examples:ValueRound Half To Even ToResult16.255Tens place2016.255Ones place1616.255Tenths place16.216.255Hundredths place16.26To prove that round() really does round to even, let us try on a few different values:>>> round(4.5) 4 >>> round(3.5) 4 >>> round(1.75, 1) 1.8 >>> round(1.65, 1) 1.6The Decimal ClassThe  decimal module in Python is one of those features of the language which you might not be aware of if you have just started learning Python. Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – except from the decimal arithmetic specification. Some of the benefits of the decimal module are mentioned below -Exact decimal representation: 0.1 is actually 0.1, and 0.1 + 0.1 + 0.1 - 0.3 returns 0, as expected.Preservation of significant digits: When you add 1.50 and 2.30, the result is 3.80 with the trailing zero maintained to indicate significance.User-alterable precision: The default precision of the decimal module is twenty-eight digits, but this value can be altered by the user to match the problem at hand.Let us see how rounding works in the decimal module.>>> import decimal >>> decimal.getcontext() Context(     prec=28,     rounding=ROUND_HALF_EVEN,     Emin=-999999,     Emax=999999,     capitals=1,     clamp=0,     flags=[],     traps=[         InvalidOperation,         DivisionByZero,         Overflow     ] )The function decimal.getcontext() returns a context object which represents the default context of the decimal module. It also includes the default precision and the default rounding strategy.In the above example, you will see that the default rounding strategy for the decimal module is ROUND_HALF_EVEN. It allows to align with the built-in round() functionLet us create a new Decimal instance by passing a string containing the desired value and declare a number using the decimal module’s Decimal class.>>> from decimal import Decimal >>> Decimal("0.1") Decimal('0.1')You may create a Decimal instance from a floating-point number but in that case, a floating-point representation error will be introduced. For example, this is what happens when you create a Decimal instance from the floating-point number 0.1>>> Decimal(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625')You may create Decimal instances from strings containing the decimal numbers you need in order to maintain exact precision.Rounding a Decimal using the .quantize() method:>>> Decimal("1.85").quantize(Decimal("1.0")) Decimal('1.8')The Decimal("1.0") argument in .quantize() allows to determine the number of decimal places in order to round the number. As 1.0 has one decimal place, the number 1.85 rounds to a single decimal place. Rounding half to even is the default strategy, hence the result is 1.8.Decimal class:>>> Decimal("2.775").quantize(Decimal("1.00")) Decimal('2.78')Decimal module provides another benefit. After performing arithmetic the rounding is taken care of automatically and also the significant digits are preserved.>>> decimal.getcontext().prec = 2 >>> Decimal("2.23") + Decimal("1.12") Decimal('3.4')To change the default rounding strategy, you can set the decimal.getcontect().rounding property to any one of several  flags. The following table summarizes these flags and which rounding strategy they implement:FlagRounding Strategydecimal.ROUND_CEILINGRounding updecimal.ROUND_FLOORRounding downdecimal.ROUND_DOWNTruncationdecimal.ROUND_UPRounding away from zerodecimal.ROUND_HALF_UPRounding half away from zerodecimal.ROUND_HALF_DOWNRounding half towards zerodecimal.ROUND_HALF_EVENRounding half to evendecimal.ROUND_05UPRounding up and rounding towards zeroRounding NumPy ArraysIn Data Science and scientific computation, most of the times we store data as a  NumPy array. One of the most powerful features of NumPy is the use of  vectorization and broadcasting to apply operations to an entire array at once instead of one element at a time.Let’s generate some data by creating a 3×4 NumPy array of pseudo-random numbers:>>> import numpy as np >>> np.random.seed(444) >>> data = np.random.randn(3, 4) >>> data array([[ 0.35743992,  0.3775384 ,  1.38233789,  1.17554883],        [-0.9392757 , -1.14315015, -0.54243951, -0.54870808], [ 0.20851975, 0.21268956, 1.26802054, -0.80730293]])Here, first we seed the np.random module to reproduce the output easily. Then a 3×4 NumPy array of floating-point numbers is created with np.random.randn().Do not forget to install pip3 before executing the code mentioned above. If you are using  Anaconda you are good to go.To round all of the values in the data array, pass data as the argument to the  np.around() function. The desired number of decimal places is set with the decimals keyword argument. In this case, round half to even strategy is used similar to Python’s built-in round() function.To round the data in your array to integers, NumPy offers several options which are mentioned below:numpy.ceil()numpy.floor()numpy.trunc()numpy.rint()The np.ceil() function rounds every value in the array to the nearest integer greater than or equal to the original value:>>> np.ceil(data) array([[ 1.,  1.,  2.,  2.],        [-0., -1., -0., -0.], [ 1., 1., 2., -0.]])Look at the code carefully, we have a new number! Negative zero! Let us now take a look at Pandas library, widely used in Data Science with Python.Rounding Pandas Series and DataFramePandas has been a game-changer for data analytics and data science. The two main data structures in Pandas are Dataframe and Series. Dataframe works like an Excel spreadsheet whereas you can consider Series to be columns in a spreadsheet. Series.round() and DataFrame.round() methods. Let us look at an example.Do not forget to install pip3 before executing the code mentioned above. If you are using  Anaconda you are good to go.>>> import pandas as pd >>> # Re-seed np.random if you closed your REPL since the last example >>> np.random.seed(444) >>> series = pd.Series(np.random.randn(4)) >>> series 0    0.357440 1    0.377538 2    1.382338 3    1.175549 dtype: float64 >>> series.round(2) 0    0.36 1    0.38 2    1.38 3    1.18 dtype: float64 >>> df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"]) >>> df           A         B         C 0 -0.939276 -1.143150 -0.542440 1 -0.548708  0.208520  0.212690 2  1.268021 -0.807303 -3.303072 >>> df.round(3)        A      B      C 0 -0.939 -1.143 -0.542 1 -0.549  0.209  0.213 2  1.268 -0.807 -3.303 The DataFrame.round() method can also accept a dictionary or a Series, to specify a different precision for each column. For instance, the following examples show how to round the first column of df to one decimal place, the second to two, and the third to three decimal places: >>> # Specify column-by-column precision with a dictionary >>> df.round({"A": 1, "B": 2, "C": 3})      A     B      C 0 -0.9 -1.14 -0.542 1 -0.5  0.21  0.213 2  1.3 -0.81 -3.303 >>> # Specify column-by-column precision with a Series >>> decimals = pd.Series([1, 2, 3], index=["A", "B", "C"]) >>> df.round(decimals)      A     B      C 0 -0.9 -1.14 -0.542 1 -0.5  0.21  0.213 2  1.3 -0.81 -3.303 If you need more rounding flexibility, you can apply NumPy's floor(), ceil(), and print() functions to Pandas Series and DataFrame objects: >>> np.floor(df)      A    B    C 0 -1.0 -2.0 -1.0 1 -1.0  0.0  0.0 2  1.0 -1.0 -4.0 >>> np.ceil(df)      A    B    C 0 -0.0 -1.0 -0.0 1 -0.0  1.0  1.0 2  2.0 -0.0 -3.0 >>> np.rint(df)      A    B    C 0 -1.0 -1.0 -1.0 1 -1.0  0.0  0.0 2  1.0 -1.0 -3.0 The modified round_half_up() function from the previous section will also work here: >>> round_half_up(df, decimals=2)       A     B     C 0 -0.94 -1.14 -0.54 1 -0.55  0.21  0.21 2 1.27 -0.81 -3.30Best Practices and ApplicationsNow that you have come across most of the rounding techniques, let us learn some of the best practices to make sure we round numbers in the correct way.Generate More Data and Round LaterSuppose you are dealing with a large set of data, storage can be a problem at times. For example, in an industrial oven you would want to measure the temperature every ten seconds accurate to eight decimal places, using a temperature sensor. These readings will help to avoid large fluctuations which may lead to failure of any heating element or components. We can write a Python script to compare the readings and check for large fluctuations.There will be a large number of readings as they are being recorded each and everyday. You may consider to maintain three decimal places of precision. But again, removing too much precision may result in a change in the calculation. However, if you have enough space, you can easily store the entire data at full precision. With less storage, it is always better to store at least two or three decimal places of precision which are required for calculation.In the end, once you are done computing the daily average of the temperature, you may calculate it to the maximum precision available and finally round the result.Currency Exchange and RegulationsWhenever we purchase an item from a particular place, the tax amount paid against the amount of the item depends largely on geographical factors. An item which costs you $2 may cost you less (say $1.8)  if you buy the same item from a different state. It is due to regulations set forth by the local government.In another case, when the minimum unit of currency at the accounting level in a country is smaller than the lowest unit of physical currency,  Swedish rounding is done. You can find a list of such rounding methods used by various countries if you look up on the  internet.If you want to design any such software for calculating currencies, keep in mind to check the local laws and regulations applicable in your present location.Reduce errorAs you are rounding numbers in a large datasets used in complex computations, your primary concern should be to limit the growth of the error due to rounding.SummaryIn this article we have seen a few methods to round numbers, out of those “rounding half to even” strategy minimizes rounding bias the best. We are lucky to have Python, NumPy, and Pandas already have built-in rounding functions to use this strategy. Here, we have learned about -Several rounding strategies, and how to implement in pure Python.Every rounding strategy inherently introduces a rounding bias, and the “rounding half to even” strategy mitigates this bias well, most of the time.You can round NumPy arrays and Pandas Series and DataFrame objects.If you enjoyed reading this article and found it to be interesting, leave a comment. To learn more about rounding numbers and other features of Python, join our  Python certification course.
Rated 4.5/5 based on 43 customer reviews
12784
How to Round Numbers in Python

While you are dealing with data, sometimes you may... Read More

How To Use Python Lambda Functions

Modern-day programming languages like Python and other programming languages like C, C#, and Java have added lambda functions to their syntax to increase the functionality of the languages.Python Lambdas are anonymous functions which are small and restricted and come without an identifier.Lambda Calculus is a universal model of computation which was formalized by Alonzo Church in the 1930s. In simple terms, it is a formal system in mathematical logic that is based on pure abstraction and can encode any Turing Machine.The two models of computations— lambda calculus and Turing machines can be translated into one another. This equivalence is known as the Church-Turing Hypothesis. However, the lambda calculus is Turing complete and does not keep any state, unlike the Turing machine.The Turing machine has led to the discovery of the imperative style of programming. This type of approach requires managing states and comprises of programming with statements which drive the program in steps, using a comprehensive and detailed instruction format. Languages like C, Fortran, or Python uses this type of programming technique.On the other hand, the lambda philosophy focuses on data abstraction, transformation, and purity. Their approach is declarative in nature and functional languages like Haskell, Lisp, or Erlang directly inherit them.However, functional features are also a part of the imperative programming style, especially with the implementation of lambda functions in Python or Java.Although Python is not a functional language, some functional features like map(), filter(), reduce(), and the lambda operator were added to Python in the year 1994. To learn more about such features, join our Python certification course.What are Lambdas in Python?Lambda expressions or lambda forms are used to create anonymous functions. Let us first see an identity function. It is an identity relation or identity map that returns the same argument that was originally provided as input. This is a standard Python definition defined using the def keyword:>>> def identity(z): ...    return zOn the other hand, a Python lambda function can have any number of parameters and is written in a single line of code. However, the body of the function can have only one expression.An example of a Python lambda construct:>>> lambda z: zThe expression above comprises of three essential parts:The lambda keyword.The parameters.The function body.Another example of a lambda function with an argument:>>> (lambda z: z + 1)(5) 6Here, the argument and the function are surrounded by parentheses. The function adds 1 to the argument.Since lambda function is an expression, you are allowed to name it whatever you want. Let us perform reduction to compute the value of an expression by naming the lambda function:>>> add = lambda x: x + 1 >>> add(5) 6We can also declare multi-argument function by listing arguments and separating them with commas ( , )  but without using parentheses:>>> name = lambda first_name, last_name: f'The full name is {first.title()} {last.title()}' >>> name('Alex', 'Pandian') 'The full name is Alex Pandian'Here, the function add takes two arguments and returns a string by interpolating the two parameters first_name and last_name.What are Anonymous Functions in Python?A function without a name is known as an anonymous function in Python. It is created with the help of the keyword lambda.An example of an anonymous function with two arguments:>>> lambda a, b: a + bHere, the function has two arguments x and y and is defined using lambda and is not bound to any variable. The function accepts the two arguments and returns their sum.However, you can invoke the same function using an interactive interpreter-only feature of Python via the underscore(_):>>> _(4, 5) 9In the interactive interpreter, the single underscore(_) is bound to the last expression evaluated which means it points to the last lambda function.The functions which take one or more arguments and returns the result are known as higher-order functions.A lambda function can be a higher-order function:>>> higher_order_function = lambda x, f1: x + f1(x) >>> higher_order_function(3, lambda x: x * x) 12 >>> higher_order_function(3, lambda x: x + 3) 9The higher-order functions are considered as built-in functions in the Python Standard Library. Some of the examples are filter(), map(), reduce() or key functions like min(), max(), sort() or sorted().Python Lambdas vs Regular FunctionsA Lambda function might be considered a function with a syntax within a programming language which makes the language “sweeter” for human use. It is created to make things easier to read and express.However, there are a number of precise differences between the regular functions and Python lambdas. The following section highlights them all.A. Difference in FunctionsIn fundamental terms, there is almost no difference between a regular function with a single return line and a lambda function. However, let us check what difference it would make while we write it in code:>>> import dis >>> sub = lambda a, b: a + b >>> type(sub) >>> dis.dis(sub)   1           0 LOAD_FAST                0 (x)               2 LOAD_FAST                1 (y)               4 BINARY_ADD               6 RETURN_VALUE >>> sub The dis module subjects a readable version of the Python bytecode generated by the compiler, which in turn displays the low-level instructions used by the Python interpreter.Let us try the same with a regular function:>>> import dis >>> def sub(x,y): return a + b >>> type(sub) >>> dis.dis(sub)   1           0 LOAD_FAST                0 (x)               2 LOAD_FAST                1 (y)               4 BINARY_ADD               6 RETURN_VALUE >>> sub You can see the Python bytecode is similar in both cases. However, what differs is the style of naming. With def, the function is named as sub whereas lambda is used in case of Python built-in function.B. Difference in TracebackAn example of exception raising using lambda:>>> divide_by_zero = lambda a: a / 0 >>> divide_by_zero(2) Traceback (most recent call last):     File "", line 1, in     File "", line 1, in ZeroDivisionError: division by zeroWhen you’re using a lambda expression, the traceback of an exception identifies only the function, resulting in the exception as .On the other hand, when you’re using a regular function, the traceback provides the name of the function in particular:>>> def divide_by_zero(a): return a / 0 >>> divide_by_zero(2) Traceback (most recent call last):     File "", line 1, in     File "", line 1, in divide_by_zero ZeroDivisionError: division by zeroThe traceback returns the function name divide_by_zero.C. Difference in SyntaxA lambda expression differs in syntax from a normal function in a number of ways: Expressions and StatementsA lambda function can contain only expressions and cannot include any statements. It will raise a SyntaxError upon using statements like return, assert or raise.Let us see an example of using an assert statement in a lambda function:>>> (lambda a: assert a == )(2) SyntaxError: invalid syntaxThe interpreter raises an error while parsing the code since assert is not a valid keyword in a lambda expression. Single ExpressionIn a Python lambda expression, you can distribute the expression across several lines using parentheses or a multi-line string. But the function will still remain as a single expression:>>> (lambda a: ... (a % 2 and 'odd' or 'even'))(5) 'odd'The lambda expression above spreads over two lines but still remains a single expression which evaluates a number and results into odd or even depending upon the argument. AnnotationsYou can use Python type hints and type checking when you’re using normal functions:def name(first_name: str, last_name: str) -> str:     return f'{first_name.title()} {last_name.title()}'If there are any errors with the function name, it can be caught using packages like mypy or pyre. On the other hand, if you’re using a lambda expression, a SyntaxError will be raised:>>> lambda first_name: str, last_name: str: first_name.title() + " " + last_name.title() -> str  File "", line 1     lambda first: str, last: str: first.title() + " " + last.title() -> str SyntaxError: invalid syntax IIFEImmediately Invoked Function Execution or IIFE is a JavaScript function that gets executed as soon as it is defined. However, you cannot use it outside the Python Interpreter.An example of such is:>>> (lambda a, b: a + b)(4,6) 10The IIFE is mainly used to pass the definition of a Python function into a higher-order function like map(), filter() or reduce().D. Difference in ArgumentsPython supports different ways of passing arguments in a lambda expression just like regular functions. Some of which are as follows:Named arguments.Variable list of arguments.Positional arguments.Variable list of keyword arguments.Keyword only arguments.An example to illustrate different ways of passing arguments in a lambda function:>>> (lambda a, b, c: a + b + c)(1, 2, 3) 6 >>> (lambda a, b, c=3: a + b + c)(1, 2) 6 >>> (lambda a, b, c=3: a + b +c)(1, b=2) 6 >>> (lambda *arg: sum(arg))(1,2,3) 6 >>> (lambda **kwarg: sum(kwarg.values()))(number_one=1, number_two=2, number_three=3) 6 >>> (lambda a, *, b=0, c=0: a + b + c)(1, b=2, c=3) 6E. Difference in DecoratorsA decorator is a function that accepts another function and allows adding a behavior to a function or class. Its syntax is @decorator which is written before a function.An example of a decorator is:def decorator(a):     def wrap(*arguments):         print(f"Calling function '{a.__name__}'")         return a(arguments)     return wrap @decorator def decorated_func(x):     print(f"With argument '{x}'")If we invoke decorated_func(“Hello World”), the output will be as follows:Calling function 'decorated_func' With argument 'Hello World'The function decorated_func() prints With argument 'Hello World', but the decorator adds a behavior and also prints  Calling function 'decorated_func'An example of applying decorator in lambda function is mentioned below:# Defining a decorator def trace(a):   def wrap(*arg, **kwarg): print(f"[TRACE] func: {f.__name__}, args: {arg}, kwarg: {kwarg}") return a(*arg, **kwarg)   return wrap # Applying decorator to the function @trace def add(t):     return t + 2 # Calling the decorated function add(3) # Applying decorator to a lambda function print((trace(lambda y: y ** 2))(3))If we execute the following code, we’ll get the following output:[TRACE] func: add, arg: (3,), kwarg: {} [TRACE] func: , arg: (3,), kwarg: {} 9The function add is decorated with @trace and invoked. The lambda function gets implemented to the decorator. The lambda function name is and the regular function is add.F. Difference in ClosuresA closure is a function object that remembers values and is bound to a specified value in the enclosing scope of that function. In simple words, closure is a record that stores a function and defines the environment in which they run.Both lambda functions and regular functions can be implemented as closures.An example to show a closure construct with a regular function:def outer_function(a):     b = 4     def inner_function(c):         print(f"a = {a}, b = {b}, c = {c}")         return a + b + c     return inner_function     for i in range(5):     closure = outer_function(i)     print(f"closure({i+5}) = {closure(i+5)}")inner_function() is a nested function that is being returned by outer_function(). The nested function evaluates the sum of three arguments. The outer_function() is invoked 5 times in a for loop resulting in the output:x = 0, y = 4, z = 5 closure(5) = 9 x = 1, y = 4, z = 6 closure(6) = 11 x = 2, y = 4, z = 7 closure(7) = 13 x = 3, y = 4, z = 8 closure(5) = 15 x = 4, y = 4, z = 4 closure(5) = 017An example to show closure using a Python lambda function:def outer_function(a):     b = 4     return lambda c: a + b + c   for i in range(5):     closure = outer_function(i)     print(f"closure({i+5}) = {closure(i+5)}")The output of the above code will be:closure(5) = 9 closure(6) = 11 closure(7) = 13 closure(7) = 15 closure(7) = 17In both situations, the normal function and the lambda function behaves precisely similar.G. Difference in Evaluation TimeA lambda function’s behavior as a closure may be counter-intuitive, especially while working with loops.  Using a regular function:>>> def wrap(x): ...    def f(): ...        print(x) ...    return f ... >>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(wrap(x)) ... >>> for f in f1: ...    f() ... one two threeWhen the function f1 gets appended to the list, x is evaluated at definition time.Let us implement the same using lambda function:>>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(lambda: print(x)) ... >>> for f in f1: ...    f() ... three three threeSince n is a free variable bound at runtime  when we invoke the function f, an unexpected error occurs printing three all the time.However, to get rid of this situation, you can assign the free variable during definition time:>>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(lambda x=x: print(x)) ...  >>> for f in f1: ...    f() ... one two threeThe lambda argument is initialized with a default value. So, when the function is invoked, the default value x set at definition time is used.Testing LambdasYou can test Python lambdas similarly like regular functions with the help of two modules— unittest and doctest.unittestTesting Python lambda function using unittest:import unittest add = lambda x: x + 2 class Lambda_Testing(unittest.TestCase):     def test_add1(self):         self.assertEqual(add(2), 4)     def test_add2(self):         self.assertEqual(add(2.2), 4.2)     def test_add3(self):         # Should fail         self.assertEqual(add(3), 6) if __name__ == '__main__':     unittest.main(verbosity=2)The function Lambda_Testing tests three methods, each implemented as a lambda function. After execution, the Python file produces the following output:$ python lambda_unittest.py test_add3 (__main__.Lambda_Testing) ... FAIL test_add1 (__main__.Lambda_Testing) ... ok test_add2 (__main__.Lambda_Testing) ... ok ====================================================================== FAIL: test_add_three (__main__.Lambda.Testing) ---------------------------------------------------------------------- Traceback (most recent call last):   File "lambda_unittest.py", line 18, in test_add_three     self.assertEqual(add3(3), 6) AssertionError: 5 != 6 ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)There are two successful test cases and one failure for test_add3. However, if we change the expected result from 6 to 5, the Lambda_Testing will be satisfied for all tests.doctestThe doctest module tests Python lambdas by extracting Python code from docstring:add = lambda a: a + 2 add.__doc__ = """Add 2 to a number.     >>> add(2)     4     >>> add(2.2)     4.2     >>> add(3) # Should fail     6     """ if __name__ == '__main__':     import doctest     doctest.testmod(verbose=True)You can execute the code above using doctest.testmod(), the output will be:$ python lambda_doctest.py Trying:     add(2) Expecting:     4 ok Trying:     add(2.2) Expecting:     4.2 ok Trying:     add(3) # Should fail Expecting:     6 ********************************************************************** File "lambda_doctest.py", line 16, in __main__.add Failed example:     add(3) # Should fail Expected:     6 Got:     5 1 items had no tests:     __main__ ********************************************************************** 1 items had failures:    1 of   3 in __main__.add 3 tests in 2 items. 2 passed and 1 failed. ***Test Failed*** 1 failures.Here, the failure of the test result is also because of the same test failures explained above in the execution of test cases. Although  it is possible to use docstrings for lambda functions, Python recommends using docstrings for regular functions rather than lambda functions.Where should you not use Lambda Expressions?You can simply say that if there is a situation where lambda expressions are not supported, normal functions would be more suitable in such places.However, there might be situations when you need to avoid lambda expressions in your code:When it doesn’t follow the Python Style Guide ( PEP 8 ).When it is difficult to read and interpret.When it doesn’t support readability.Exception Raising An example of raising an exception in a Python lambda:>>> def throw_except(excpt): raise excpt >>> (lambda: throw_except(Exception('Exception is raised')))() Traceback (most recent call last):     File "", line 1, in     File "", line 1, in     File "", line 1, in throw Exception: Something bad happenedThough there are some really clever ways of raising an exception in Python lambda, it is always suggested to use a normal function. This is because a statement is never correct in syntax in the body of a Python lambda function.Cryptic StyleLambda functions are brief in nature, because of which it might be difficult to read. An example of a bad writing style lambda  expression:>>> (lambda _: list(map(lambda _: _ // 2, _)))([1,2,3,4,5,6,7,8,9,10]) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]Let us modify this lambda code by naming the variables:>>> (lambda some_list: list(map(lambda a: a // 2, list)))([1,2,3,4,5,6,7,8,9,10]) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]The code is still difficult to read and understand. However, if we execute the same code using a regular function by distributing the logic across several lines, it would greatly impact the readability of the code:>>> def divide(list):       divide = lambda a: a // 2       return map(divide, list) >>> list(divide([1,2,3,4,5,6,7,8,9,10]))) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]Though this method is not the best, it surely enhances the readability of the code in comparison to the lambda expressions.Python ClassAn example of a Python class using lambda:class Car:     """Car with methods as lambda functions."""     def __init__(s, brand, year):         s.brand = brand         s.year = year     brand = property(lambda s: getattr(s, '_brand'),                     lambda s, value: setattr(s, '_brand', value))     year = property(lambda s: getattr(s, '_year'),                     lambda s, value: setattr(s, '_year', value))     __str__ = lambda s: f'{s.brand} {s.year}'  # 1: error E731     honk = lambda s: print('Honk!')     # 2: error E731If you use a style guide tool like flake8 for checking the code above, it will result in following errors for __str__ and honk:E731 do not assign a lambda expression, use a defSince multiple strings like '_brand and'_year' are used, the properties that are difficult to read are inclined to errors.Ultimately, considering a general rule, you should have a preference for regular functions instead of lambda functions in the context of Python programming.Where should you use lambda expressions?Lambdas provide a shortened syntax for writing functions, which return a single expression. Since Python supports functional programming, lambdas are one of the most common use cases in such a paradigm of programming. Lambdas allow a fine way to pass functions as arguments to another function by creating a one-time function and passing it as a parameter.Let us discuss some situations where using lambdas are very appropriate and also suggested by Python.Functional Constructs Built-in functions like map(), filter(), and functools.reduce(), found in the functools module, are often used along with lambda expressions.Three examples of those functions along with lambda expressions:>>> list(map(lambda x: x.upper(), ['alex', 'bob', 'charles'])) ['ALEX', 'BOB', 'CHARLES'] >>> list(filter(lambda x: 'o' in x, ['alex', 'bob', 'charles'])) ['BOB'] >>> from functools import reduce >>> reduce(lambda acc, x: f'{acc} | {x}', ['alex', 'bob', 'charles']) 'alex | bob | charles'There are other functional constructs which are alternatives to these constructs and are considered more Pythonic in nature.Key FunctionsPython key functions are higher-order functions that directly determine the algorithm driven by the key function. They accept a named parameter known as key, which in turn takes a lambda function.Some of the most commonly used key functions are sort(), sorted, min(), max(), nlargest() and nsmallest().Let us sort a list of IDs using sorted(), in which each ID is a concatenated string of string id and a  number. To sort the list of IDs with the help of the corresponding number associated, we’ll assign lambda to the key argument:>>> ids = ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200'] >>> print(sorted(ids))#Sorting ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200'] >>> sorted_ids = sorted(ids, key=lambda x: int(x[2:]))#Integer sorting >>> print(sorted_ids) ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200']UI FrameworksSome of the UI frameworks that use lambda expressions for their UI events are Tkinter, wxPython or .NET Windows Forms.An example of a Tkinter program using lambda:import tkinter as t import sys window = t.Tk() window.grid_columnconfigure(0, weight=1) window.title("Lambda Calculus") window.geometry("500x200") label = t.Label(window, text="HELLO WORLD") label.grid(column=0, row=0) button = t.Button(     window,     text="Reverse the string",     command=lambda: label.configure(text=label.cget("text")[::-1]), ) button.grid(column=0, row=1) window.mainloop()When the Reverse button is clicked, an event gets fired that triggers the lambda, which in turn changes the label from HELLO WORLD  to DLROW OLLEH.Though lambda can handle firing events, it is always recommended to use a normal function instead as the lambda ends up being self-contained in a shortcode structure.The Python InterpreterPython lambdas are considered as bliss when you use it inside the Python Interpreter. In comparison to regular functions, creating a single-line lambda function to look into some code is much easier. The lambdas in interpreter are just like scrap paper that is useless after being used once and are later thrown away.The timeit moduletimeit is a Python module that is used to time small fragments of Python code. In simple words, it measures the evaluation time of small code snippets.An example of timeit.timeit() being called directly:>>> from timeit import timeit >>> timeit("factorial(100)", "from math import factorial", number = 5) 1.799199999652501e-05A NameError exception would be raised if the full context of the statement is not passed as a string. So the environment should be set up that is required by the main function to be timed.However a  cleaner and more readable solution to the above code is by using a lambda function:>>> from math import factorial >>> timeit(lambda: factorial(100), number=5) 1.799199999652501e-05Although the lambda version takes less execution time, the string version has a benefit of executing the functions again.What are the alternatives of lambda expressions?The higher-order functions like map(), filter(), and functools.reduce() can be used in place of lambdas by changing the form with lists and generators.Using map()map() takes two arguments— a function and an iterable like string, lists or tuples. It executes the function object for each element and returns a modified list of elements.An example to illustrate map() with lambda by transforming a string of integers into its capitalized form:>>> list(map(lambda x: x.capitalize(), ['alex', 'bob', 'charles'])) ['Alex', 'Bob', 'Charles']list() should be invoked so that the iterator gets converted into the modified list which can be shown as output in the Python Interpreter.Using filter()filter() accepts two arguments— a boolean-valued function and an iterable. It is an excellent way to filter out all elements of a sequence for only those which returns True.An example of filter() with lambda which returns all odd numbers from a list:my_list = [5, 10, 21, 95, 51, 69, 72, 22, 70, 99] final_list = list(filter(lambda x: (x%2 != 0) , my_list)) print(final_list) [5, 21, 95, 51, 69, 99]The filter() function returns the list of elements, just like map().Using reduce()reduce() is a functools module function that takes two arguments just like map() and filter(). However, it might also take an initializer as a third argument as the initial value of the accumulator.An example of reduce() with lambda to calculate the sum of a list:from functools import reduce my_list = [5, 8, 12, 25, 50, 500] sum = reduce((lambda x, y: x + y), my_list) print(sum) 600The Pythonic Nature of Lambda ExpressionsThe style guide of Python, PEP 8 discourages lambdas and recommends using normal functions since it is more beneficial. On the other hand, though lambda functions have some good uses in Python, they have a lot of limitations.Lambdas are meant to be used as anonymous functions that will be used especially with functions like map(), filter(), and reduce(). So, you can consider them to be Pythonic since they are quick and elegant in their use and they depend on how you use them.In simple terms, lambdas are considered Pythonic if there are no Pythonic elements available other than that.SummaryLet us sum up what we’ve learned in this article so far:Lambdas and Anonymous Functions.Where should we use a lambda.When should we use a  regular function.Lambda expression abuses.Appropriate uses of Lambdas.Lambda alternatives.Pythonic nature of Lambda.Python lambdas are considered as salt. If used in small amounts, it will enhance the flavor but if used more, the dish will be spoiled. If you are intending to know more about Lambda and Lambda Calculus, you can refer to the following links—Lambda CalculusLambdasTo gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.
Rated 4.5/5 based on 12 customer reviews
8682
How To Use Python Lambda Functions

Modern-day programming languages like Python and o... Read More

Scala-The Complete Guide

Introducing ScalaDoes Scala have a better future than any other programming language? Why Java Developer should learn Scala? What is the demand for Scala? Don’t worry we’ll help you understand why Scala has emerged as one of the most powerful Java alternatives in recent times and what made Developers think about Scala?Scala is a high-caliber programming language that changed the world of big data. It is a general-purpose, functional and object-oriented programming language that helps both object-oriented and functional styles of programming on a larger scale. Scala is a strong and static type language. If you are looking for a technique that can simplify your code easily then Scala is one of the great choices you can opt for. One of the best advantages of Scala for developers is, it reduces the burden by reducing the code snippets to two to three times compared to other application platforms.Let’s understand how Scala came into existenceHistory of ScalaScala is a programming language created by developed by  Martin Odersky in the year 2001.The language was first released internally in the year 2003 later it was officially released on January 20, 2004. Scala language was formally released on the platforms of Java, and .Net in the month of June 2004. Scala 2.0 version was released in Mach 2006. In the year 2011 Typesafe launched to provide commercial support training, services for Scala. These developments led towards the formal cessation of the .Net support in the year 2012. The team Scala has won a five-year research grant of over €2.3 million from the European Research Council.Features of ScalaLike other languages, even Scala has its own features. Its operational characteristics are the same as Java’s. Let’s understand the different features of Scala.Scala is Object-OrientedScala is functionalMarketableScala is ExtensibleExpressivenessScala runs on the JVMScala can execute Java CodeLet’s understand each of these clearly1. Scala is Object-OrientedScala is an object-oriented programming language like Python, Ruby, Java, Smalltalk, etc. It is a pure object-oriented language, it means that every value is an object. The Behavior of objects and Types and are described by classes and traits.2. Scala is functionalIt means that every function in Scala is a value and every value is an object, which makes every function an object. Scala provides a lightweight syntax for defining anonymous functions.3. MarketableYes, Scala is Marketable.  Learning Scala will surely make you more marketable. These days many top companies are moving to Scala.4. ExpressivenessScala is inherently very expressive. There are tons and tons of useful code in Scala. This is attracting more and more Java developers to learn Scala who is willing to write beautiful and clean code.5. Multi-Paradigm LanguageScala supports two programming paradigms like Object-oriented programming (OOP) and Functional programming (FP). It provides you a chance to explore both the languages. This combination of features will help you write Scala programs that are quite compact and simple.6. Scala runs on the JVMJava is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM). It means that both Java and Scala have a common runtime platform.7. Scala can execute Java CodeJust simple, it allows you to use all the classes of the Java SDK and also your favorite java open source projects.Frameworks for ScalaScala is a powerful language that has gained popularity among many developers. It enables developers to develop cutting edge applications that are less costly to maintain and easier to scale. Scala frameworks will help you in selecting the right technologies for solving your project tasks.Following is the list of different Scala frameworks:PlayFinchAkka HTTPChaosLiftScalaQueryBlueEyesSlickLet’s understand a few main frameworks1. PlayPlay is an open-source web application framework released in 2007. This high-velocity framework will allow developers to build highly scalable web applications written in Scala. Applications built with Play deliver all of the benefits of Reactive systems including a high degree of responsiveness, resilience, and elasticity. It is currently used by some large websites like Samsung’s IoT Artik platform, LinkedIn, etc.2. FinchFinch is a modular system of HTTP primitives centered upon the concept of composability. Its purpose is to provide developers simple and robust HTTP primitives. Finch is very fast and highly functional for a variety of systems.3. Akka:Akka is a free and open-source toolkit and runtime, good with distributed processing. It was created for building distributed and resilient message-driven applications. Since the Akka ecosystem is immense it provides a wide range of tools for various purposes like Akka Actors, Akka HTTP, etc.4. Akka HTTPAkka HTTP is a modern toolkit for building integration layers. It provides tools for building integration layers rather than application cores. This Akka HTTP tool is mostly used in high load environments.5. LiftLift is a highly secure and scalable framework designed to address a multitude of security concerns including code injection and cross-site scripting. It was created by David Pollak since he was dissatisfied with some aspects of Ruby on Rails.6. SlickSlick is a modern database query and access library for Scala. It is designed to connect to databases and sources. Slick helps in simplifying the process of building next-generation distributed applications using Scala.Applications of ScalaScala is a general-purpose computer language that widely supports the object and functional style of programming. Using Scala, you can create any type of application in less time. It has the capability to support multiple functionalities Below are the few areas where Scala can be applied.It supports both front and back ends of a web application with scala.jsBig Data and data analysis with Apache SparkScala can be used to create Android ApplicationsHighly concurrent things, like messaging apps, with AkkaScala is also applied in HadoopParallel batch processingDesktop Applications can be created using ScalaConcurrency and distributed application1. Front and back ends of a web application with scala.jsScala is used for designing Web Applications and Web Pages. Scala.js is an implementation of Scala which gathers Scala code to JavaScript. It supports full bilateral interoperability between Scala and Javascript code and hence it allows us to develop front-end web applications in Java using Javascript libraries and frameworks.2. Android ApplicationsScala can be used to build Android Applications. In order to develop Android applications in Scala, you need a minimum set of tools like Android SDK and Homebrew. Scala is easy to use for existing and newly created Android projects and the apps written using Scala is lightweight and start at 30kb.3. Desktop ApplicationsWhen you want to develop desktop applications you need to make sure you have the right framework that is going to work for you. There are several options out there, Scala is one among them.4. Scala is used with HadoopScala is used in some of the Hadoop ecosystem components like Apache Kafka, Apache Spark. Obviously, it will be really useful for someone to develop applications using Scala that uses Hadoop and ecosystem projects.We use Scala due to the factor that it is faster than Java. The central drive behind Scala is to make life easier and more productive for the programmer.Technologies built using ScalaApache SmazaFinagleAkkaLichessScaldingApache SparkLearn more about different technologies built using Scala  here.Career in ScalaScala has been gradually gaining popularity in recent times, some of the world’s best-known web platforms have switched to Scala. According to  Indeed, Scala is in the 12th place in terms of the most demanded languages. Very few developers know how to work with Scala. It is the best-suited technology for aspiring software professionals like Data Scientists, Data Engineers, etc. People who know Scala can enjoy a great career as Scala Developer.Different Scala Job RolesSoftware EngineerSenior Software EngineerSoftware DeveloperApplication DeveloperIT ConsultantScala Developers SalaryAccording to  PayScale the average salary for a Software Engineer with Scala Skills is RS 1019K. Let’s see the salary for different job roles.Job RolesMinimum Salary in RSMaximum Salary  in RSSoftware Engineer296K1.8MSenior Software Engineer452K2.9MSoftware Developer296K1MApplication Developer708K1.1MIT Consultant670K2.3MSenior Software Engineer/ Developer/ Programmer528K2.3MSoftware Engineer/ Developer/ Programmer240K550KSource: PayScaleScala Developers Salary in  different countriesAs per  PayScale the average salary for a Software Engineer with Scala Skills is $107,633. Scala Developer's salary differs from country to country. Let’s see the salary for a Software Engineer with Scala Skills in other countries.CountryMinimumMaximumSourceUSA$97195-Indeed.comFrance€33000 (Junior)€52000StackOverflowAustraliaAUS65000 (Specialist)AUS 146000PayScaleGermany€43000€81000PayScaleUkraine$12000$46000PayScaleAre you still pondering about the future of your career in Scala? Confused about whether to make a career shift in Scala or not? What will be the next career option available? Don’t worry you can earn a Scala Certification and grab a chance to get your dream job. Taking up   Scala Certification Course will definitely give you an advantage while hiring. Scala Certification is the best way to tell your hiring manager that you belong to the category of niche professionals who can make a difference. Taking up this certification course will help you understand the basics of how functional programming work. Hence, learning Scala programming language will definitely take your career to the new career avenues.
Rated 4.5/5 based on 33 customer reviews
7457
Scala-The Complete Guide

Introducing ScalaDoes Scala have a better future t... Read More

Differences Between Swift and Objective C

Today, apps have become a crucial part of the marketing industries and mobile app development companies are now developing more apps according to customers’ requirements to gain profit. While developing the apps, the companies need to make sure that the app is pleasant, loads fast, execute even more fast, and valuable for its consumers. Programming languages live longer, but it is the market getting outdated with the use of same programming language to develop an app. If you are developing apps and not yet explored Swift, an iOS programming language then you should make a note that Swift is the language of this era which not only supercede Objective-C (the other iOS programming language) also a better option to replace embedded programming on Apple platforms. But, how these two programming languages differ from each other? Let’s take a look at the differences between Swift and Objective-C iOS programming languages.Swift vs Objective-CThere are many factors to consider every time before choosing any programming language before app development. It leads to confusion among the app developers which leaves a space for the discussion on which language to choose- Swift or Objective-C for building iOS application? Have a look at the analysis of facts given by Google trends that will solve all your doubts on choosing between the Swift or Objective-C programming languages:  Let’s take a closer look at the comparison of Swift vs Objective-C:Switch is easyIn Swift programming language, a switch can be executed to all new features such as ranges, tuples, values, lists of values, wildcards, as well as lines, classes, and structures. It doesn’t ‘fall through’ by default. Objective-C code is less readable and more complicated. In addition to this, it is mandatory to develop a separate new structure for some Point variable.  On the other side, Swift simplifies this process.User-FriendlySwift has a more simplified syntax for creating fields and properties of the classes. Also, properties in Swift do not require instance variables. On the other end, in the latest versions of Objective-C, instance variables were created automatically and they could be set manually as well.In Swift, instance variables cannot be created.    Easy Code CompilationThis is a very interesting feature for programmers. Xcode IDE is the latest editor where programmers can run the code. This code can be compiled and executed once at this editor. This lets the programmer code and see the results directly without building a complete project and running an emulator to check everything, saving your time. In Swift, you can easily experiment with new algorithms using a great interactive environment, which is not possible in Objective-C.  Better enumEnum is referred to as lines, characters, integers, and fractional numbers in Swift programming language. Therefore, using Swift, you get a more readable and less complex code implementing the inverse transformation #toRaw which is not possible with Objective-C.   Functional Programming featuresIn Swift, there are higher-order functions, functions as values, nested functions, closures, anonymous functions and other attributes of real functional programming. On the contrary, in Objective-C, you have to use blocks instead of functions. That’s why the code in Objective-C is 4 times lengthy and not as clear as in Swift.Differences between Swift and Objective-CWhile comparing Swift with Objective-C, it should always be noted that Swift is improved on a continual basis and this is a reason that the developers around the world are learning this new language. The most crucial reason for learning this language is that an average programmer also can develop simple mobile applications with Swift.But, how will you decide which language to learn- either Swift or Objective-C? Let's take a look around the tabular form of comparison between Swift and Objective-C languages based on the factors:FactorsSwift                        vs              Objective-CExecution TimeIt takes less time as unchanged files are not compiled againIt takes more time as the whole code is built each time when there is a change in codeSupporting OSSupports iOS, OS XIt is cross-platformParadigmIt is Object-OrientedIt is Class-based Object OrientedPlatformIt has a WYSIWYG editorIt has a basic editorReadabilityIn Swift, it eliminates @ symbol, increasing its readabilityObjective-C makes use of @ symbol for new keyword insertionCode LengthsHere, codes are smaller and less complexHere, codes are lengthy and complexEnumsIn Swift language, raw value is mapped to enum directlyIn Objective-C, raw value is assigned manually to an enumMaintaining CodeIn Swift, a code is easy to manage (similar to the English language)In Objective-C, a code is difficult to manageFunctional ProgrammingSwift incorporates functional programming with the help of various functionsThis programming language doesn’t incorporate functional programmingDeclaration SyntaxDeclaration Syntaxes are more simplified which needs no instance variablesIn Objective-C, declaration syntaxes are unmanageable which needs instance variablesType DefinitionHere, no need to define TypeHere, need to mention the Type specificallyComing to the conclusionSwift is finally declared as ABI stable and is considered as a mature language. Also, from now on the future updates in Swift will not break the current code in Swift 5. On the other hand, Apple provides good interoperability between these two languages- Swift and Objective-C. If you are building a binary framework, you can use Swift language to get Module Framework Stability and if you want to develop any C++ and Objective-C++ framework, at that moment you can blend the two languages- Swift and Objective-C. 
Rated 4.5/5 based on 19 customer reviews
5877
Differences Between Swift and Objective C

Today, apps have become a crucial part of the mark... Read More