Python:Comparing dictionaries in Python

September 19, 2016

There is already an existing function cmp() from Python 2 which can be used to compare dictionaries, but its output comes as -1,1 or 0. Which I don’t think is much helpful. In python 3, you would need to write your own cmp() function. So, I thought of writing a one which will be more clarifying and helpful to user.


def dict_compare(dict1, dict2):
dict_match = True
keys1 = list(dict1.keys())
keys2 = list(dict2.keys())
if (len(keys1) == len(keys2)):
print (“Number of keys in both dictionaries are same.”)
for i in range(len(keys1)):
values_match = False
for j in range(len(keys2)):
if keys1[i] == keys2[j]:
#print (“keys matched %s %s” %(keys1[i],keys2[j]))
if (dict1[keys1[i]] == dict2[keys2[j]]):
#print(“%s %s” %(dict1[keys1[i]],dict2[keys2[j]]))
values_match = True
break
else:
continue
if values_match == False:
dict_match = False
break
else:
continue
else:
dict_match = False
print (“Number of keys in both dictionaries are different.”)

return dict_match

dict1 = {
“key1″:”value 1”,
“key2″:”value 2”,
“key4″:”value 2”,
}
dict2 = {
“key3″ :”value 3”,
“key4″ :”value 4”,
“key1″ :”value 1”
}
dict3 = {
“key1″:”value 1”,
“key3″:”value 2”,
“key4″:”value 2”,
}

dict4 = {
“key1″:”value 1”,
“key4″:”value 2”,
“key2″:”value 2”,
}

dict_match = dict_compare(dict1,dict2)
print (dict_match)
dict_match = dict_compare(dict1,dict3)
print (dict_match)
dict_match = dict_compare(dict1,dict4)
print (dict_match)


 

Advertisements

Some interesting interview puzzles

August 22, 2016

1.You have 7 balls. One weighs more than the others (not significantly). You have a scale, like the scales of justice. Describe how to find the weighted ball only using the scale twice.

Ans: First select any 4 balls randomly, weigh them 2 vs 2.

If they are equal select 2 more randomly and weigh them 1 vs 1.

If they are equal, then the remaining ball is the heavier one.

If the 2 weighed once are not equal, heavier one is found then.

If the first 4 balls don’t weigh equal, weigh the 2 balls from side which went down.

This should identify the heavier ball by using the scale twice only.

 

2. If you have a vacant field and add one flower and the number of flowers doubles everyday and at the end of 45 days, the field is full, on what day is the field half full?

Ans: Since the field is full on 45th day, it must be half full on 44th day. When all the flowers doubled after 44th day, hall became full on 45th day.

 

3. There are 3 non-transparent buckets with FALSE labels ‘Red’, ‘Blue’ and ‘Red+Blue’ on them. There are equal numbers of balls in all 3 buckets; one of them has only red, one of them has only blue and other one has both blue and red balls. How many minimum numbers of attempts are required to correct the labels?

Ans: This is not a probability question. Only one ball needs to be picked up from bucket with ‘Red+Blue’ label. If that ball is ‘Red’ then that bucket should contain all the red balls. Since the label is a false label. Now bucket with ‘Blue’ label can be either ‘Red’ or ‘Red+Blue’, but we already know ‘Red’ bucket so it must be ‘Red+Blue’ and then remaining bucket must be corrected with ‘Blue’.

Vice versa if the ball picked up is ‘Blue’ then that bucket is ‘Blue’. ‘Red’ bucket is ‘Red+Blue’ and ‘Blue’ bucket is ‘Red’.

4. You have 3 buckets which can carry 10, 7 and 3 liters each. You have 10 liter of water. Divide the water as 5 liters in 2 buckets.

Ans:

10  7   3

———

10  0   0

3    7   0

3    4   3

6    4   0

6    1   3

9    1   0

9    0   1

2    7   1

2    5   3

5    5   0

Python: List basic operations

August 16, 2016

The program below is a solution to google’s python exercise which contains basic list operations.


# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.

def match_ends(words):
# +++your code here+++
string_counter = 0
for word in words:
if (len(word) >= 2):
if (word[0] == word[len(word)-1]):
string_counter += 1

return string_counter

# front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with ‘x’ first.
# e.g. [‘mix’, ‘xyz’, ‘apple’, ‘xanadu’, ‘aardvark’] yields
# [‘xanadu’, ‘xyz’, ‘aardvark’, ‘apple’, ‘mix’]

def front_x(words):

x_list = []
non_x_list = []
for word in words:
if (word[0] == “x”):
x_list.append(word)
else:
non_x_list.append(word)

x_list.sort()
non_x_list.sort()

for i in range(len(non_x_list)):
x_list.append(non_x_list[i])

return x_list

# sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]

def sort_last(tuples):
# +++your code here+++
my_dict = {}
last_items = []
for my_tuple in tuples:
last_items.append(my_tuple[len(my_tuple)-1])
my_dict[my_tuple[len(my_tuple)-1]] = my_tuple
last_items.sort()
#print (my_dict)
#print (“%s” %last_items)
sorted_items = []
for key in last_items:
sorted_items.append(my_dict[key])
#print (“%s ” %sorted_items)

return sorted_items

# Simple provided test() function used in main() to print
# what each function returns vs. what it’s supposed to return.
def test(got, expected):
if got == expected:
prefix = ‘ OK ‘
else:
prefix = ‘  X ‘
print (‘%s got: %s expected: %s’ % (prefix, repr(got), repr(expected)))

# Calls the above functions with interesting inputs.
def main():
print (‘match_ends’)
test(match_ends([‘aba’, ‘xyz’, ‘aa’, ‘x’, ‘bbb’]), 3)
test(match_ends([”, ‘x’, ‘xy’, ‘xyx’, ‘xx’]), 2)
test(match_ends([‘aaa’, ‘be’, ‘abc’, ‘hello’]), 1)

print ()
print (‘front_x’)
test(front_x([‘bbb’, ‘ccc’, ‘axx’, ‘xzz’, ‘xaa’]),
[‘xaa’, ‘xzz’, ‘axx’, ‘bbb’, ‘ccc’])
test(front_x([‘ccc’, ‘bbb’, ‘aaa’, ‘xcc’, ‘xaa’]),
[‘xaa’, ‘xcc’, ‘aaa’, ‘bbb’, ‘ccc’])
test(front_x([‘mix’, ‘xyz’, ‘apple’, ‘xanadu’, ‘aardvark’]),
[‘xanadu’, ‘xyz’, ‘aardvark’, ‘apple’, ‘mix’])

print ()
print (‘sort_last’)
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])

if __name__ == ‘__main__’:
main()

Python: List exercises

August 16, 2016

Below is the python program solution of google’s list exercise.


# Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
# +++your code here+++
new_dict = {}
new_nums = []
for num in nums:
new_dict[num] = “”
for key in new_dict:
new_nums.append(key)
return new_nums

# Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in “linear” time, making a single
# pass of both lists.
def linear_merge(list1, list2):

new_list = []
while len(list1) > 0 and len(list2) > 0:
if list1[0] < list2[0]:
new_list.append(list1.pop(0))
else:
new_list.append(list2.pop(0))
new_list.extend(list1)
new_list.extend(list2)

”’while len(list1) > 0 and len(list2) > 0:
if (list1[-1] > list2[-1]):
new_list.append(list1.pop(-1))
else:
new_list.append(list2.pop(-1))
new_list.extend(list1)
new_list.extend(list2)
new_list.reverse() ”’

return new_list

# Simple provided test() function used in main() to print
# what each function returns vs. what it’s supposed to return.
def test(got, expected):
if got == expected:
prefix = ‘ OK ‘
else:
prefix = ‘  X ‘
print (‘%s got: %s expected: %s’ % (prefix, repr(got), repr(expected)))

# Calls the above functions with interesting inputs.
def main():
print (‘remove_adjacent’)
test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])

print ()
print (‘linear_merge’)
test(linear_merge([‘aa’, ‘xx’, ‘zz’], [‘bb’, ‘cc’]),
[‘aa’, ‘bb’, ‘cc’, ‘xx’, ‘zz’])
test(linear_merge([‘aa’, ‘xx’], [‘bb’, ‘cc’, ‘zz’]),
[‘aa’, ‘bb’, ‘cc’, ‘xx’, ‘zz’])
test(linear_merge([‘aa’, ‘aa’], [‘aa’, ‘bb’, ‘bb’]),
[‘aa’, ‘aa’, ‘aa’, ‘bb’, ‘bb’])

if __name__ == ‘__main__’:
main()


 

Python: Counting words from input file

August 16, 2016

The python program below can be used to count words in a file, it also has an option to print top 20 most used words in a file.


import sys

def word_dictionary(filename):
fh = open(filename,’r’)
file_text = fh.read()
fh.close()
words = file_text.split()
word_dict = {}
word_count = 0

for word in words:
if word in word_dict:
word_dict[word] = word_dict[word] + 1
else:
word_dict[word.lower()] = 1
return word_dict

def print_words(filename):
word_dict = word_dictionary(filename)

for key in word_dict:
print (“word: %s and count: %s\n” %(key,word_dict[key]))

def print_top(filename):
word_dict = word_dictionary(filename)
word_dict_sorted = sorted(word_dict.items(),key= lambda x:x[1])
for i in range(1,21): #len(word_dict_sorted)):
print (“%s %d\n”%(word_dict_sorted[len(word_dict_sorted)-i][0], word_dict_sorted[len(word_dict_sorted)-i][1]))

word_dict_values = list(word_dict.values())
#print (” %s\n” %(word_dict_values))
word_dict_values.sort()
word_dict_values.reverse()
#print (” %s\n” %(word_dict_values))

return

###

# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions
def main():

if len(sys.argv) != 3:
print (‘usage: ./wordcount.py {–count | –topcount} file’)
sys.exit(1)

option = sys.argv[1]
filename = sys.argv[2]
if option == ‘–count’:
print_words(filename)
elif option == ‘–topcount’:
print_top(filename)
else:
print (‘unknown option: ‘ + option)
sys.exit(1)

if __name__ == ‘__main__’:
main()

———————————————————————-

Python: List comprehension in Python

August 4, 2016

to_one_hundred = range(101)
print (*to_one_hundred  )

backwards_by_tens = to_one_hundred[100:0:-10]
print (  *backwards_by_tens)

to_21 = range(1,22)
print (*to_21)
odds = [x for x in to_21 if (x%2 !=0)]
print (*odds)
middle_third = to_21[7:14]
print (*middle_third)

languages = [“HTML”, “JavaScript”, “Python”, “Ruby”]
print (*(x for x in languages if x == “Python”))
print filter(lambda x: x == “Python”, languages)

Python: Palindrome program in Python

August 4, 2016

def palindrome_test(word):

flag_palindrome = True
if (len(word) >= 2):
for i in range(0, int(len(word) / 2)):
if (word[i] == word[len(word) – (i + 1)]):
flag_palindrome = True
continue
else:
print (“String is not palindrome”)
flag_palindrome = False
break
else:
print (“The string you provided does not have more than or 2 characters”)
flag_palindrome = False

if (flag_palindrome):
print (“String you entered is palindrome”)

str_to_test = input(‘Enter a string: ‘)
palindrome_test(str_to_test)

Python: Method overriding example in Python

August 4, 2016

class Employee(object):
“””Models real-life employees!”””
def __init__(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

class PartTimeEmployee(Employee):
def full_time_wage(self,hours):
return super(PartTimeEmployee,self).calculate_wage(hours)
def calculate_wage(self,hours):
self.hours = hours
return hours*12.00

milton = PartTimeEmployee(“milton”)
full_time_wage = milton.full_time_wage(10)
print (full_time_wage)

Python: Simple example of creating class and functions in it

August 4, 2016

class ShoppingCart(object):
“””Creates shopping cart objects
for users of our fine website.”””
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name

def add_item(self, product, price):
“””Add product to the cart.”””
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + ” added.”
else:
print product + ” is already in the cart.”

def remove_item(self, product):
“””Remove product from the cart.”””
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + ” removed.”
else:
print product + ” is not in the cart.”

my_cart = ShoppingCart(“Kedar”)
my_cart.add_item(“fruit”,30)

Python: Example of using functions

August 4, 2016

lloyd = {
“name”: “Lloyd”,
“homework”: [90.0, 97.0, 75.0, 92.0],
“quizzes”: [88.0, 40.0, 94.0],
“tests”: [75.0, 90.0]
}
alice = {
“name”: “Alice”,
“homework”: [100.0, 92.0, 98.0, 100.0],
“quizzes”: [82.0, 83.0, 91.0],
“tests”: [89.0, 97.0]
}
tyler = {
“name”: “Tyler”,
“homework”: [0.0, 87.0, 75.0, 22.0],
“quizzes”: [0.0, 75.0, 78.0],
“tests”: [100.0, 100.0]
}

def average (numbers):
total = sum(numbers)
return float(total)/len(numbers)

def get_average(student):
homework = average(student[“homework”])
quizzes = average(student[“quizzes”])
tests = average(student[“tests”])
return (homework * 0.1) + (quizzes * 0.3) + (tests * 0.6)
def get_letter_grade(score):
if (score >= 90):
return “A”
elif (score >= 80):
return “B”
elif (score >= 70):
return “C”
elif (score >=60):
return “D”
else:
return “F”
def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)

letter_grade = get_letter_grade(get_average(lloyd))
students = [lloyd,alice,tyler]
class_average = get_class_average(students)
print (“%.10f” %class_average)
print letter_grade