Write a Python program that will read the names contained in “names.txt” and ins
ID: 3738152 • Letter: W
Question
Write a Python program that will read the names contained in “names.txt” and insert them into a dictionary. They key values will be integers such that the first name will have key value 1, the second will have key value 2, the third will have key value 3 etc. Once the dictionary has been constructed, go through it and write the names that have prime key values into a new file called “namesprime.txt”. That is, only the names that have a key which is a prime number are written to “namesprime.txt”. You will have to create a function to determine whether an integer is prime or not. One way is to create an array of primes between 2 and 57 and check the value against those values. Another way is to go through all integers less than the key value and see if they divide it (really you only need to check integers from 2 to sqrt(number) to determine if it’s prime). Names.txt file has random name so you can put any name to create that file before writing code Write a Python program that will read the names contained in “names.txt” and insert them into a dictionary. They key values will be integers such that the first name will have key value 1, the second will have key value 2, the third will have key value 3 etc. Once the dictionary has been constructed, go through it and write the names that have prime key values into a new file called “namesprime.txt”. That is, only the names that have a key which is a prime number are written to “namesprime.txt”. You will have to create a function to determine whether an integer is prime or not. One way is to create an array of primes between 2 and 57 and check the value against those values. Another way is to go through all integers less than the key value and see if they divide it (really you only need to check integers from 2 to sqrt(number) to determine if it’s prime). Names.txt file has random name so you can put any name to create that file before writing codeExplanation / Answer
#function to check if a number is prime
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
#opening the file
f = open('input.txt','r')
filedata = []
filedata = f.read().strip().split()
i = 1
#mapping indexes and storing into dictonary
dc = {}
for string in filedata:
dc[i] = string
i += 1
f.close()
#writing words with prime indexes into the file
f2 = open('namesprime.txt','w')
for ind in range(2,len(dc)):
if is_prime(ind):
f2.write(dc[ind]+" ")
f2.close()
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.