1669856640
In this python tutorial we will learn Python Regular Expression Interview Questions. Welcome to the first article in a series of interview questions and solutions in python! I will be walking through the solutions in detail, so you understand exactly what is going on. The solutions are written in python because it is arguably one of the easiest languages to master interview questions in – meaning you may have a higher chance of dominating the interview!
In this article, we will be using Regular Expressions to solve each problem. I hope you’re as excited as I am. So, without further adieu, let’s begin!
Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.
Your task is to write a function that takes a string argument and returns a new string with all vowels removed.
For example, the string “Hello World!” would become “Hll Wrld”.
Note: For this problem, ‘y’ is NOT considered a vowel.
This doesn’t look too bad, does it? Let’s jump right in!
Here is what the skeleton of the solution looks like:
def disemvowel(string_):
"""Removes all occurences of vowels from the string.
Args:
string_ (str): The input string.
Returns:
(str): The string with vowels removed.
"""
When I first began coding, my instinct for this solution would have been to create a temporary string, loop through the input string, and concatenate every letter that isn’t a vowel onto the temp string before returning it. However, programmers are smart folk – I’ll bet you can already tell me that this isn’t the most efficient solution.
We can use a Regular Expression (RegEx) to greatly reduce the complexity of the solution. Our goal is to replace every vowel (lower and uppercase) with a blank space. We can use the regular expression ‘substitute‘ operation to replace all the vowels with a blank space.
The substitute operation has 3 arguments we’ll be using:
re.sub(pattern, replacement, input_string)
“Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in input_string with replacement. If the pattern isn’t found, input_string is returned unchanged.” – Python Docs
In python, RegEx uses the “re” class, so let’s be sure to import that into our code:
import re
VOWELS_REGEX = r"[aeiouAEIOU]"
def disemvowel(string_):
return re.sub(VOWELS_REGEX, "", string_)
if __name__ == '__main__':
print(disemvowel("Programming With Mosh Rocks!"))
Output:
Prgrmmng Wth Msh Rcks!
———————————————————————-
The VOWELS_REGEX variable is, of course, used to find the vowels in the string. To make a regex pattern, we start the string with an ‘r’ to tell python to create a “raw string pattern”. This lets us use escape characters, or “\”, in our patterns followed by regex special characters.
Next, we use a regex metacharacter (a character with a special meaning). In this case, we use the metacharacter “[]”, which contains a set of characters that will match any character inside of it. For example, “[0-9a-zA-Z]” means it will match all numbers from 0 to 9 and all lowercase and uppercase letters from a-z. I’m sure you noticed using ranges in a set decreased the number of characters you need to type out.
The code works! Great job 🙂
Write a function that accepts a string and searches it for a valid phone number.
Return the phone number if found.
A valid phone number may be one of the following:
Here is what the skeleton of the solution looks like:
def find_valid_phone(text):
""" check text for phone number in either following format:
- (xxx)-xxx-xxxx
- xxx-xxx-xxxx
Args:
text (str): random string
Returns:
phone (bool): a valid phone number in the required format
"""
To solve this problem, we’ll be using the regular expression operation, “search” to find the pattern (phone number) in the text.
The search operation has 2 arguments we’ll be using:
re.search(pattern, string)
“Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern.” – Python Docs
Here is the solution:
import re
def find_valid_phone(text):
PHONE_REGEX = r'(\d{3}|\(\d{3}\))-\d{3}-\d{4}'
phone = re.search(PHONE_REGEX, text)
if phone != None:
return phone.group()
if __name__ == '__main__':
print(find_valid_phone('Call me at 415-555-1011 tomorrow.'))
print(find_valid_phone('My number is (212)-543-2212 tomorrow.'))
Output:
415-555-1011
(212)-543-2212
———————————————————————-
The PHONE_REGEX variable is used to find the phone number. Again, we start it with ‘r’ to signify the creation of a raw string.
To start with, we use a parenthesis (which is the beginning of a group in Regex. I’ll explain why in a minute.
Then, we use a ‘\’, which is an escape character. It signifies the beginning of a special regex sequence and follows with a character that has a special meaning.
We follow the escape character by a ‘d{3}’, which means ‘match 3 digits’. This will match the first 3 digits of the phone number with the format “xxx”. But what about the other format?
To match the other format, we need to use the pipe (‘|’), because we want to find “xxx” OR “(xxx)”. Be sure to keep both formats inside of the group we created at the beginning of the pattern.
Follow that by the escape character “\” and “(“, which looks for literal parentheses. If you don’t use the escape character before the parentheses, it will assume you are starting another group.
Finally, we finish the pattern with a “-” and more “digit” special characters (followed by how many digits to match it to, {3} and {4}).
Remember, the search operator returns a match object. In order to get the phone number out of the match object, access it using the group operator. Pass an int argument to the operator to denote which group to return. You can make new groups by surrounding characters with parentheses inside a pattern. By default, The entire match is the zeroth group, accessed by either “match.group()” or “match.group(0)“.
That’s it! The code works. Do you feel more confident with regex yet? Just in case, let’s do more!
Write a function that employs regular expressions to ensure the password given to the function is strong.
A strong password is defined as follows:
You may need to test the string against multiple regex patterns to validate its strength.
At first glance, this problem looks a lot harder than the previous one. In actuality, it’s just as simple (just longer).
Here is what the skeleton of the solution looks like:
def validate_password(password):
""" check for
- at least eight characters long
- contains uppercase character
- contains lowercase character
- has at least one digit
- has at least one special character
Args:
password (str): password as string
Returns:
(bool): True if password is strong, else False
"""
To solve this problem, we’ll be using the regex “search” operator again to ensure that each pattern (password criteria) is fulfilled.
import re
def validate_password(password):
# REGEX PATTERN THAT CHECKS PASSWORD HAS AT LEAST 8 CHARACTERS
at_least_8 = r".{8,}"
# REGEX PATTERN THAT CHECKS PASSWORD HAS 1 LOWERCASE
one_lowercase = r"[a-z]"
# REGEX PATTERN THAT CHECKS PASSWORD HAS 1 UPPERCASE
one_uppercase = r"[A-Z]"
# REGEX PATTERN THAT CHECKS PASSWORD HAS 1 DIGIT
one_digit = r"\d"
# REGEX PATTERN THAT CHECKS PASSWORD HAS 1 SPECIAL CHARACTER
special_characters = r"!\”#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
if re.search(at_least_8, password) == None:
print('Error: Password must have at least 8 characters')
return False
elif re.search(one_lowercase, password) == None:
print('Error: Password must have at least 1 lowercase character')
return False
elif re.search(one_uppercase, password) == None:
print('Error: Password must have at least 1 uppercase character')
return False
elif re.search(one_digit, password) == None:
print('Error: Password must have at least 1 digit')
return False
elif re.search(special_characters, password) == None:
print('Error: Password must have at least 1 special character')
return False
return True
if __name__ == '__main__':
print(validate_password('pass'))
print(validate_password('PASSWORD'))
print(validate_password('password'))
print(validate_password('Password'))
print(validate_password('Password77'))
print(validate_password('Password-77'))
Output:
Error: Password must have at least 8 characters
False
Error: Password must have at least 1 lowercase character
False
Error: Password must have at least 1 uppercase character
False
Error: Password must have at least 1 digit
False
Error: Password must have at least 1 special character
False
True
———————————————————————-
Remember, you may use the pipe to find pattern1 OR pattern2 in a string. But, if you want to ensure pattern1 AND pattern2 are fulfilled in a string, we’ve got to split them up. We’ll be splitting the five criteria into five different patterns.
Begin by creating a pattern that checks for a minimum of 8 characters. To do this, we use “.” to check for any character, and the “{8, }” to check that there is a minimum of 8 of them (with no maximum value specified).
Then, create a pattern that checks for a lower case character. We use the lowercase letters from “a-z” inside of a set to check for this.
Next, make a pattern to check for an uppercase character. We use the uppercase letters from “A-Z” inside of a set to do this.
Next, we check for a digit (“\d”).
For the final pattern, we check for a special character. The OWASP recommends the following list of special characters for passwords:” !\”#$%&'()*+,-./:;<=>?@[\]^_`{|}~”. We can put these characters inside of a set to search for them in the provided password.
We’ll use these patterns in five separate searches to see if each criterion is met. If even one of the match regexes returns None, we’ll know the password is NOT strong and to return False. Else, we return True.
Our job is done!
Regular expressions are incredibly powerful tools that every developer should be proficient in. Unfortunately, most do not take the time to learn it well. Do your future self a favor and learn them early – you will be thanking your current self in the future 🙂
Original article sourced at: https://programmingwithmosh.com
1595098800
Android Interview Questions and Answers from Beginner to Advanced level
DataFlair is committed to provide you all the resources to make you an android professional. We started with android tutorials along with practicals, then we published Real-time android projects along with source code. Now, we come up with frequently asked android interview questions, which will help you in showing expertise in your next interview.
Android – one of the hottest technologies, which is having a bright future. Get ready to crack your next interview with the following android interview questions. These interview questions start with basic and cover deep concepts along with advanced topics.
1. What is Android?
Android is an open-source mobile operating system that is based on the modified versions of Linux kernel. Though it was mainly designed for smartphones, now it is being used for Tablets, Televisions, Smartwatches, and other Android wearables.
2. Who is the inventor of Android Technology?
The inventors of Android Technology are- Andry Rubin, Nick Sears, and Rich Miner.
3. What is the latest version of Android?
The latest version of Android is Android 10.0, known as Android Q. The upcoming major Android release is Android 11, which is the 18th version of Android. [Note: Keep checking the versions, it is as of June 2020.]
4. How many Android versions can you recall right now?
Till now, there are 17 versions of Android, which have their names in alphabetical order. The 18th version of Android is also going to come later this year. The versions of Android are here:
5. Explain the Android Architecture with its components.
This is a popular android developer interview question
Android Architecture consists of 5 components that are-
a. Linux Kernel: It is the foundation of the Android Architecture that resides at the lowest level. It provides the level of abstraction for hardware devices and upper layer components. Linux Kernel also provides various important hardware drivers that act as software interfaces for hardwares like camera, bluetooth, etc.
b. Native Libraries: These are the libraries for Android that are written in C/C++. These libraries are useful to build many core services like ART and HAL. It provides support for core features.
c. Android Runtime: It is an Android Runtime Environment. Android Operating System uses it during the execution of the app. It performs the translation of the application bytecode into the native instructions. The runtime environment of the device then executes these native instructions.
d. Application Framework: Application Framework provides many java classes and interfaces for app development. And it also provides various high-level services. This complete Application framework makes use of Java.
e. Applications: This is the topmost layer of Android Architecture. It provides applications for the end-user, so they can use the android device and compute the tasks.
6. What are the services that the Application framework provides?
The Android application framework has the following key services-
a. Activity Manager: It uses testing and debugging methods.
b. Content provider: It provides the data from application to other layers.
c. Resource Manager: This provides users access to resources.
d. Notification Manager: This gives notification to the users regarding actions taking place in the background.
e. View System: It is the base class for widgets, and it is also responsible for event handling.
7. What are the important features of Linux Kernel?
The important features of the Linux Kernel are as follows:
a. Power Management: Linux Kernel does power management to enhance and improve the battery life of the device.
b. Memory Management: It is useful for the maximum utilization of the available memory of the device.
c. Device Management: It includes managing all the hardware device drivers. It maximizes the utilization of the available resources.
d. Security: It ensures that no application has any such permission that it affects any other application in order to maintain security.
e. Multi-tasking: Multi-tasking provides the users the ease of doing multiple tasks at the same time.
8. What are the building blocks of an Android Application?
This is a popular android interview question for freshers.
The main components of any Android application are- Activity, Services, Content Provider, and Broadcast Receiver. You can understand them as follows:
a. Activity- It is a class that acts as the entry point representing a single screen to the user. It is like a window to show the user interface.
b. Services- Services are the longest-running component that runs in the background.
c. Content Provider- The content provider is an essential component that allows apps to share data between themselves.
d. Broadcast receivers- Broadcast receiver is another most crucial application component. It helps the apps to receive and respond to broadcast messages from the system or some other application.
9. What are the important components of Android Application?
The Components of Android application are listed below:
10. What are the widgets?
Widgets are the variations of Broadcast receivers. They are an important part of home screen customization. They often display some data and also allow users to perform actions on them. Mostly they display the app icon on the screen.
11. Can you name some types of widgets?
Mentioned below are the types of widgets-
a. Informative Widgets: These widgets show some important information. Like, the clock widget or a weather widget.
b. Collective Widgets: They are the collection of some types of elements. For example, a music widget that lets us change, skip, or forward the song.
c. Control Widgets: These widgets help us control the actions within the application through it. Like an email widget that helps check the recent mails.
d. Hybrid Widgets: Hybrid widgets are those that consist of at least two or more types of widgets.
12. What are Intents?
Intents are an important part of Android Applications. They enable communication between components of the same application as well as separate applications. The Intent signals the Android system about a certain event that has occurred.
13. Explain the types of intents briefly?
Intent is of three types that are-
a. Implicit Intents: Implicit intents are those in which there is no description of the component name but only the action.
b. Explicit Intents: In explicit intents, the target component is present by declaring the name of the component.
c. Pending Intents: These are those intents that act as a shield over the Intent objects. It covers the intent objects and grants permission to the external app components to access them.
14. What is a View?
A view is an important building block that helps in designing the user interface of the application. It can be a rectangular box or a circular shape, for example, Text View, Edit Text, Buttons, etc. Views occupy a certain area of the screen, and it is also responsible for event handling. A view is the superclass of all the graphical user interface components.
15. What do you understand by View Group?
It is the subclass of the ViewClass. It gives an invisible container to hold layouts or views. You can understand view groups as special views that are capable of holding other views, that are Child View.
16. What do you understand about Shared Preferences?
It is a simple mechanism for data storage in Android. In this, there is no need to create files, and using APIs, it stores the data in XML files. It stores the data in the pair of key-values. SharedPreferences class lets the user save the values and retrieve them when required. Using SharedPreferences we can save primitive data like- boolean, float, integer, string and long.
17. What is a Notification?
A notification is just like a message that shows up outside the Application UI to provide reminders to the users. They remind the user about a message received, or some other timely information from the app.
18. Give names of Notification types.
There are three types of notifications namely-
a. Toast Notification- This notification is the one that fades away sometime after it pops up.
b. Status Notification- This notification stays till the user takes some action on it.
c. Dialog Notification- This notification is the result of an Active Activity.
19. What are fragments?
A fragment is a part of the complete user interface. These are present in Activity, and an activity can have one or more fragments at the same time. We can reuse a fragment in multiple activities as well.
20. What are the types of fragments?
There are three types of fragments that are: Single Fragment, List Fragment, Fragment Transactions.
21. What are Layout XML files?
Layout XML files contain the structure for the user interface of the application. The XML file also contains various different layouts and views, and they also specify various GUI components that are there in Activity or fragments.
22. What are Resources in Android Application?
The resources in Android Apps defines images, texts, strings, colors, etc. Everything in resources directory is referenced in the source code of the app so that we can use them.
23. Can you develop Android Apps with languages other than Java? If so, name some.
Yes, there are many languages that we can work with, for the development of Android Applications. To name some, I would say Java, Python, C, C++, Kotlin, C#, Corona/LUA.
24. What are the states of the Activity Lifecycle?
Activity lifecycle has the following four stages-
a. Running State: As soon as the activity starts, it is the first state.
b. Paused State: When some other activity starts without closing the previous one, the running activity turns into the Paused state.
c. Resume State: When the activity opens again after being in pause state, it comes into the Resume State.
d. Stopped State: When the user closes the application or stops using it, the activity goes to the Stopped state.
25. What are some methods of Activity?
The methods of Activity are as follows:
26. How can you launch an activity in Android?
We launch an activity using Intents. For this we need to use intent as follows:
27. What is the service lifecycle?
There are two states of a service that are-
a. Started State: This is when the service starts its execution. A Services come in start state only through the startService() method.
b. Bounded State: A service is in the bounded state when it calls the method bindService().
28. What are some methods of Services?
The methods of service are as follows-
29. What are the types of Broadcast?
Broadcasts are of two types that are-
a. Ordered Broadcast: Ordered broadcasts are Synchronous and work in a proper order. It decides the order by using the priority assigned to the broadcasts.
b. Normal Broadcast: These are asynchronous and unordered. They are more efficient as they run unorderly and all at once. But, they lack full utilization of the results.
30. What are useful impotent folders in Android?
The impotent folders in an Android application are-
31. What are the important files for Android Application when working on Android Studio?
This is an important android studio interview question
There are following three files that we need to work on for an application to work-
a. The AndroidManifest.xml file: It has all the information about the application.
b. The MainActivity.java file: It is the app file that actually gets converted to the dalvik executable and runs the application. It is written in java.
c. The Activity_main.xml file: It is the layout file that is available in the res/layout directory. It is another mostly used file while developing the application.
32. Which database do you use for Android Application development?
The database that we use for Android Applications is SQLite. It is because SQLite is lightweight and specially developed for Android Apps. SQLite works the same way as SQL using the same commands.
33. Tell us some features of Android OS.
The best features of Android include-
34. Why did you learn Android development?
Learning Android Studio is a good idea because of the following-
35. What are the different ways of storage supported in Android?
The various storage ways supported in Android are as follows:
36. What are layouts?
Layout is nothing but arrangements of elements on the device screen. These elements can be images, tests, videos, anything. They basically define the structure of the Android user interface to make it user friendly.
37. How many layout types are there?
The type of layouts used in Android Apps are as follows:
38. What is an APK?
An APK stands for Android Package that is a file format of Android Applications. Android OS uses this package for the distribution and installation of the Android Application.
39. What is an Android Manifest file?
The manifest file describes all the essential information about the project application for build tools, Android operating system, and google play. This file is a must for every Android project that we develop, and it is present in the root of the project source set.
#android tutorials #android basic interview questions #android basic questions #android developer interview questions #android interview question and answer #android interview questions #android interview questions for experienced #android interview questions for fresher
1624767960
Are you preparing for a job interview or an exam that involves knowledge about Python? Or do you want to quickly go through common topics of Python?
Here is a list of 50 interview questions with answers. The list is in no particular order.
I hope you enjoy it.
…
#python #data-science #software-development #50 python interview questions and answers #interview questions and answers #python interview questions and answers
1626775355
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Robust frameworks
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Progressive applications
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
1623050167
Everyone loves Mad Libs! And everyone loves Python. This article shows you how to have fun with both and learn some programming skills along the way.
Take 40% off Tiny Python Projects by entering fccclark into the discount code box at checkout at manning.com.
When I was a wee lad, we used to play at Mad Libs for hours and hours. This was before computers, mind you, before televisions or radio or even paper! No, scratch that, we had paper. Anyway, the point is we only had Mad Libs to play, and we loved it! And now you must play!
We’ll write a program called mad.py
which reads a file given as a positional argument and finds all the placeholders noted in angle brackets like <verb>
or <adjective>
. For each placeholder, we’ll prompt the user for the part of speech being requested like “Give me a verb” and “Give me an adjective.” (Notice that you’ll need to use the correct article.) Each value from the user replaces the placeholder in the text, and if the user says “drive” for “verb,” then <verb>
in the text replaces with drive
. When all the placeholders have been replaced with inputs from the user, print out the new text.
#python #regular-expressions #python-programming #python3 #mad libs: using regular expressions #using regular expressions
1619647380
Attending a Python interview and wondering what are all the questions and discussions you will go through? Before attending a python interview, it’s better to have an idea about the types of python interview questions will be asked so that you can prepare answers for them.
Undisputed one of the most popular programming languages these days, Python is a hot choice for both established and beginner programmers. And, ease of the language helps develop some interesting Python Projects that are applicable in the real world. Its simplicity and ease of use lend to its popularity. Not to mention, it is the language of choice for the data science and data visualization fields, along with R.
That being said, Python is a very important language for anyone’s toolkit. To help you out, I have created the top python interview question and answers guide to understand the depth and real-intend of python interview questions.
Apart from these questions, you will also be given code snippets where you have to deduce the resulting value or statement (or the lack of it). These cannot be predicted and will be dependent on your programming practice. Let’s get started with top python interview questions and answers.
#data science #python interview #python interview questions #python interview questions and answers