Python Algorithms Flashcards

1
Q

Write a Python program to print the following string in a specific format (see the output). Go to the editor
Sample String : “Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are” Output :

Twinkle, twinkle, little star,
	How I wonder what you are! 
		Up above the world so high,   		
		Like a diamond in the sky. 
Twinkle, twinkle, little star, 
	How I wonder what you are
A

print(“Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a Python program to get the Python version you are using.

A
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)

Python version
3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609]
Version info.
sys.version_info(major=3, minor=5, micro=2, releaselevel=’final’, serial=0)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a Python program to display the current date and time.
Sample Output :
Current date and time :
2014-07-05 14:34:14

A

import datetime
now = datetime.datetime.now()
print (“Current date and time : “)
print (now.strftime(“%Y-%m-%d %H:%M:%S”))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write a Python program which accepts the radius of a circle from the user and compute the area.

Sample Output :
r = 1.1
Area = 3.8013271108436504

A

from math import pi
r = float(input (“Input the radius of the circle : “))
print (“The area of the circle with radius “ + str(r) + “ is: “ + str(pi * r**2))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write a Python program which accepts the user’s first and last name and print them in reverse order with a space between them.

A

fname = input(“Input your First Name : “)
lname = input(“Input your Last Name : “)
print (“Hello “ + lname + “ “ + fname)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.

A
values = input("Input some comma seprated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)

Sample Output:
Input some comma seprated numbers : 3,5,7,23
List : [‘3’, ‘5’, ‘7’, ‘23’]
Tuple : (‘3’, ‘5’, ‘7’, ‘23’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Write a Python program to accept a filename from the user and print the extension of that.

A

filename = input(“Input the Filename: “)
f_extns = filename.split(“.”)
print (“The extension of the file is : “ + repr(f_extns[-1]))

Sample Output:
Input the Filename: abc.java
The extension of the file is : ‘java’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Write a Python program to display the first and last colors from the following list.
color_list = [“Red”,”Green”,”White” ,”Black”]

A

color_list = [“Red”,”Green”,”White” ,”Black”]
print( “%s %s”%(color_list[0],color_list[-1]))

Red Black

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 615

A
a = int(input("Input an integer : "))
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print (n1+n2+n3)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Write a Python program to print the documents (syntax, description etc.) of Python built-in function(s).
Sample function : abs()
Expected Result :
abs(number) -> number
Return the absolute value of the argument.

A

print(abs.__doc__)

Sample Output:
Return the absolute value of the argument.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Write a Python program to print the calendar of a given month and year.
Note : Use ‘calendar’ module.

A

import calendar
y = int(input(“Input the year : “))
m = int(input(“Input the month : “))
print(calendar.month(y, m))

Sample Output:

Input the year : 2017
Input the month : 04
April 2017
Mo Tu We Th Fr Sa Su
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days

A
from datetime import date
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)

Sample Output:
9

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Write a Python program to get the volume of a sphere with radius 6.

A
volume = 4/3pi * r^3
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V)

Sample Output:
The volume of the sphere is: 904.7786842338603

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.

A
def difference(n):
    if n <= 17:
        return 17 - n
    else:
        return (n - 17) * 2

print(difference(22))
print(difference(14))

Sample Output:
10
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Write a Python program to test whether a number is within 100 of 1000 or 2000

A
def near_thousand(n):
      return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1000))
print(near_thousand(900))
print(near_thousand(800))
print(near_thousand(2200))

Sample Output:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.

A

def sum_thrice(x, y, z):

 sum = x + y + z

 if x == y == z:
  sum = sum * 3
 return sum

print(sum_thrice(1, 2, 3))
print(sum_thrice(3, 3, 3))

Sample Output:
6
27

17
Q

Write a Python program to get a new string from a given string where “Is” has been added to the front. If the given string already begins with “Is” then return the string unchanged.

A
def new_string(str):
  if len(str) >= 2 and str[:2] == "Is":
    return str
  return "Is" + str
print(new_string("Array"))
print(new_string("IsEmpty"))

Sample Output:
IsArray
IsEmpty

18
Q

Write a Python program to get a string which is n (non-negative integer) copies of a given string.

A
def larger_string(str, n):
   result = ""
   for i in range(n):
      result = result + str
   return result

print(larger_string(‘abc’, 2))
print(larger_string(‘.py’, 3))

Sample Output:
abcabc
.py.py.py

19
Q

Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.

A
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
    print("This is an odd number.")
else:
    print("This is an even number.")

Sample Output:
Enter a number: 5
This is an odd number.

20
Q

Write a Python program to count the number 4 in a given list.

A
def list_count_4(nums):
  count = 0
  for num in nums:
    if num == 4:
      count = count + 1

return count

print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))

Sample Output:
2
3

21
Q

Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2

A
def substring_copy(str, n):
  flen = 2
  if flen > len(str):
    flen = len(str)
  substr = str[:flen]
  result = ""
  for i in range(n):
    result = result + substr
  return result
print(substring_copy('abcdef', 2))
print(substring_copy('p', 3));

Sample Output:
abab
ppp

22
Q

Write a Python program to test whether a passed letter is a vowel or not.

A
def is_vowel(char):
    all_vowels = 'aeiou'
    return char in all_vowels
print(is_vowel('c'))
print(is_vowel('e'))

Sample Output:
False
True

23
Q

Write a Python program to check whether a specified value is contained in a group of values.

Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False

A
def is_group_member(group_data, n):
    for value in group_data:
        if n == value:
            return True
    return False
print(is_group_member([1, 5, 8, 3], 3))
print(is_group_member([5, 8, 3], -1))

Sample Output:
True
False

24
Q

Write a Python program to create a histogram from a given list of integers.

A
def histogram( items ):
    for n in items:
        output = ''
        times = n
        while( times > 0 ):
          output += '*'
          times = times - 1
        print(output)

histogram([2, 3, 6, 5])

Sample Output:

  • **
25
Q

Write a Python program to concatenate all elements in a list into a string and return it.

A
def concatenate_list_data(list):
    result= ''
    for element in list:
        result += str(element)
    return result

print(concatenate_list_data([1, 5, 12, 2]))

Sample Output:
15122

26
Q

Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.

numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]

A
for x in numbers:
    if x == 237:
        print(x)
        break;
    elif x % 2 == 0:
        print(x)

Sample Output:
386
462
418
344
236
566
978
328
162
758
918
237

27
Q

Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.

Test Data : 
color_list_1 = set(["White", "Black", "Red"]) 
color_list_2 = set(["Red", "Green"])
Expected Output : 
{'Black', 'White'}
A
Test Data : 
color_list_1 = set(["White", "Black", "Red"]) 
color_list_2 = set(["Red", "Green"])
Expected Output : 
{'Black', 'White'}

Sample Output:
{‘White’, ‘Black’}

28
Q

Write a Python program that will accept the base and height of a triangle and compute the area.

A
b = int(input("Input the base : "))
h = int(input("Input the height : "))
area = b*h/2
print("area = ", area)

Sample Output:
Input the base : 20
Input the height : 40
area = 400.0

29
Q

Create a function that accepts a number as an input. Return a new array that counts down by one, from the number (as arrays ‘zero’th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0].

A
myarr = []
def countDown(num):
   while (num >=0):
       myarr.append(num)
       num =num - 1
   print(myarr)  

countDown(15)

Output:
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

30
Q

Print and Return - Your function will receive an array with two numbers. Print the first value, and return the second.

A
def print1returnanother(a,b):
   print(a)
   return(b)

print1returnanother(5,7)

Output:
5

31
Q

ForThis Length, That Value - Write a function called lengthAndValue which accepts two parameters, size and value. This function should take two numbers and return a list of length size containing only the number in value. For example, lengthAndValue(4,7) should return [7,7,7,7]

A
def lengthandvalue(size, value):
    arr = []
    i = 0
    while i < size:
        arr.append(value)
        i += 1
    return arr 

print(lengthandvalue(7,7))

Output:
[7, 7, 7, 7, 7, 7, 7]