Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

def names(): with open(\'names.txt\') as f: words = [i.strip().lower() for i in

ID: 3698737 • Letter: D

Question

def names():
    with open('names.txt') as f:
        words = [i.strip().lower() for i in f.read().split()]
        return dict(zip(words[:-1], words[1:]))
      


is what i have so far, but im getting double names. the text file itself is single word per line such as

Name1

name2

name 3

(Without the spaces)

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). (10 points)

Explanation / Answer

def createDictionary():

    dict = {}

    # open file in read mode

    fptr = open('names.txt', 'r')

   

    # read the content of file into names

    names = fptr.read()

   

    i = 1

   

    # read the contents of file line by line

    for x in names.split(' '):

   

        # add name to dictionary

        dict[i] = x

       

        i += 1

       

    return dict

   

def isPrime(n):

    if n < 2:

   

        return False

       

    if n == 2:

   

        return True

       

    for i in range( 2, n ):

   

        # if n is divisible by i

        if int( n % i ) == 0:

       

            return False

           

    return True

   

dict = createDictionary()

# open file in write mode

fptr = open('namesprime.txt', 'w')

# read the key set of dict

for key in dict.keys():

    # if current key is prime

    if isPrime(key):

   

        # write the current name to file

        fptr.write( str( dict[key] ) + ' ' )

------------------------names.txt-----------------------------

Name1
Name2
Name3
Name4
Name5
Name6
Name7
Name8
Name9
Name10
Name11

----------------------------namesprime.txt----------------------------

Name2
Name3
Name5
Name7
Name11