{Python} Generate unique integers using iteration - python

I'm making a program to collect information from the user, and to add it to a text file.
It's a program that will be used to get said information from a number of applicants.
For linearity in the results I collect, I want to randomly ask the questions.
What i'm asking is a way to pull a question from the list, ask for input, store the input in the text file, and then ask another question pulled from the list at random.
Here is my code so far:
def ques():
global quesnum
for i in questions:
num = int(random.randint(0,len(questions)-1))
j = int(numbers.count(str(num)))
while j >= 1:
num = int(random.randint(0,len(questions)-1))
##DEBUG ONLY##
print('true')
break
else:
num = str(num)
numbers.append(num)
##DEBUG ONLY##
print('false')
num = int(num)
answer = input(str(quesnum) + '. ' + questions[num] + ': ')
answers.write(str(quesnum) + '. ' + questions[num] + ': ')
answers.write(answer + '\n')
quesnum = int(quesnum + 1)
Errors:
Once the number has been used it is added to the list.
If a number has already been used, ideal situation is to generate a new number and use that instead.
I can't see any errors in my code, and as far as I can see it should work fine.
Can anyone point out a fix or suggest a better way of doing this? I have already found answers suggesting to use random.sample() but I have tried this already and can't get that working either.
Thanks in advance.

You can solve this by using random.shuffle:
import random
questions = ['Q1: ...', 'Q2: ...', 'Q3: ...']
random.shuffle(questions)
for q in questions:
answer = raw_input(q + ': ')
with open("answers.txt", "a") as myfile:
myfile.write("{}: {}\n\n".format(q, answer))
This will shuffle your questions, ask them in random order and save them to a text file. If you want to save more detailed information for each question, this will also work with a list of dicts. E.g.
questions = [
{'nr.': 1, 'text': 'Do you like horses?'},
{'nr.': 2, 'text': 'Where were you born?'}
]

Related

Lists won't produce result due to it must be a string. 8 Ball Fortune

The problem with my code is that when running it to see if the first word of the question is in the query list. It won't give anything back due to being a int. Can anyone point me towards right direction ?
import random
response = [ 'Yes, of course!',"Without a doubt,yes.",
'For sure!','Ask me later.',
'I am not sure.',
'I will tell you after my nap.',
'No Way!','I do not think so.',
'The answer is clearly NO.']
query = ['Will','Are','Is','Am','Do','Can','May']
# Global lists ^^^
def main(response,query,ran):
# The program that
print('Ask a question that can only be answered in yes or no.')
question = input()
if question(0) in query():
ran(response,query)
res = ran(response,query)
print(res)
again = input('Enter Y or y to play again. Enter N or n to exit.')
if again in ['y','Y']:
main(lists)
else:
print('This program will now close.')
def ran(response,query):
res = random.choice(response)
return res
main(response,query,ran)
The problem lies here question.index(0) in lists. You are comparing apples with pears. index will yield a number and you are comparing it with the actual definition of the lists function. You might want to rethink what you want to compare.
Secondly, you will have extra errors, you are using random.sample in a bad way, you should be doing random.sample(response, 1)[0], I'm presuming you want to pick a random response from that collection.
Thirdly, what is the lists() function supposed to do?

Python - Comparing two lists and getting incorrect results

The goal of the program is to compare a list of student answers to a list of correct answers and calculate how many are answered correctly. The answer key is stored as a list of strings, and the student answers are read from a text file and then converted to uppercase to match the answer key.
#Read student answer file
student_answers = infile.read()
#Convert student answer to all caps
student_answers = [answer.upper() for answer in student_answers]
My program runs without errors, but the results of comparing the two lists are incorrect. Only 3 of the answers are showing to be correct and there are 20 correct answers. Below is the relevant code I have so far, and I have also included a screenshot of the output Program Output Image. Only questions 1,3,5,7, and 25 should be flagged as incorrect. I have double checked both lists and they contain the correct information so its not input error. Any guidance on where I could be going wrong would be appreciated.
for studentLine, keyLine in zip(Student, TestKey):
keyAnswer = keyLine.split()
studentAnswer = studentLine.split()
#Compare student answer to test key
if studentAnswer == keyAnswer:
correct += 1
percent_score += 4
print('Good job! Question ', index + 1, 'is correct!')
index +=1
if studentAnswer != keyAnswer:
incorrect += 1
incorrect_list.append(index + 1)
print('The correct answer to question ', index + 1, 'is ', TestKey[index])
index +=1
I think you have incorrectly splitting instead of stripping.
So you should be using:
keyAnswer = keyLine.strip()
studentAnswer = studentLine.strip()

Amazon Alexa's card system and Flask-Ask

Ok im new to Alexa skill development but its going well, my skill is coming on well however, id like to add some more content in the form of a card. The data id like to populate the card with is in the form of a list. So I thought id try passing the list directly (didnt think it would work but worth a shot). There is nothing in the docs that explains passing lists to the card system. Can anyone explain how to achieve this?
The intent function looks like this:
#ask.intent('TopTenCounties')
def top_ten():
top_countries = get_top_ten_countries()
stats = []
for item in top_countries[1]:
stat = str(item[0]) + ' ' + str(item[1])
stats.append(stat)
msg = "The top ten countries are, {}".format(top_countries[0])
return statement(msg).standard_card(title='Top Ten Usage Stats:',
text=stats,
large_image_url='url.com/img.png')
Alexa's cards only take text, no other rich format is currently supported (https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/providing-home-cards-for-the-amazon-alexa-app). What's happening here is that the list is being converted to string automatically. You probably want to make your own little function to do it yourself so you have more fine control on how it's done.
def lst2str(lst, last='and'):
if len(lst)==1:
return lst[0]
else:
return ', '.join(lst[0:-1]) + ' ' + last + ' ' + lst[-1]

How to find and print out of a specific value from a list (at least i think thats what i want to do?)

if n == 0:
print('And your products are: ')
for i in inputs:
with open('items.txt') as f:
for line in f:
if i in line:
desc1 = line[9:17]
price1 = line[21:25]
print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities))
There is no error when running the code. When run, it outputs:
Our available products are:
15372185 ChocBisc
13281038 AppJuice
26419633 TomaSoup
74283187 SprRolls
Enter the product code: 74283187
SprRolls
Price = 0.90
Available Quantity = 86
Is this what you want? (Y/N) y
How much would you like? 34
Would you like to continue? (Y/N) y
Continuing!
Enter the product code: 15372185
ChocBisc
Price = 1.20
Available Quantity = 50
Is this what you want? (Y/N) y
How much would you like? 45
Would you like to continue? (Y/N) n
System Closing!
And your products are:
SprRolls 0.90 [34, 45]
ChocBisc 1.20 [34, 45]
As you can see, right at the bottom, it prints both quantities entered. I knew it was going to do this but i dont know how to rectify it. What i need it to do is to print only the quantity entered for that product code. Any help as always would be greatly appreciated. Thank you!!
Also i removed most of the script under while n == 1 since this is my coursework, and i would rather it didn't get copied or anything like that. Hopefully this still shows the relevant section of the code to the question.
I would re-write the latter part of your code to iterate through the range of values in inputs, rather than the values themselves. Then, you can call the index of the element you want to print from quantities.
As a caveat, this works in your case because the user send inputs to inputs one at a time (so, the indices of inputs correspond with the indices of quantities). You might consider a different data structure to use within this code, like a dictionary, which could store product codes and quantities as key/value pairs. Then, you can simply refer to the key of the dictionary when printing.
Here is how I would suggest changing your code:
if n == 0:
print('And your products are: ')
for i in range(len(inputs)):
with open('items.txt') as f:
for line in f:
if inputs[i] in line:
desc1 = line[9:17]
price1 = line[21:25]
print(str(desc1) + ' ' +str(price1) + ' ' + str(quantities[i]))
You're creating a new list for the quantities so at the end where you print out this list you can append it to print out only the product code of that item. Understand? I'll post the code in a little bit if I can.
You can use enumerate. For example:
for index, i in enumerate(inputs):
print(index, i)
That should print out
0, 74283187
1, 15372185
Getting the quantities is trivial: quantities[index]

Can I use a dictionary in this way

I'm currently revising for my GCSE coursework. The Task I have been asked for is a troubleshooting program, in which the user says their problem; and I evaluate their input and test it for keywords, before pulling up a text file into the code and printing the according solution.
This was my original code:
keywords = ["k1","k2","k3","k4","k5","k6","k7","k8","k9","kk"]
question_about_phone = input("What Seems to be the Problem? Please be percific but don't bombard us with too much info").lower()
file = open('code.txt','r')
solution = [line.strip(',') for line in file.readlines()]
for x in range(0, 10):
if keywords[x] in question_about_phone:
print(solution[x])
However in the middle of my Assessment I realised that u cant have it printing a solution for each keyword. So I decided to make it assign a value to a different list and then have many lines of
if list[1] and list[5] = "true:
print(Solution[1]
and so on ...
however this is inefficient ;( is there anyway i can use a DICTIONARY with values and say something along the lines of:
dictionary = [list[1] list[5], (more combos)
then something like (probably a while loop)
for x in range(0,10):
if dictionary[x] == "TRUE":
print(solutions[x])
end code
You can do
keywords = ["battery", "off", "broken"]
question_about_phone = input("What Seems to be the Problem?")
with open('code.txt', 'r') as file:
solutions = {k:line.strip(',\n') for k, line in zip(keywords, file)}
answers = [v for k, v in solutions.items() if k in question_about_phone]
if answers:
print(answers)
else:
print('Sorry, there are no answers to your question')
which, for example, with a file of
answer 4 battery
answer 4 off
answer 4 broken
...
and an input question of
What Seems to be the Problem? broken battery sunny
produces
['answer 4 broken', 'answer 4 battery']
basically solutions is built pairing the keywords and each line of the file.
Then answers is formed picking the values of those keywords that appear in the question
However, I strongly agree with Tim Seed's approach: it would be much more efficient to only look for the keywords present in the question instead of doing the opposite, since the possible answers outnumber the terms in the question.
In order to achieve that, simply change
answers = [solutions[k] for k in question_about_phone.split() if k in solutions]
You have correctly deduced that iterating through a list (array) is inefficient - and using a dictionary is an option.
So using your Example
keywords = {"k1": "Turn Power on","k2":"Turn Power Off"}
for k in ['Bad','k1','k2','bad']:
if k in keywords:
print("%s: Answer is %s"%(k,keywords[k]))
else:
print("%s: No idea what the issue is"%(k))
You should get Answers for k1,k2 - but not for the others....
Giving you output of
Bad: No idea what the issue is
k1: Answer is Turn Power on
k2: Answer is Turn Power Off
bad: No idea what the issue is
Hope that helps
I assume that there is exactly one answer per keyword (from your example code).
You can then just return after the first answer has been found, as in:
for x in range(0, 10):
if keywords[x] in question_about_phone:
print(solution[x])
return
print("No solution found, be more specific")
You can also iterate in a more general way:
for idx, kw in enumerate(keywords):
if kw in question_about_phone:
print(solutions[idx])
return

Categories

Resources