So basically what i am trying to achieve is get my program to perform a n number of iterations on one input variable(i use a for loop for this). After the for loop ends the program asks the user if they want to continue, for yes the program then asks the user for another n number of iterations to perform on the same input variable. The program then has to start the operation from where it left from the previous value, i used a dictionary for this but cant find it working. Would be great if i can get some help.
my code is pasted below:
def function(x, i):
return x**i
num_dic = {}
j = 1
while True:
if j == 1:
start = 1
n = int(input("number of iterations: "))
x = int(input("Number to perform operation: "))
for i in range(start, n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
num_dic[f"{i}"] = total
elif j > 1:
start = int(sorted(num_dic.keys())[-1]) + 1
x = sorted(num_dic.values())[-1]
n = int(input("number of iterations: "))
for i in range(start, n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
num_dic[f"{i}"] = total
j += 1
while True: # while loop for repeating program
ask = input("Do you want to continue?(Y to continue/ N to exit): ")
if ask.upper() == "Y":
break
if ask.upper() == "N":
break
else:
print("Please enter a correct operation (Y/N) ")
continue
if ask.upper() == "Y":
continue
else:
break
current output i am getting:
number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5
after this part it just doesn't do anything.
the desired output should look like:
number of iterations: 5
Number to perform operation: 2
2 ** 1 = 2
2 ** 2 = 4
2 ** 3 = 8
2 ** 4 = 16
2 ** 5 = 32
Do you want to continue?(Y to continue/ N to exit): y
number of iterations: 5
2 ** 6 = 64
2 ** 7 = 128
2 ** 8 = 256
2 ** 9 = 512
2 ** 10 = 1024
You don't need a dictionary for this operation. You just need a clean and proper while-loop that can keep track of your variables, specifically the exponent (variable j in your original code) and your number of iterations, n.
base doesn't change, so it should be left outside the while-loop, as advised by the #Blckknght's answer to this question.
exponent = 1
base = int(input("Number to perform operation: "))
n = None # initialize n to None
while True:
# logic to keep track of n in the previous loop, if there is one.
if n:
n += int(input("number of iterations: ")) # cumulatively increment n if user wishes to continue.
else:
n = int(input("number of iterations: "))
# while-loop that prints the output for a single set of x and n values
while n >= j:
print(f"{base} ** {exponent} = {base ** exponent}")
exponent += 1
# get user input for continuation
ask = input("Do you want to continue?(Y/ N): ")
# while loop to handle user input values
while ask.upper() not in ["Y", "N"]:
ask = input("Please enter a correct operation (Y/N).")
if ask.upper() == 'Y':
continue # loop back to the outer while-loop and ask for another set of user input
elif ask.upper() == 'N':
break # break if user says no
Since you only need to keep track of where you left off, there's no need to store many values in a dictionary. Just remembering the base and the last exponent used is enough. And conveniently, the variables x and i that you're using won't automatically get reset between iterations, so you can just start the next iteration from i + 1:
elif j > 1:
n = int(input("number of iterations: "))
for i in range(i+1, i + n + 1):
total = function(x, i)
print(f"{x}", "**", i, "=", total)
Indeed, you could probably simplify things so that you don't need a special case for the first iteration. Just ask for the base before the loop starts! Here's how I'd do it (using more descriptive variable names too):
base = int(input("Number to perform operation: "))
start_from = 1
while True:
n = int(input("number of iterations: "))
for exponent in range(start_from, start_from + n):
print(f'{base} ** {exponent} = {function(base, exponent)}')
start_from = start_from + n
# ask about continuing down here, optionally break out
If you really want to prompt for the number of iterations first, before asking for the base, you could probably make that work by using a sentinel value like None to indicate when it hasn't been set yet, so that you only prompt for it the first iteration (without explicitly counting):
base = None
start_from = 0
while True:
n = int(input("number of iterations: "))
if base is None:
base = int(input("Number to perform operation: "))
# ...
Related
How do I include the user input value in the very first place in the output?
here is my code below:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
So when I entered 6, it was printed like this:
3 10 5 16 8 4 2 1
My entered value (which MUST be included) is missing.
Please help!
In your current code, you add n to seq at the end of every iteration. To add the initial value of n, simply do seq.append(n) before entering the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
seq.append(n) # this is the addition you need
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
There are several ways you can do this. I believe the most logical way is to move your seq.append(n) statement to the first line of your while loop to capture your input. The issue will then be that 1 will be dropped off the end of the list. To fix that, you change your while loop condition to capture the one and add a condition to break out of the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 0):
seq.append(n)
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print()
print(*seq)
#output:
Enter a number (greater than 1): 6
6 3 10 5 16 8 4 2 1
This program will ask the user a series of questions about two numbers. These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. At the end of these 10 questions the program will display how many the user got correct out of those questions.
Each question should randomly decide between asking for the product, sum, or difference. Separate the question asking into a function, as well as the validating user input.
I tried using with three product, sum or difference in random to generate. I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y, but I couldn't figure it finish it up. I have the expected result when I first run with product but it works so I just need to add with sum and difference included.
EXPECTED OUTPUT with product (Some are incorrect for testing with scores):
> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10
My Work for Product Only (Success):
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 100)
y = random.randint(1, 100)
print("What is " + str(x) + " x " +str(y))
u = askNum()
if (u == x * y):
return 1
else:
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
My Currently Work: (I am working to add sum and difference like the expected output
UPDATED: After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now.
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
else if (z == 2):
x + y #sum
return 1
else if (z == 3):
x / y #difference
return 1
else
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
OUTPUT:
md35#isu:/u1/work/python/mathquiz> python3 mathquiz.py
File "mathquiz.py", line 27
if (z == 1):
^
IndentationError: unexpected indent
md35#isu:/u1/work/python/mathquiz>
With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. Any help would be more appreciated with explanation. (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet.
Your problem is that python 3 does not allow mixing spaces and tabs for indentation. Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips.
You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. You feed it into a calc(a,ops,b) function and return the correct result from it.
You can also shorten your askNum and provide the text to print.
These could look like so:
def askNum(text):
"""Retunrs an integer from input using 'text'. Loops until valid input given."""
while True:
try:
return int(input(text))
except ValueError:
print("Incorrect Input!")
def calc(a,ops,b):
"""Returns integer operation result from using : 'a','ops','b'"""
if ops == "+": return a+b
elif ops == "-": return a-b
elif ops == "*": return a*b
elif ops == "/": return a//b # integer division
else: raise ValueError("Unsupported math operation")
Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer.
Program:
import random
total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
ops = random.choice("+-*/")
a,b = random.choices(nums,k=2)
# you only allow integer input - your division therefore is
# limited to results that are integers - make sure that this
# is the case here by rerolling a,b until they match
while ops == "/" and (a%b != 0 or a<=b):
a,b = random.choices(nums,k=2)
# make sure not to go below 0 for -
while ops == "-" and a<b:
a,b = random.choices(nums,k=2)
# as a formatted text
result = askNum("What is {} {} {} = ".format(a,ops,b))
# calculate correct result
corr = calc(a,ops,b)
if result == corr:
correct += 1
print("Correct")
else:
print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))
print("You have {} out of {} correct.".format(correct,total))
Output:
What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
elif (z == 2):
x + y #sum
return 1
elif (z == 3):
x / y #difference
return 1
else:
return 0
Write your block like this your u = askNum() and next if loop should be on same vertical line.
To Generate n number of random number you can use
random.sample(range(from, to),how_many_numbers)
User this as reference for more info on random
import random
low=0
high=4
n=2 #no of random numbers
rand = random.sample(range(low, high), n)
#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)
x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)
if (operator == 0):
result = x + y# sum
elif(operator == 1):
result = x - y# difference
elif(operator == 2):
result= x / y#division
else :
result=x * y# product
print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
The following stores a random number(int)
operator = random.randint(0, 3)
to compare it with the list for operators.
Example: operator = 2
elif(operator == 2):
result= x / y#division
than this code will executed and because operator=2, 3rd element from list(/) will be selected
Output:
What is 3 / 2?
I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)
I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
It freezes up without showing an error message, and I have no clue why this happens.
1) You are invoking range() incorrectly.
Your code: for n in range(max - min): produces the range of numbers starting at 0 and ending at the value max-min. Rather, you want the range of numbers starting at min and ending at max.
Try this:
for n in range(min, max):
2) You are performing floating-point division, but this program should use only integer division. Try this:
num = num // 2
3) You are updating the count variable in the wrong loop context. Try indenting it one stop.
4) Your final line could be:
print('Number: '+str(n)+' Steps needed: '+str(count))
Program:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
Result:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5
It looks like it's getting stuck in the while not num == 1 loop. Remember that range() starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.
EDIT: I earlier said that count = 0 needed to be moved. Actually, looking more carefully it seems like the line count = count + 1 line just needs to be moved under the while loop.
How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:
if n is even, the next number is n/2
if n is odd, the next number is 3n + 1.
e.g. when starting with 11
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
This is my code now:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n_add = [n/2]
collatz = [] + n_add
else:
n_add2 = [3*n + 1]
collatz = [] + n_add2
print collatz
if I execute this and insert a number, nothing happens.
You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
print n
You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print
It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.
You should be modifying n each time, this will do what you want:
n = int(raw_input('insert a random number'))
while n > 1:
n = n / 2 if not n & 1 else 3 * n + 1 # if last bit is not set to 1(number is odd)
print n
## -- End pasted text --
insert a random number11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Using your own code to just print out each n:
n = int(raw_input('insert a random number'))
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print n
Or keep all in a list and print at the end:
all_seq = []
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
all_seq.append(n)
print(all_seq)
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input('Please pick any whole number to see the Collatz Sequence in action.\n'))
collatz(num)
except ValueError:
print('Please use whole numbers only.')
I've also been working on it for a while now, and here's what I came up with:
def collatz (number):
while number != 1:
if number == 0:
break
elif number == 2:
break
elif number % 2 == 0:
number = number // 2
print (number)
elif number % 2 == 1:
number = 3 * number + 1
print (number)
if number == 0:
print ("This isn't a positive integer. It doesn't count")
elif number == 2:
print ("1")
print ("Done!")
elif number == 1:
print ("1")
print ("Done!")
try:
number = int(input("Please enter your number here and watch me do my magic: "))
except (ValueError, TypeError):
print ("Please enter positive integers only")
try:
collatz(number)
except (NameError):
print ("Can't perform operation without a valid input.")
Here is my Program:
def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*number+1)
return 3*number+1
else:
print("Invalid number")
number = input("Please enter number: ")
while number != 1:
number = collatz(int(number))`
And the output of this program:
Please enter number: 12
6
3
10
5
16
8
4
2
1