AMS 209: HW 5: Problem 1ΒΆ

  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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
# coding: utf8

'''
Created on November 6th, 2017

@author: Geetanjali
'''


def readNWordsintoList(filename, N):
	"""
	:param filename: name of file from which words are read
	:param N: number of words to be read from the file
	:return word_list: a list of N words from the file
	"""

	f = open(filename, "r")
	i = 0
	word_list = []
	for line in f:
		if(i > N):
			break
		line = line.strip()
		word_list.append(line)
		i = i+1
	f.close()
	return word_list

def readAllWordsintoList(filename):
	"""
	:param filename: name of file from which words are read
	:return word_list: a list of all words from the file
	"""

	f = open(filename, "r")
	word_list = []
	for line in f:
		line = line.strip()
		word_list.append(line)
	f.close()
	return word_list

def readNWordsintoDict(filename, N):
	"""
	:param filename: name of file from which words are read
	:param N: number of words to be read from the file
	:return word_dict: a dictionary of N words from the file
	"""

	f = open(filename, "r")
	i = 0
	word_dict = {}
	for line in f:
		if(i > N):
			break
		line = line.strip()
		word_dict[line] = 1
		i = i+1
	f.close()
	return word_dict

def readAllWordsintoDict(filename):
	"""
	:param filename: name of file from which words are read
	:return word_dict: a dictionary of all words from the file
	"""

	f = open(filename, "r")
	word_dict = {}
	for line in f:
		line = line.strip()
		word_dict[line] = 1
	f.close()
	return word_dict

def checkWord(word_dict, word):
	"""
	:param word_dict: a dictionary of all words from the file
	:param word: word to be checked if it exists in dictionary
	:return: returns True if word exists in the dictionary, False otherwise
	"""

	if(word in word_dict):
		return True
	else:
		return False


if __name__ == '__main__':

	filename = "words.txt"
	N = int(input("Enter the number of words to be read: "))
	print("Printing as list...")
	print(readNWordsintoList(filename, N))
	print("Printing as dictionary...")
	word_dict = readNWordsintoDict(filename, N)
	print(word_dict)

	printFlag = input("\nDo you want all the words to be printed to screen? (y/n): ")
	if(printFlag == "y"):
		print("All words: ")
		print(readAllWordsintoList(filename))

	word = input("\nEnter a word to be looked up in the dictionary: ")
	if(checkWord(word_dict, word)):
		print("Exists in dictionary.")
	else:
		print("Does not exist in dictionary!")