Question:
Write python program to print the user name of a given email address.
Program:
|
1 2 3 4 5 6 7 8 9 |
import re emailAddress = raw_input("Enter email addresses: ") pat2 = "(\w+)@((\w+\.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) |
Email addresses are in the “[email protected]” format.
Both user names and company names are composed of letters only.
Use \w to match letters.
Output:
|
1 2 3 |
Enter email addresses: hi@globalsql.com hi |
Question:
Raise Assertion error when trying to verify that every number in the list [2,4,6,8,1] is even.
Use “assert expression” to make assertion
Program:
|
1 2 3 4 5 |
li = [2,4,6,8,1] for i in li: assert i%2==0 |
Explanation:
The Assert Statement: When python encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception.
Output:
|
1 2 3 4 5 6 7 |
Traceback (most recent call last): File "assert.py", line 4, in <module> assert i%2==0 AssertionError |
Question:
Write a program to print the squares of the numbers in a list [1,2,3,4,5] without using any iterative function.,
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#creates generator def squaregenerator(nums): for i in nums: #yield keyword makes it a generator yield(i*i) #no need of return as it is generator #our data my_nums = [1,2,3,4,5] res2=squaregenerator(my_nums) print res2 print next(res2) print next(res2) print next(res2) print next(res2) print next(res2) <span style="color: #000000;"><strong>Explanation:</strong></span> <span style="color: #000000;">Generators are very easy to implement, but a bit difficult to understand.</span> <span style="color: #000000;">Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.</span> <span style="color: #000000;">When an iteration iterate over a set of item starts using <strong>for</strong> statement, the generator runs. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the <strong>for</strong> loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.</span> <span style="color: #000000;"><strong>Output:</strong></span> |
|
1 2 3 4 5 6 |
<generator object squaregenerator at 0x2ac4a8d49820> 1 4 9 16 25 |
Question:
Write a python program to show the difference in zip() and izip() function
Explanation:
zip() is a standard library which combines elements into tuples.
The izip() function works the same way, but it returns an iterable object for an increase in performance by reducing memory usage.
We can directly print the list returned by zip() but, we cannot directly print an iterable object. We need to use next(iterable_object) or a loop.
Lists are stored in memory so they have the advantage of faster access times over Iterable Object whose contents are not entirely stored in memory but fetched on-demand instead.
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
from itertools import izip #import izip to use it in the program list1=[1,2,3] list2=['a','b','c'] print "PRINTING INITIAL LISTS" print list1 print list2 x=zip(list1,list2) print "\n\nzip() PERFORMED" #zip() combines elements of list1 and list2 into tuples and returns a list of tuples which you can directly print print "PRINTING LIST OF TUPLES" print x x=izip(list1,list2) print "\n\nizip() PERFORMED" #izip() does almost same thing as zip() but it returns a iterlist.izip object which is iterable using next() or using loops print x #cant print contents of iterable object directly print "\nUSING LOOP TO PRINT CONTENTS OF izip OBJECT" for i in x: print i |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
PRINTING INITIAL LISTS [1, 2, 3] ['a', 'b', 'c'] zip() PERFORMED PRINTING LIST OF TUPLES [(1, 'a'), (2, 'b'), (3, 'c')] izip() PERFORMED <itertools.izip object at 0x2ae4fc5dcb48> USING LOOP TO PRINT CONTENTS OF izip OBJECT (1, 'a') (2, 'b') (3, 'c') |
Question:
Write a python program to solve a quadratic equation
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions s1 = (-b-cmath.sqrt(d))/(2*a) s2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(s1,s2)) |
Explanation:
Quadratic Equations is a equation having form like ax2 + bx+c =0. Roots are of the form x = (-b +/-√(b2 – 4ac))/2a. To know more about Quadratic Equations, click here.
Output:
|
1 2 3 4 |
Enter a: 1 Enter b: 5 Enter c: 6 The solutions are (-3+0j) and (-2+0j) |
Question:
Write a python program to convert Fahrenheit to Celsius
Program:
|
1 2 3 4 5 |
Fahrenheit = int(raw_input("Enter a temperature in Fahrenheit: ")) Celsius = (Fahrenheit - 32) * 5.0/9.0 print "Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C" |
Explanation:
To convert the temperature from Fahrenheit to Celsius, deduct 32, then multiply by 5, then divide by 9.
Output:
|
1 2 3 |
Enter a temperature in Fahrenheit: 65 Temperature: 65 Fahrenheit = 18.333333333333332 C |
Question:
Write a python program to convert KPH to MPH
Program:
|
1 2 3 |
kmh = int(raw_input("Enter km/h: ")) mph = 0.6214 * kmh print "Speed:", kmh, "KM/H = ", mph, "MPH" |
Explanation:
To convert KPH to MPH, just multiply by 0.6214
Output:
|
1 2 |
Enter km/h: 25 Speed: 25 KM/H = 15.534999999999998 MPH |
Question:
Write a python program to remove punctuations from a string
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = input("Enter a string: ") # remove punctuation from the string no_pt = "" for char in my_str: if char not in punctuations: no_pt = no_pt + char # display the unpunctuated string print(no_pt) |
Explanation:
There are fourteen punctuation marks commonly used in English grammar. They are the period, question mark, exclamation point, comma, semicolon, colon, dash, hyphen, parentheses, brackets, braces, apostrophe, quotation marks, and ellipsis.
Output:
|
1 2 |
Enter a string: GlobalSQA!! on^ the& swing)( GlobalSQA on the swing |
Question:
Write a python program to add two matrices
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
m=int(input("ENTER MARTIX ROW SIZE m : ")) n=int(input("ENTER MARTIX COLUMN SIZE n : ")) #initializing matrix elements as 0 X = [[0]*n for j in range(m)] Y = [[0]*n for j in range(m)] result = [[0]*n for j in range(m)] #getting input to matrix X for i in range (m): for j in range (n): print ('entry in row: ',i+1,' column: ',j+1) X[i][j] = int(input()) #printing first matrix X print "FIRST MATRIX : " for i in range (m): for j in range (n): print X[i][j],"\t", print "\n" #getting input to matrix X for i in range (m): for j in range (n): print ('entry in row: ',i+1,' column: ',j+1) Y[i][j] = int(input()) #printing second matrix Y print "SECOND MATRIX : " for i in range (m): for j in range (n): print Y[i][j],"\t", print "\n" #adding X and Y to result for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] #displaying result print "SUM OF MATRICES IS : " for i in range (m): for j in range (n): print result[i][j],"\t", print "\n" |
Explanation:
If A and B are the two matrices for addition, both of them must be of the same order.
If i and j are the index positions, then result[i][j] = A[i][j] + B[i][j]
Output:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
ENTER MARTIX ROW SIZE m : 2 ENTER MARTIX COLUMN SIZE n : 2 entry in row: 1 column: 1 2 entry in row: 1 column: 2 2 entry in row: 2 column: 1 2 entry in row: 2 column: 2 2 FIRST MATRIX : 2 2 2 2 entry in row: 1 column: 1 9 entry in row: 1 column: 2 9 entry in row: 2 column: 1 9 entry in row: 2 column: 2 9 SECOND MATRIX : 9 9 9 9 SUM OF MATRICES IS : 11 11 11 11 |
Question:
Write a python program to find the HCF
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#Program to find the H.C.F of two input number def HCF(x, y): # choose the smaller number if x > y: small = y else: small = x for i in range(1, small+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) print "The H.C.F. of", n1,"and", n2,"is",HCF(n1, n2) |
Explanation:
The Highest Common Factor (H.C.F) of two (or more) numbers is the largest number that divides evenly into both numbers. In other words the H.C.F is the largest of all the common factors. The common factors or of 12 and 18 are 1, 2, 3 and 6. The largest common factor is 6, so this is the H.C.F. of 12 and 18.
Output:
|
1 2 3 4 5 |
Enter first number: 10 Enter second number: 5 The H.C.F. of 10 and 5 is 5 |
Question :
Write a program to find the factorial of a number using recursive function
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# The recursive function def factorial(n): if n == 1: return n else: return n*factorial(n-1) # take input from the user num = int(input("Enter a number: ")) # check is the number is negative if num < 0: print "Sorry, factorial does not exist for negative numbers" elif num == 0: print "The factorial of 0 is 1" else: print "The factorial of",num,"is",factorial(num) |
Explanation:
Factorial of a number is the product of all natural numbers till that number. It does not exist for negative numbers.
For example, the factorial of 4 would be 1*2*3*4=24
A recursive function is a function that calls on itself. In the above recursive function, the function calls on itself with n-1 as argument till n becomes 1 and 1 is returned. Each time the function is called, product the corresponding n and the factorial of n-1 is returned. Hence, factorial is found.
Output:
1.
|
1 2 |
Enter a number: -9 Sorry, factorial does not exist for negative numbers |
|
1 2 |
Enter a number: 1 The factorial of 1 is 1 |
|
1 2 |
Enter a number: 9 The factorial of 9 is 362880 |
Question:
Write a python program to find the factors of a given number
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
# Python Program to find the factors of a number # This function takes a number and prints the factors def factors(x): print "The factors of",x,"are:" for i in range(1, x + 1): if x % i == 0: print i n = int(input("Enter a number: ")) factors(n) |
Explanation:
The factors of a number are any numbers that divide into it exactly. This includes 1 and the number itself. For example, the factors of 6 are 1, 2, 3 and 6. The factors of 8 are 1, 2, 4 and 8. For larger numbers it is sometimes easier to ‘pair’ the factors by writing them as multiplications.
Output:
|
1 2 3 4 5 6 7 8 9 10 11 |
Enter a number: 10 The factors of 10 are: 1 2 5 10 |
Question
Write a python program to find the largest of three numbers
Hint: Use if and elif
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#Accept three numbers print "Enter the numbers for comparision" nos1 = input("Enter first number: ") nos2 = input("Enter second number: ") nos3 = input("Enter third number: ") #Comparison using if elif clauses if (nos1 > nos2) and (nos1 > nos3): large = nos1 elif (nos2 > nos1) and (nos2 > nos3): large = nos2 else: large = nos3 print "The largest number is",large |
Explanation:
Three numbers are accepted from the user ‘nos1′,’nos2′,’nos3’.
First ‘nos1’ is checked.If it is greater than both ‘nos2’ and ‘nos3’, then ‘large’ is allocated wth the value of ‘nos1’
Otherwise ‘nos2’ is checked. If it is greater than both ‘nos1’ and ‘nos2’,then ‘large’ is allocated with the value of ‘nos2’
Otherwise ‘large’ is allocated with ‘nos3’
Output:
|
1 2 3 4 5 6 7 8 9 |
Enter the numbers for comparision Enter first number: 89 Enter second number: 23 Enter third number: 10 The largest number is 89 |
Question:
Program to find the LCM of two numbers
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# Python Program to find the L.C.M. of two input number # defining a user defined function for finding LCM def lcm(x, y): # choose the greater number if x > y: large = x else: large = y while(True): if((large % x == 0) and (large % y == 0)): lcm = large break large += 1 return lcm nos1 = int(input("Enter first number: ")) nos2 = int(input("Enter second number: ")) print "The L.C.M. of", nos1,"and", nos2,"is", lcm(nos1, nos2) |
Explanation:
A common multiple is a number that is a multiple of two or more numbers. The common multiples of 3 and 4 are 0, 12, 24, …. The least common multiple(LCM) of two numbers is the smallest number (not zero) that is a multiple of both.
Output:
|
1 2 3 4 5 |
Enter first number: 6 Enter second number: 3 The L.C.M. of 6 and 3 is 6 |
Question
Write a python program to check whether given string is palindrome or not without using any inbuilt function to reverse the string
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Program to check if a string is palindrome or not take input from the user string = raw_input("Enter a string: ") #Use inbuilt function to convert all characters to lowercase string = string.lower() # check if the string is equal to its reverse if string == string[::-1]: print("It is palindrome") else: print("It is not palindrome") |
Explanation:
A palindrome is a string which is same read forward or backwards. Dad is a palindrome while Python is not.
In the program, we first accept the string to ‘string’. Since capital letters and small letters are perceived differently because of difference in ASCII codes, we convert the string to all lower for uniformity using inbuilt function ‘x.lower()’ where x is the string
In the above program, we have used the slice operator to reverese the string.The slice operator[n:m:p] returns the part of the string from nth to the (m-1)th character Setting p to -1 returns the reverse order of the slice of string you asked for. Since here we want the whole string, we use the shorthand [::-1]
Compare both the string and it’s reversal. If they are equal, then it’s a palindrome, otherwise not.
Output:
1.
|
1 2 3 |
Enter a string: Dad It is palindrome |
|
1 2 3 |
Enter a string: Python It is not palindrome |
Question 2
Write a Python program to check whether a given number is armstrong or not.
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# Python program to check if the number provided by the user is an Armstrong number or not # take input from the user nos = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = nos while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if nos == sum: print nos,"is an Armstrong number" else: print nos,"is not an Armstrong number" |
Explanation:
Armstrong number is the number whose sum of cube of individual digits is equal to the number itself.
Output:
1.
|
1 2 3 |
Enter a number: 371 371 is an Armstrong number |
|
1 2 3 |
Enter a number: 56 56 is not an Armstrong number |
Question:
Program to print the Fibonacci Number
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# Program to display the Fibonacci sequence up to n-th term n= int(input("Enter Limit: ")) # first two terms n1 = 0 n2 = 1 count = 0 # check if the number of terms is valid if n <= 0: print "Fibonacci exist only for positive numbers" elif n == 1: print "Fibonacci sequence upto",n,":" print n1 else: print "Fibonacci sequence upto",n,":" while count < n: print n1, n3 = n1 + n2 # update values n1 = n2 n2 = n3 count += 1 |
Explanation:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8….
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms
Ex: 5th term is sum of 4th and 3rd term;3=2+1
Output:
1.
|
1 2 3 4 5 |
Enter Limit: 10 Fibonacci sequence upto 10 : 0 1 1 2 3 5 8 13 21 34 |
|
1 2 3 |
Enter Limit: -5 Fibonacci exist only for positive numbers |
|
1 2 3 4 5 |
Enter Limit: 1 Fibonacci sequence upto 1 : 0 |
Question;
Write a program to print the multiplication table of a number
Program:
|
1 2 3 |
num = int(input("Display multiplication table of: ")) for i in range(1,11): print(num,'x',i,'=',num*i) |
|
1 2 3 4 5 6 7 8 9 10 11 |
Display multiplication table of: 17 17 x 1 = 17 17 x 2 = 34 17 x 3 = 51 17 x 4 = 68 17 x 5 = 85 17 x 6 = 102 17 x 7 = 119 17 x 8 = 136 17 x 9 = 153 17 x 10 = 170 |
Question:
Write a program to print some Python built-in functions documents, such as abs(), int(), raw_input(). The built-in document method is __doc__.
Program:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
print abs.__doc__ print int.__doc__ print raw_input.__doc__ def square(num): '''Return the square value of the input number. The number must be integer. ''' return num ** 2 print square(2) print square.__doc__ |
Explanation:
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object’s docsting is defined by including a string constant as the first statement in the object’s definition
Output:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
abs(number) -> number Return the absolute value of the argument. int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. 4 Return the square value of the input number. The number must be integer. |
Being Tester we are used to reporting bugs and we know that developer debug the code to find out the line of code causing the bug. But now you are the one coding the test cases and you are responsible for solving any bug in your testing framework.
Android Studio provides some shortcut keys for debugging. In this post, we will use our HelloWord Espresso test Case Example and We will run our test Case In Debug mode and we will debug our code line by line.
It is always good practice to use Debug Mode for root tracing the bug as it allows you to run your code line by line by setting a debug point. Debug point is the nothing but marking the line of code from which you wish to start debugging. This speeds up your work and efficiency.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
package com.example.globalsqa.myapplication1; import android.app.Activity; import android.app.Instrumentation; import android.app.LauncherActivity; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.support.test.runner.AndroidJUnitRunner; import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityUnitTestCase; import android.test.InstrumentationTestRunner; import android.test.suitebuilder.annotation.SmallTest; import android.view.ContextThemeWrapper; import android.widget.TextView; import com.example.globalsqa.myapplication1.MainActivity; import com.robotium.solo.Solo; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; public class MyActivityTest extends ActivityInstrumentationTestCase2<Activity> { private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.example.globalsqa.myapplication1.MainActivity"; private static Class<?> launchActivityClass; static { try { launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private Solo solo; public MyActivityTest() { super((Class<Activity>) launchActivityClass); } @Override public void setUp() throws Exception { super.setUp(); solo = new Solo(getInstrumentation(), getActivity()); } @Test public void testText() throws Exception { // s=new Solo(this.getInstrumentation(),getActivity()); solo.waitForView("MainActivity"); Thread.sleep(3000); TextView t = (TextView) solo.getCurrentActivity().findViewById(R.id.globalsqa); assertEquals("Hello world!", t.getText().toString()); } public void tearDown() throws Exception { solo.finishOpenedActivities(); super.tearDown(); } } |






This will help you debug your test cases and write a efficient and bug free code.