I tried to run this program but it seems time only exit code 0.
if __name__ == '__main__':
import random
f = open("quiz.csv", 'r')
Counter =0
Content = f.read()
Colist = Content.split("\n")
qlist=[]
calist=[]
adict={}
alist=[]
c=0
for i in Colist:
if i:
if (Counter%5 ==0):
if(Counter!= 0):
x = alist[0]
random.shuffle(alist)
calist.append(alist.index(x))
c+=1
alist=[]
qlist.append(i)
else:
alist.append(i)
Counter+=1
x = alist[0]
random.shuffle(alist)
adict[c]= alist
calist.append(alist.index(x))
congo =["Goodjob!","awesome!","correct"]
cnt = 0
for i in range(len(qlist)):
print("\n question", i + 1)
print("-------")
print(qlist[i])
for j in range (len(adict[1])):
print(j+1, "->", adict[i][j])
ch = int(input("enter your choice: "))
if ((ch-1)==calist[i]):
random.shuffle(congo)
print(congo[0])
cnt+=1
else:
print("sry you chose the wrong option! the correct option is",calist[i]+1)
#print("\n End of quiz ! your score is", round(cnt/len(qlist)*100,2))
Can some one tell me what's wrong with this code? It's a school project which I need submit within 2 days time. Please give me some advice on this as I'm stuck at this stage for a long period of time.
Your loop is not correct. You're not saving the first question. I would skip reading and splitting the file, and just let the standard file do it.
counter = 0
qlist = []
alist = []
for line in open("quiz.csv"):
if line:
if counter % 5 == 0:
qlist.append( line )
alist.append( [] )
else:
alist[-1].append( line )
if counter % 5 == 4:
x = alist[-1][0]
random.shuffle(alist[-1])
calist.append(alist[-1].index(x))
counter += 1
Now you have qlist as the list of questions, alist as a list of lists, where entry [i] has the answers that map to question i, and calist has the index of the right answer.
Note that for this change to work, you must delete your "open", your "read", and your "split".
Related
I am trying to make a random word/phrase generator that is like the one that bitwarden has (in python3). But the issue I am running into and need some help with is the addition of 1 number at the end of 1 of the words that is shown.
Something like this Referee-Outrank-Cymbal-Cupping-Cresting-Fiber7-Expensive-Myth-Unveiling-Grasp-Badland-Epiphany-Simplify-Munchkin-Pastrami-Spiffy-Gladly-Skeptic-Retouch-Buckskin
What is very important here is that the number is "random" and the word it is attached to is "random".
Code I have written so far:
Word list I am using is https://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain but without ' in any of the words.
#pycryptodome==3.15.0
from Crypto.Random import random
import beaupy
import os
def clear():
os.system('clear||cls')
def main():
while True:
try:
number = int(beaupy.prompt("How many words?: "))
except ValueError as e:
print(f'Oops! Something went wrong.\nError: {e}\n\n')
input('Press "enter" to continue...')
clear()
continue
if number > 20 or number < 3:
print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
input('Press "enter" to continue...')
clear()
else:
break
cwd = os.getcwd()
word_path = f"{cwd}/words.txt"
with open(word_path, 'r') as fh:
words = fh.read().lower()
word_list = words.splitlines() #list of words
sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
if sep == '' or sep == ',':
sep = '-'
#Returns True or False. Basically Yes or No?
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
c_lst.append(i.title())
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
#I don't know what to do here... but I need to have a version with the number and one without. (default)
if __name__ == '__main__':
clear()
main()
I am not exactly familiar with string manipulation and searching for answers online just isn't giving me any help with the very specific thing I'm trying to do. All I want is for 1 word in the resulting string to have a "random" number attached to it.
I don't know if I need to re order my code and have it be done a different way. I am having such a headache with this. Any help would be great.
Edit#1
Additional and unrelated note, If anyone knows of a better word list to use, please let me know!
If I am understanding correctly, here is a solution:
#Returns True or False. Basically Yes or No?
capital_words = ''
default_words = ''
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
c_lst.append(i.title())
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
#I don't know what to do here... but I need to have a version with the number and one without. (default)
word_index = random.randint(0, number - 1) # Get random index that is in the word list
if default_words != '':
word_with_number = default_words.split(sep)
else:
word_with_number = capital_words.split(sep)
word_with_number[word_index] = word_with_number[word_index] + str(rn_num)
word_with_number = sep.join(word_with_number)
print(word_with_number)
if default_words != '':
print(default_words)
else:
print(capital_words)
OUTPUT:
detroit-elide-windbag-purge-tort-mortician-codex7-annex-fairy-suntanning
detroit-elide-windbag-purge-tort-mortician-codex-annex-fairy-suntanning
With some help from AnonymousFrog. I was able to get my code working.
The following is the now working code.
from Crypto.Random import random
import beaupy
import os
def clear():
os.system('clear||cls')
def main():
while True:
try:
number = int(beaupy.prompt("How many words?: "))
except ValueError as e:
print(f'Oops! Something went wrong.\nError: {e}\n\n')
input('Press "enter" to continue...')
clear()
continue
if number > 20 or number < 3:
print("20 words is the maximum number of words you can use. And 5 words is the minimum.\n\n")
input('Press "enter" to continue...')
clear()
else:
break
cwd = os.getcwd()
word_path = f"{cwd}/words.txt"
with open(word_path, 'r') as fh:
words = fh.read().lower()
word_list = words.splitlines() #list of words
sep = beaupy.prompt('Line separator? (leave empty for default "-"): ')
if sep == '' or sep == ',':
sep = '-'
#Returns True or False. Basically Yes or No?
capital_words = ''
default_words = ''
if beaupy.confirm("Capitalize?"):
"""Make list of words with the first letter capitalized."""
c_lst = []
for i in word_list:
if len(i) < 3 or len(i) > 9:
pass
else:
c_lst.append(i.title())
cap = True
capital_words = f'{sep}'.join(random.choice(c_lst) for _ in range(number))
else:
cap = False
default_words = f'{sep}'.join(random.choice(word_list) for _ in range(number))
if beaupy.confirm("Number?"):
num = True
rn_num = random.randint(0, 9) # <-- Get a random number to be used with only 1 of the words defined in capital_words or default_words below.
word_index = random.randint(0, number - 1) # Get random index that is in the word list
if default_words != '':
word_with_number = default_words.split(sep)
else:
word_with_number = capital_words.split(sep)
word_with_number[word_index] = word_with_number[word_index] + str(rn_num)
word_with_number = sep.join(word_with_number)
else:
num = False
if cap == True and num == False:
print(capital_words)
if cap == False and num == False:
print(default_words)
if num == True:
print(word_with_number)
Thanks for the help!
(if anyone knows of a better word list to use, feel free to let me know)
I need to check whether 2 lists match in order, e.g. ['h', 'i', '2'] and ['h', 'i', '2'] would be a match.
I am trying a range of things and am trying list1 == list2 but that doesnt work for some reason and im not too sure why.
I have also tried collection counters and that did work but it also worked for lists that werent in order so not useful
I have had to do some wierd layout stuff by changing it from tuples to lists but the lists match completely, they are just not flagged when they do match.
class passwordCracker:
def __init__(self, password):
self.password = password
self.characters = []
self.passwordLength = len(password)
def characterFinder(self):
letters = string.printable
letters = [char for char in letters]
start = time.time()
with open("common_passwords.csv") as f: #cracking password using a dictionary attack
reader = csv.reader(f)
commonWords = list(reader) #putting common passwords in a list
passwordList = [self.password]
print(passwordList)
counter = 0
found = False
for i in range(len(commonWords)): #looping through common passwords
lengthOfList = len(commonWords)
if commonWords[i] == passwordList: #if passwords match
print("password cracked: " + self.password)
end = time.time()
print(f"Password cracked in {end - start}") #print message
found = True
break #break from for loop
else:
counter = counter + 1
if counter == lengthOfList: #if end of list reached
break #break from for loop
# passwordSplit = [char for char in self.password]
passwordTuple = tuple(self.password)
count = 0
checker = 0
if found == False:
for i in range(0, len(letters)+1):
for x in itertools.combinations(letters, i):
if found == False:
count=count+1
print(count)
passwordTuple = list(passwordTuple)
print(passwordTuple)
variable = list(x)
print(variable)
if passwordTuple == variable:
for i in range(1000000):
print("HELLO")
print("password cracked: " + self.password)
end = time.time()
print(f"Password cracked in {end - start}") # print message
found = True
break # break from for loop
password = input("Please enter the tested password: ")
test2 = passwordCracker(password)
test2.characterFinder()
example list below
An easier way to do this could be by sorting the lists and then using Collections counter. Make sure you import collections
list1.sort()
list2.sort()
if collections.Counter(list1) == collections.Counter(list2):
print ("The lists are identical")
else :
print ("The lists are not identical")
My intent is to read a list from a file, pick a random number from that list and remove it, then resave the list. Sometimes the function works fine, sometimes not.
choices=[]
with open("C:\\choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices)==0:
choices=[0,1,2,3,4,5]
num=rdm.randint(0,5)
def chooseline(myList, myNum):
print("before if num= "+str(myNum))
if not myNum in myList:
myNum=rdm.randint(0,5)
chooseline(myList,myNum)
print("In NOT-IF num= "+str(myNum))#<-- Need to move before chooseline to print. ok
else:
myNum=myList.pop(myList.index(myNum))
print("in Else num= "+str(myNum))
print("end num= "+str(myNum))
return myNum
newnum= chooseline(choices,num)
with open("C:\\choices.txt", "w") as f:
for e in choices:
f.write(str(e) +"\n")
As long as the random number is in the list the function returns as expected, but if the first number is not on the list, it seems to loop back.
runfile('...')
before if num= 0
in Else num= 0
end num= 0
runfile('...')
before if num= 2
in Else num= 2
end num= 2
runfile('...')
before if num= 2 #ok not in list
before if num= 0 #ok chooses new number, but not in list
before if num= 4 # chose 4, in list
in Else num= 4 # as expected
end num= 4 #<----- expect to stop here and return 4
In NOT-IF num= 4
end num= 4 #
In NOT-IF num= 0
end num= 0
There is an easier and more efficient approach ...
import random
lines = []
with open('choices.txt', 'r') as file:
for line in file:
lines.append(int(line.rstrip()))
file.close()
with open('choices.txt', 'w') as file:
if len(lines) > 1:
number = lines[random.randint(0, len(lines) - 1)]
for line in lines:
if line != number:
file.write(f'{line}\n')
file.close()
Example without the recursion as mentioned in the comments:
import random
choices = []
with open("choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices) == 0:
choices = [0, 1, 2, 3, 4, 5]
num = random.randint(0, 5)
def choose_num_in_list(max_attempts=100):
chosen_number = -1
attempts = 0
while chosen_number == -1 and attempts < max_attempts:
candiate_number = random.randint(0, 5)
attempts = attempts + 1
if candiate_number in choices:
chosen_number = candiate_number
return chosen_number
newnum = choose_num_in_list()
if(newnum != -1):
choices.pop(choices.index(newnum))
print(f"Removed {str(newnum)} from the list")
else:
print("Failed to remove a number from the list")
with open("choices.txt", "w") as f:
for e in choices:
f.write(str(e) + "\n")
I am building a Hangman game. The code that I wrote prints the 'updated target word' multiple times if a letter occurs multiple times.
Example: the target word is 'celebrate'. If I guess e then it prints
*e******
*e*e****
*e*e***e
I would like to avoid printing the first two printouts and only print the third and most updated version.
import random
import re
word_list = ["fireboard", "identical", "chocolate", "christmas", "beautiful", "happiness", "wednesday", "challenge", "celebrate"]
random_pick = random.choice(word_list)
random_pick_a = re.sub("[a-z]","*", random_pick)
random_pick_list_a = list(random_pick_a)
print(random_pick)
count = 0
def main_function():
global count
while count <= 9:
user_input = str(input("type a letter:"))
for i, c in enumerate(random_pick):
if c == user_input.casefold():
random_pick_list_a[i] = user_input.casefold()
random_pick_list_b = ''.join(random_pick_list_a)
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
else:
continue
else:
if user_input.casefold() not in random_pick:
count = count+1
print(count)
if count == 10:
print("sorry")
exit()
main_function()
Disclaimer: I am in my first weeks of coding!
No need to str() the input(), it's already a string. So strip str(input("type a letter:")) to input("type a letter:").
No need in
else:
continue
it will continue even without it. Don't use globals, just move your count into main_function().
Don't do if count == 10, you're already doing it in while count <= 9.
As for your question - move the block
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
out of the for-loop. So the whole thing would look like this:
def main_function():
count = 0
while count <= 4:
user_input = input("type a letter:")
for i, c in enumerate(random_pick):
if c == user_input.casefold():
random_pick_list_a[i] = user_input.casefold()
random_pick_list_b = ''.join(random_pick_list_a)
print(random_pick_list_b)
if random_pick_list_b == random_pick:
print("done")
exit()
else:
if user_input.casefold() not in random_pick:
count = count+1
print(count)
print("sorry")
You have:
print(random_pick_list_b)
Inside the for loop that is checking each character for the chosen letter. So, it prints out random_pick_list_b every time it finds a match.
Move it to right after the for loop if you want to do it one time when the checking is complete.
I would do this check once before the for loop.
I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
s = searchStock(stockList, stockPrice, s)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I cant seem to get it to work. Can someone please help me?
Try adding this print to help you debug:
def searchStock(stockList, stockPrice, s):
output = -1
for i in range(len(stockList)):
if s == stockList[i]:
output = stockPrice[i]
print i, output, stockList[i], stockPrice[i]
elif s != stockList[i]:
output = -1
return output
Also I changed one of your variables, it seems better than modifying your input value and then returning it.