How many answers? - livewires

So,again I'm making a tables (math tables) checker to check your answers. I've used the search but nothing I found is relevant.
def math():
for f in range (3):
right=0
wrong=0
x=10
c=5
p=x*c
print x,'times',c
v=read_number('What is the answer?')
if p==v:
right=right+1
print 'You got it right!'
else:
wrong=wrong+1
print 'You got it wrong.'
for h in range (1)
print 'You got',right,'right, and',wrong,'wrong'
The problem is, when I do this, I get the last one wrong to test it, and it says: 'You got 0 right and 1 wrong' like it's not registering the answers. What am I doing wrong?

Looks like a scope issue to me.
def math():
for f in range (3):
right=0
wrong=0
should be
def math():
right=0
wrong=0
for f in range (3):
so you don't reset right and wrong for each question.

Related

How to reference UDF's and use return function?

I'm having great difficulty on a seemingly simple task... I created this one UDF to calculate the factorial of a given variable, then I need to reference this UDF from a different file which calculates Euler's number. I've tried everything I can think of, but nothing works, except displaying my 'error' message... Here's the two codes if it would help...
(fact_sub.py file)
'''
def MyFactorial(x):
q=1 # define q for future 'for' loop
if x<0: #test whether value is + or -
from colorama import Back, Style #import colorama, allowing for special effects
print(Back.RED + '\n\nError: negative integer') #print error message with red background
print(Style.RESET_ALL) #undoes colour change
else:
for a in range(1,x+1): #initiate for loop
q = a*q #set new q to old q *a (sequential values from list)
return q
'''
(Euler's.py file)
'''
from fact_sub import MyFactorial
def main():
lst_=([])
print("Enter positive integer value 'k' to calculate Euler's number and see percent accuracy.")
k=int(input('\nEnter value for k: '))
if k < 0:
MyFactorial(k)
else:
for x in range(1,k+1):
a=1/(MyFactorial(x))
lst_.append(a)
euler_lst=sum(lst_)
print(euler_lst)
'''
I hope that all makes sense... I've been looking at this problem too long, so if the logic is flawed, please tell me! Any help appreciated, TIA!
Mitchell

Unable to find a correct output for the two-sum problem

Please mention the logical error in the below code as I am not getting a correct output. Also, do share the correct one to get an output of the indices only.
def find2Sum(A,X):
n=len(A)
for i in range(0,n):
l=[]
if X-A[i] in A:
l.append(i)
return l
nums = [1,4,6,44, 9,8]
target = 14
find2Sum(nums,target)
#Pradeepta Sahu
When you have target=8 the answer for nums=[1,4,6,44, 9,8] should be none because there are no such numbers. But with your code logic X-A[i] in A this for i = 1 will result into 8-4==4 and it will append index to L. This is the main logical bug in the code that you have written. Any number that is target/2 will be passed by your condition.
Aside this you also declared your list var inside the for loop but you are returning it outside the for loop.
This is wrong
for i in range(0,n):
l=[]
This is right
l=[]
for i in range(0,n):

Question regarding a self made number guessing game

I am trying to learn python since 2 days now and I am challenging myself with this little python projects from this website: https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/#1_Mad_Libs_Generator
I am at the second game now (number guessing game).
The instruction is as follows:
'''Make a program in which the computer randomly chooses a number between 1 to 10, 1 to 100, or
any range. Then give users a hint to guess the number. Every time the user guesses wrong,
he gets another clue, and his score gets reduced. The clue can be multiples, divisible,
greater or smaller, or a combination of all.
You will also need functions to compare the inputted number with the guessed number, to compute
the difference between the two, and to check whether an actual number was inputted or not in this python project.'''
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
guess = int(input("Enter a guess: "))
guess_count += 1
if guess < number:
print("Your guess is too small. Try again.")
elif guess > number:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You loose!")
else:
print("Your guess is correct. You Won!")
The output looks like this:
Welcome to the number game. A random number will be generated and you can guess which one it is.
You got three tries.
Enter a guess: 78
Your guess is too high. Try again.
Enter a guess: 28
Your guess is too small. Try again.
Enter a guess: 29
**Your guess is too small. Try again.**
You are out of guesses. You loose!
My problem is the line marked in strong. Actually, after the user entered the third try and did not guess the correct answer, I don't want the line "your guess is too ..." to be displayed. However, before the user is out of tries, I do want it to be displayed.
Do you got any hints on how to adjust the code?
Also, I did understand the concept of try and except, but don't really know where exactly to add it to make the game more "smooth" with regard to entering a wrong input type.
Kind Regards
Given the current code structure, you can avoid printing the hints on the last guess by adding an additional check in the guess and number comparison.
Regarding exception handling, the crash points of the program involve the comparison between user input and the number. Adding exception handling around the integer conversion of user input seems appropriate. Doing this before incrementing guess_count and a continue to allow for another user input will allow the game to run for 3 valid inputs.
The _ variable being used to refer to the exception is a 'throwaway' variable - this is just a conventional name. In an interpreted session, however, _ would store the return value of the previously executed statement.
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
try:
guess = int(input("Enter a guess: "))
except ValueError as _:
print('Wrong input type')
continue
guess_count += 1
if guess < number and guess_count != guess_limit:
print("Your guess is too small. Try again.")
elif guess > number and guess_count != guess_limit:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You lose!")
else:
print("Your guess is correct. You Won!")

Compare two arrays: one contais sole words, the other contains phrases. some made of those words, some not [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
While I thought it was going to be straightforward as doing a comparison of arrays it is not working as expected. They can only be compared with a regex pattern.
EXAMPLE of what the two arrays look like:
first array contains lone words like, house, cat, dog etc. The second string contains phrases "I have a house", "i have a cat". So the point is to see what words of first array are contained in the second array that has the phrases
SAMPLE ARRAY WORDS: {house, dog, cat, man, girl, etc}
SAMPLE ARRAY PHRASES: {"I have a house", "I am a dog", "I am man" etc}
I have gone through all the array methods in the documentation here
https://docs.ruby-lang.org/en/2.0.0/Array.html
Is not to use subtraction of arrays to see differences, we are not talking about numbers. It is not to check if some are included because the boolean is not an answer to me and besides,
The bad and strange result that I am getting is that it prints me out the full of the second array as if everything from the first array was contained there, which is not the case.
I have tried 3 variants, .each, select, and for.
Note: if instead of using a variable I hardcode a string that I know it is part of the second array, it gets me the results fine. Also, IF I write a variable and I assign it the value by hand such as this: item = house and they put it into the pattern of the regex, it also works! so the problem would seem to be that somehow the items are not being extracted from the first array, but that is not the case because I tried printing them and they print out fine. So, if they are correctly extracted from the first array, and they work if I assign by hand the value of the variable, why can't I just assign automatically the values to the variable as they come out of the first array? that is what drives me insane. 8 hours so far.
The code is not long, only 4 lines, I have included multiple approaches I have tried. 5 actually
TAKE NUMBER ONE:
words= Array.new
File.open('mtos-array.txt').each { |line| linesdb << line }
phrases = Array.new
File.open('out23.txt').each { |line| fcia << line }
$x = 0
for item in words do
for mto in phrases
if(mto =~/#{item}/)
puts"it is contained in #{mto}"
end
end
puts $x
$x +=1
end
TAKE NUMBER TWO
x = words.select {|num| num}
phrases.each {|a|
if(a =~/#{x}/)
puts"coincide com #{a}"
end
}
THIS THIRD TAKE very compact does not work either. It prints me out the full of the second array (linesdb). I would have wanted to print ONLY if x is contained in v
x = words.select {|num| num}
puts(phrases.select {|v| v =~ /#{x}/})
TAKE NUMBER 4
This harcoded value works, only that I need variables instead but insanely cant have them work. To make it even clearer: Suppose the word house comes from the first array, it indeed finds me all the phrases in the second array that contain the word "house".
num = "house"
phrases.each {|a| if(a =~/#{num}/)
puts"coincide en #{a}"
end
}
TAKE NUMBER 5
again it prints me out the full second array
for item in words do
phrases.each {|a| if(a =~/#{item}/)
puts"it is contained in en #{a}"
end
}
end
words = ["house", "dog", "cat", "man", "girl"]
phrases = ["I have a house", "I am a dog", "I am man"]
words.select { |word| phrases.any? { |phrase| phrase.include? word } }
#=> ["house", "dog", "man"]

Can't assign to operator?

Several questions have the same error, but I'm just starting Python and don't understand it.
I'm trying to create a program which generates two random numbers, nicknames these numbers, asks the user what the answer is, multiplies the two numbers and gives a nickname to THAT number, then it reads the user's answer and sees if the user's answer is the same as the one it got. I started with a simpler program that asks the same question three times.
My program is the following:
def math ():
for f in range (3):
x=10
c=5
x*c=p
print x,'times',c,'.'
v=read_number('What is the answer?')
if p==v:
print 'You got it right!'
else:
print 'You got it wrong.'
And now that I look at it line 6 it is unnecessary. But when I finish it Python says 'SyntaxError: can't assign to operator.'
It also highlights after c=5. Why does this happen and how can I fix it?
The
x*c=p
should read
p=x*c
This multiplies x by c and assigns the result to p.
you use randint() from the random module to generate random numbers, for example:
from random import randint
x = randint(0,10) # random between 0 and 10
c = randint(0,10)
p = x * c
print p

Resources