Python for loops for repeated addition - python

I am trying to create a program that creates a multiplication table of n x n.
It's required for the assignment to use repeated addition instead of the multiplication function.
This is the code I have so far:
def main():
import math
print('Hello!')
n = (abs(eval(input("Enter n for the multiplication table n x n: "))))
n = int(n)
a = 0
for i in range(1,n+1):
for x in range(1,n+1):
a = i+a
print(i,' * ',x,' = ',a)
main()
It gives me an output like this:
Hello!
Enter n for the multiplication table n x n: 4
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 6
2 * 2 = 8
2 * 3 = 10
2 * 4 = 12
3 * 1 = 15
3 * 2 = 18
3 * 3 = 21
3 * 4 = 24
4 * 1 = 28
4 * 2 = 32
4 * 3 = 36
4 * 4 = 40
The output is obviously incorrect, so what can I change/add to fix the calculations?

You have a variable a inside of your nested for loops that you continuously add values to for different values of the multiplication table. Instead of adding i to a each iteration, let a = i*x. This will give you the correct value of multiplication each time. However, if you really want to do it with repeated addition, set a = 0 outside of the second for loop, but inside the first, like so:
for i in range(1,n+1):
for x in range(1,n+1):
a = i+a
print(i,' * ',x,' = ',a)
a = 0

For the print statement try using instead:
print(i,' * ',x,' = ',i*x)
I'm not certain what you are using the 'a' variable for, but if you'd like to output the multiplication of i and x still using a, instead keep your code the same and just change what you have for a in your nest for loop:
a = i*x
Hope this helps!

In your for loop, you're always incrementing the variable 'a' by itself added to 'i' each time, instead you should multiply i*x
print("Hello!")
n = input("Enter n for the multiplication table n x n: ")
n = int(n)
result = 0
for i in range(1,n+1):
for j in range(1, n+1):
result = i*j
print(i," * ", j, " = ", result)

Related

Find missing arrithmetic operations in arithmetic expression

I was given the following task:
Richard likes to ask his classmates questions like the following:
4 x 4 x 3 = 13
In order to solve this task, his classmates have to fill in the missing arithemtic operators (+, -, *, /) that the created equation is true. For this example the correct solution would be 4 * 4 - 3. Write a piece of code that creates similar questions to the one above. It should comply the following rules:
The riddles should only have one solution (e.g. not 3 x 4 x 3 = 15, which has two solutions)
The operands are numbers between 1-9
The solution is a positive integer
Point before dashes is taken into account (e.g. 1 + 3 * 4 = 13)
Every interim result is an integer (e.g. not 3 / 2 * 4 = 6)
Create riddles up to 15 arithmetic operands, which follow these rules.
My progress so far:
import random
import time
import sys
add = lambda a, b: a + b
sub = lambda a, b: a - b
mul = lambda a, b: a * b
div = lambda a, b: a / b if a % b == 0 else 0 / 0
operations = [(add, '+'),
(sub, '-'),
(mul, '*'),
(div, '/')]
operations_mul = [(mul, '*'),
(add, '+'),
(sub, '-'),
(div, '/')]
res = []
def ReprStack(stack):
reps = [str(item) if type(item) is int else item[1] for item in stack]
return ''.join(reps)
def Solve(target, numbers):
counter = 0
def Recurse(stack, nums):
global res
nonlocal counter
valid = True
end = False
for n in range(len(nums)):
stack.append(nums[n])
remaining = nums[:n] + nums[n + 1:]
pos = [position for position, char in enumerate(stack) if char == operations[3]]
for j in pos:
if stack[j - 1] % stack[j + 1] != 0:
valid = False
if valid:
if len(remaining) == 0:
# Überprüfung, ob Stack == target
solution_string = str(ReprStack(stack))
if eval(solution_string) == target:
if not check_float_division(solution_string)[0]:
counter += 1
res.append(solution_string)
if counter > 1:
res = []
values(number_ops)
target_new, numbers_list_new = values(number_ops)
Solve(target_new, numbers_list_new)
else:
for op in operations_mul:
stack.append(op)
stack = Recurse(stack, remaining)
stack = stack[:-1]
else:
if len(pos) * 2 + 1 == len(stack):
end = True
if counter == 1 and end:
print(print_solution(target))
sys.exit()
stack = stack[:-1]
return stack
Recurse([], numbers)
def simplify_multiplication(solution_string):
for i in range(len(solution_string)):
pos_mul = [position for position, char in enumerate(solution_string) if char == '*']
if solution_string[i] == '*' and len(pos_mul) > 0:
ersatz = int(solution_string[i - 1]) * int(solution_string[i + 1])
solution_string_new = solution_string[:i - 1] + solution_string[i + 1:]
solution_string_new_list = list(solution_string_new)
solution_string_new_list[i - 1] = str(ersatz)
solution_string = ''.join(str(x) for x in solution_string_new_list)
else:
return solution_string
return solution_string
def check_float_division(solution_string):
pos_div = []
solution_string = simplify_multiplication(solution_string)
if len(solution_string) > 0:
for i in range(len(solution_string)):
pos_div = [position for position, char in enumerate(solution_string) if char == '/']
if len(pos_div) == 0:
return False, pos_div
for j in pos_div:
if int(solution_string[j - 1]) % int(solution_string[j + 1]) != 0:
# Float division
return True, pos_div
else:
# No float division
return False, pos_div
def new_equation(number_ops):
equation = []
operators = ['+', '-', '*', '/']
ops = ""
if number_ops > 1:
for i in range(number_ops):
ops = ''.join(random.choices(operators, weights=(4, 4, 4, 4), k=1))
const = random.randint(1, 9)
equation.append(const)
equation.append(ops)
del equation[-1]
pos = check_float_division(equation)[1]
if check_float_division(equation):
if len(pos) == 0:
return equation
for i in pos:
equation[i] = ops
else:
'''for i in pos:
if equation[i+1] < equation[i-1]:
while equation[i-1] % equation[i+1] != 0:
equation[i+1] += 1'''
new_equation(number_ops)
else:
print("No solution with only one operand")
sys.exit()
return equation
def values(number_ops):
target = 0
equation = ''
while target < 1:
equation = ''.join(str(e) for e in new_equation(number_ops))
target = eval(equation)
numbers_list = list(
map(int, equation.replace('+', ' ').replace('-', ' ').replace('*', ' ').replace('/', ' ').split()))
return target, numbers_list
def print_solution(target):
equation_encrypted_sol = ''.join(res).replace('+', '○').replace('-', '○').replace('*', '○').replace('/', '○')
print("Try to find the correct operators " + str(equation_encrypted_sol) + " die Zahl " + str(
target))
end_time = time.time()
print("Duration: ", end_time - start_time)
input(
"Press random button and after that "ENTER" in order to generate result")
print(''.join(res))
if __name__ == '__main__':
number_ops = int(input("Number of arithmetic operators: "))
# number_ops = 10
target, numbers_list = values(number_ops)
# target = 590
# numbers_list = [9, 3, 5, 3, 5, 2, 6, 3, 4, 7]
start_time = time.time()
Solve(target, numbers_list)
Basically it's all about the "Solve(target, numbers)" method, which returns the correct solution. It uses Brute-Force in order to find that solution. It receives an equation and the corresponding result as an input, which has been generated in the "new_equation(number_ops)" method before. This part is working fine and not a big deal. My main issue is the "Solve(target, numbers)" method, which finds the correct solution using a stack. My aim is to make that program as fast as possible. Currently it takes about two hours until an arithmetic task with 15 operators has been found, which follows the rules above. Is there any way to make it faster or maybe another approach to the problem besides Brute-Force? I would really appreciate your help :)
This is mostly brute force but it only takes a few seconds for a 15 operation formula.
In order to check the result, I first made a solve function (recursive iterator) that will produce the solutions:
def multiplyDivide(numbers):
if len(numbers) == 1: # only one number, output it directly
yield numbers[0],numbers
return
product,n,*numbers = numbers
if product % n == 0: # can use division.
for value,ops in multiplyDivide([product//n]+numbers):
yield value, [product,"/",n] + ops[1:]
for value,ops in multiplyDivide([product*n]+numbers):
yield value, [product,"*",n] + ops[1:]
def solve(target,numbers,canGroup=True):
*others,last = numbers
if not others: # only one number
if last == target: # output it if it matches target
yield [last]
return
yield from ( sol + ["+",last] for sol in solve(target-last,others)) # additions
yield from ( sol + ["-",last] for sol in solve(target+last,others)) # subtractions
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,ops in multiplyDivide(numbers[-size:]): # multiplicative groups
for sol in solve(target,numbers[:-size]+[value],canGroup=False):
yield sol[:-1] + ops # combined multipicative with rest
The solve function recurses through the numbers building an addition or subtraction with the last number and recursing to solve a smaller problem with the adjusted target and one less number.
In addition to the additions and subtraction, the solve function groups the numbers (from the end) into consecutive multiplications/divisions and processes them (recursing into solve) using the resulting value that will have calculation precedence over additions/subtractions.
The multiplyDivide function (also a recursive generator) combines the group of numbers it is given with multiplications and divisions performed from left to right. Divisions are only added when the current product divided by the additional number produces an integer intermediate result.
Using the solve iterator, we can find a first solution and know if there are more by iterating one additional time:
def findOper(S):
expression,target = S.split("=")
target = int(target.strip())
numbers = [ int(n.strip()) for n in expression.split("x") ]
iSolve = solve(target,numbers)
solution = next(iSolve,["no solution"])
more = " and more" * bool(next(iSolve,False))
return " ".join(map(str,solution+ ["=",target])) + more
Output:
print(findOper("10 x 5 = 2"))
# 10 / 5 = 2
print(findOper("10 x 5 x 3 = 6"))
# 10 / 5 * 3 = 6
print(findOper("4 x 4 x 3 = 13"))
# 4 * 4 - 3 = 13
print(findOper("1 x 3 x 4 = 13"))
# 1 + 3 * 4 = 13
print(findOper("3 x 3 x 4 x 4 = 25"))
# 3 * 3 + 4 * 4 = 25
print(findOper("2 x 6 x 2 x 4 x 4 = 40"))
# 2 * 6 * 2 + 4 * 4 = 40 and more
print(findOper("7 x 6 x 2 x 4 = 10"))
# 7 + 6 * 2 / 4 = 10
print(findOper("2 x 2 x 3 x 4 x 5 x 6 x 3 = 129"))
# 2 * 2 * 3 + 4 * 5 * 6 - 3 = 129
print(findOper("1 x 2 x 3 x 4 x 5 x 6 = 44"))
# 1 * 2 + 3 * 4 + 5 * 6 = 44
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 1001"))
# 1 - 2 - 3 + 4 * 5 * 6 * 7 / 8 * 9 + 8 * 7 - 6 + 5 + 4 + 1 = 1001 and more
print(findOper("1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 8 x 7 x 6 x 5 x 4 x 1= 90101"))
# no solution = 90101 (15 seconds, worst case is not finding any solution)
In order to create a single solution riddle, the solve function can be converted to a result generator (genResult) that will produce all possible computation results. This will allow us to find a result that only has one combination of operations for a given list of random numbers. Given that the multiplication of all numbers is very likely to be a unique result, this will converge rapidly without having to go through too many random lists:
import random
def genResult(numbers,canGroup=True):
*others,last = numbers
if not others:
yield last
return
for result in genResult(others):
yield result - last
yield result + last
if not canGroup: return
for size in range(2,len(numbers)+1):
for value,_ in multiplyDivide(numbers[-size:]):
yield from genResult(numbers[:-size]+[value],canGroup=False)
def makeRiddle(size=5):
singleSol = []
while not singleSol:
counts = dict()
numbers = [random.randint(1,9) for _ in range(size)]
for final in genResult(numbers):
if final < 0 : continue
counts[final] = counts.get(final,0) + 1
singleSol = [n for n,c in counts.items() if c==1]
return " x ".join(map(str,numbers)) + " = " + str(random.choice(singleSol))
The reason we have to loop for singleSol (single solution results) is that there are some cases where even the product of all numbers is not a unique solution. For example: 1 x 2 x 3 = 6 could be the product 1 * 2 * 3 = 6 but could also be the sum 1 + 2 + 3 = 6. There aren't too many of those cases but it's still a possibility, hence the loop. In a test generating 1000 riddles with 5 operators, this occurred 4 times (e.g. 4 x 1 x 1 x 4 x 2 has no unique solution). As you increase the size of the riddle, the occurrence of these no-unique-solution patterns becomes more frequent (e.g. 6 times generating 20 riddles with 15 operators).
output:
S = makeRiddle(15) # 7 seconds
print(S)
# 1 x 5 x 2 x 5 x 8 x 2 x 3 x 4 x 1 x 2 x 8 x 9 x 7 x 3 x 2 = 9715
print(findOper(S)) # confirms that there is only one solution
# 1 * 5 * 2 * 5 * 8 * 2 * 3 * 4 - 1 + 2 + 8 * 9 + 7 * 3 * 2 = 9715

Loops with variables that count- trying to find out where this ends

I'm supposed to type the programs output. Input is 6, 3
target = int(input())
n = int(input())
while n <= target:
print(n * 2)
n += 1
My output - 6
My reasoning- 3 < 6 so the code will run through. 3 * 2 = 6 so 6 gets printed out. Then we do 6 += 1 which would be 7. 7 is not <= 6 so code shouldn't run through again.
The expected output:
6
8
10
12
n += 1 is shorthand for n = n + 1. The loop ends when n is greater than target.
Can someone please tell me where I am going wrong?
print(n * 2) does not affect the value of n. Since we did not put n * 2 in the value of n, the value of n changes only by n += 1.
target = int(input())
n = int(input())
while n <= target:
n = n * 2
print(n)
n += 1
This is the main difference between print and return statement.
Using return changes the flow of the program. Using print does not
def func(target,n):
while n <= target:
return (n * 2)
n += 1
target = int(input())
n = int(input())
print(func(target,n))
See here

Python Arithmetic Sequence Sum

How do I make a code that follows this? 1⋅2+2⋅3+3⋅4+…+(n−1)⋅n
For example, if n=5, the answer is 1⋅2+2⋅3+3⋅4+4⋅5=40.
n cannot be less than or equal to two or more or equal to 1000
This is my code for now but it doesn't work.
n = int(input())
if n>= 2 and n<=1000:
sum = 0;
numbers = range(1, n+1)
for amount in numbers:
if (amount % 2 == 1):
sum *= amount
else:
sum += amount
print(sum)
For every number between 1 and n-1 (inclusive), you need to multiply it by the following number, and then sum them all. The easiest way to represent this is with a comprehension expression over a range call:
result = sum(i * (i + 1) for i in range(1, n))
You need to reproduce exactly the scheme you give
for each number, mulitply it with itself-1, and sum that
def compute(n):
if 2 <= n <= 1000:
total = 0
for amount in range(1, n + 1):
total += amount * (amount - 1)
print(total)
But that's the same as multiplying each with itself+1, if you change the bound to get one step less
for amount in range(1,n):
total += amount * (amount + 1)
Then you can use builtin methos sum and a generator syntax
def compute(n):
if 2 <= n <= 1000:
total = sum(nb * (nb + 1) for nb in range(1,n))
print(total)
If you try to approach it mathematically, you can have the answer in a single expression.
Dry run your code. You will see that for n = 5, you are doing as follows:
Num of Iterations = 6 (1 -> 5+1)
Iteration 1
sum = 0 + 1 = 1
Iteration 2
sum = 1 * 2 = 2
Iteration 3
sum = 2 + 3 = 5
Iteration 4
sum = 5 * 4 = 20
Iteration 5
sum = 20 + 5 = 25
Iteration 6
sum = 25 * 6 = 150
In this, you are completely disregarding the BODMAS/PEMDAS rule of multiplication over addition in the process of regenerating and calculating the series
What you need to do is
Iteration 1:
sum = 0 + 2 * 1 = 2
Iteration 2:
sum = 2 + 3 * 2 = 8
Iteration 3:
Sum = 8 + 4*3 = 20
Iteration 4:
Sum = 20 + 5*4 = 40
Here, We have broken the step as follows:
For each iteration, take the product of (n) and (n-1) and add it to the previous value
Also note that in the process, we are first multiplying and then adding. ( respecting BODMAS/PEMDAS rule )
So, you need to go from n = 2 to n = 5 and on each iteration you need to do (n-1)*(n)
As mentioned earlier, the loop is as follows:
## Checks for n if any
sum = 0
for i in range(2, n):
sum = sum + (i-1)*i
print(sum)

how can I modify list item value using for loop in Python?

I'm trying to implement the Luhn algorithm in a program and I'm trying to modify list items if they are larger than 9. I will attach the code I'm trying to write. variable iin is defined outside of function.
def luhn_checker():
account_number = random.randint(100000000, 999999999)
check_sum = random.randint(0, 9)
numbers = []
card_number = f'{iin}{account_number}'
for i in card_number:
numbers.append(int(i))
print(numbers)
numbers[0] = numbers[0] * 2
numbers[2] = numbers[2] * 2
numbers[4] = numbers[4] * 2
numbers[6] = numbers[6] * 2
numbers[8] = numbers[8] * 2
numbers[10] = numbers[10] * 2
numbers[12] = numbers[12] * 2
numbers[14] = numbers[14] * 2
print(numbers)
for i in numbers:
if i > 9:
numbers[i] = numbers[i] - 9
There is an error in your for-loop. It should be as follows:
for i, x in enumerate(numbers):
numbers[i] = x - 9 if x > 9 else x
Thanks for the replies, ended up using a luhn library.

How do I use while loops to create a multiplication table?

This is my code, it outputs a multiplication table but it's not what I wanted!
num = int(input("Multiplication using value? : "))
while num <= 10:
i = 1
while i <= num:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
print("\n")
num = num + 1
I am basically creating a multiplication table from the user's input from 1-9.
Ex. If the user inputs "3",
I should get this output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9
The reason why you have an infinite loop on your hands is because you are comparing i to num, while also increasing num on every run. If you make sure i is always <= 10, you get your desired output:
while num <= 10:
i = 1
while i <= 10:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
num = num + 1
print("\n")
Even if the code you posted is not pythonic at all (it is very close to what could be written in C language), it nearly works: with minimum modifications, it can be fixed as follows to give your expected ouput:
numInput = int(input("Multiplication using value? : "))
num = 1
while num <= numInput:
i = 1
while i <= numInput:
product = num*i
print(num, " * ", i, " = ", product)
i = i + 1
print("") # no need to add explicit newline character because it is automatically added
num = num + 1
In a more pythonic way, you can also do the following:
numInput = int(input("Multiplication using value? : "))
for i in range(1,numInput+1):
for j in range(1,numInput+1):
print(i, " * ", j, " = ", i*j)
print("")
For this problem it's easier to use for loops.
num = int(input("Multiplication using value? : "))
for left in range(1,num+1): # 1st loop
for right in range(1,num+1): # 2nd loop (nested)
print(left, " * ", right, " = ", left * right)
print() # newline
To understand this problem, look at the two multiplicands: left and right.
Left multiplicand goes from (1-->num), hence the first for loop.
Then, for each value of the left multiplicand, the right multiplicand goes from (1-->num), hence the 2nd loop is nested inside the first loop.
You've lots of logical error. Please have a look at this updated code:
num = int(input("Multiplication using value : "))
i=1 #you haven't initialized this variable
while i <=num:
j=1
while j <= num:
product = i*j #updated
print(i, " * ", j, " = ", product, "\n") #updated
j = j + 1
print("\n")
i = i + 1
Output (for input 3):
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
In Python 3.6+, you can use f-strings with a nested for loop:
num = int(input("Multiplication using value? : "))
for i in range(1, num+1):
for j in range(1, num+1):
print(f'{i} * {j} = {i*j}')
Multiplication using value? : 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
multiplication table using while loop in python
num = int(input("enter the number= "))
i = 1
while i<=10:
print(num, "X", i, "=", num * i)
i = i+1
output
enter the number= 33
33 X 1 = 33
33 X 2 = 66
33 X 3 = 99
33 X 4 = 132
33 X 5 = 165
33 X 6 = 198
33 X 7 = 231
33 X 8 = 264
33 X 9 = 297
33 X 10 = 330
num = int(input("Enter the number: "))
i = 1
print("Mulltiplication of number:", num)
while i<=10:
print(f"{num}X{i}={num*i}")
i = i + 1
Multiplication table 1 to 10
for x in range(1,11):
for y in range(1,11):
print(x*y, end='\t')
print()
print()
input any number to get your normal multiple table(Nomenclature) in 10 iterate times.
num = int(input("Input a number: "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
num = int(input('Enter the number you want the multiplication table for:'))
i=1
while i<=10:
product = num*i
print(product)
i=i+1
print('Thank you')
Creating a multiplication table using while loop is shown below:
b = int(input('Enter the number of the multiplicaction table : '))
print('The multiplication table of '+ str(b) + 'is : ')
a=0
while a<=11:
a=a+1
c= a*b
print( str(b)+' x '+str(a)+' ='+str(c))
print('done!!!!')
To create a multiplication table in python:
name=int(input("Enter the number of multiplication"))
i=1
while(i<=10):
print(str(name)+"X"+str(i)"="+str(name*i))
i=i+1

Categories

Resources