r/pythonhelp • u/user101dt • Oct 18 '20
hw challenge question(pls help)
Create a text document called names.txt that contains a list of 20 names, each on its own line. Write a program that reads the names from names.txt and then generates a file called shuffle.txt that contains the names listed in random order. (Do not use the .shuffle() build in list method)
1
Oct 19 '20 edited Oct 19 '20
Alright so you should start by breaking the problem down. First you need to open the file and extract the list of names, shuffle it, make a new file and write the list to it.
You could use open() and .close() to open names.txt and make shuffle.txt but for the sake of simplicity let's handle it with with open() as var
Goes like this:
from random import randint
nameList = []
with open("names.txt","r") as f: #assuming your file is in the same directory
for name in f.readlines():
nameList.append(name)
#we're gonna be shuffling the list using a very popular way, the Fisher-Yates algorithm
listRange = range(0, len(nameList))
for i in listRange:
j = randint(listRange[0], listRange[-1])
nameList[i], nameList[j] = nameList[j], nameList[i]
#our list is now shuffled, let's go ahead to the third part and make a new file
with open("shuffle.txt","w") as f:
for name in nameList:
f.write(name)2
6
u/Darkmatter_Cascade Oct 18 '20
Seems pretty straightforward. It seems to me that there are three parts to the program you need to write. What are the three parts? Can you do any of the three parts of the program?