Adding Consecutive integers in Python, with a twist - python

Here is my original code:
x = input("Please input an integer: ")
x = int(x)
i = 1
sum = 0
while x >= i:
sum = sum + i
i += 1
print(sum)
Here is what the second part is:
b) Modify your program by enclosing your loop in another loop so that you can find consecutive sums. For example , if 5 is entered, you will find five sum of consecutive numbers so that:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
I have been stuck on this for 3 days now, and I just can't understand how to do it. I have tried this but to no avail.
while x >= i:
sum_numbers = sum_numbers + i
past_values = range(i)
for ints in past_values:
L = []
L.append(ints)
print(L, "+", i, "=", sum_numbers)
i += 1
Can anyone just help steer my in the correct direction? BTW. it is python 3.3

You could do this in one loop, by using range to define your numbers, and sum to loop through the numbers for you.
>>> x = input("Please input an integer: ")
Please input an integer: 5
>>> x = int(x)
>>>
>>> for i in range(1, x+1):
... nums = range(1, i+1)
... print(' + '.join(map(str, nums)), '=', sum(nums))
...
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
range(1, x+1) would give me [1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.
nums = range(1, i+1) notice we are using i instead here, (taken from the range above), which I am using to define which number I am up to in the sequence.
' + '.join(map(str, nums)):
map(str, nums) is used to convert all elements of nums into strings using str, since the join method expects an iterable filled with strings.
' + '.join is used to "join" elements together with a common string, in this case, ' + '. In cases where there is only 1 element, join will just return that element.
sum(nums) is giving you the sum of all numbers defined in range(1, i+1):
When nums = range(1, 2), sum(nums) = 1
When nums = range(1, 3), sum(nums) = 3
Etc...

reduce(lambda x,y:x+y,range(x+1))

You don't have to use a while loop, 2 for will do the trick nicely and with a more natural feeling.
x = input("Please input an integer : ")
x = int(x)
item = range(1, x + 1)
for i in item:
sum = 0
for j in range(1, i + 1):
sum = sum + j
print(str(sum))

Using list comprehension in python:
x = input("Please input an integer: ")
x = int(x)
i = 1
sums = [(((1+y)*y)//2) for y in range(i, x+1)] # creates list of integers
print(sums) # prints list of sums on one line
OR
[print(((1+y)*y)//2) for y in range(i, x+1)] # prints sums on separate line

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

I tried it a lot and I want to get occurrence of 4 without using count function

I tried it a lot and I want to get occurrence of 4 without using count function
n = int(input()) #number of input
for i in range(n): #range
l = [] #list
x = int(input()) #input
while (x > 0): #innserting input into list
y = x % 10
x = x / 10
l.append(y)
z = 0
for i in l:
if (i == 4): # calculating no of occurrence
z = z + 1
print(z)
Here's a much simpler way of solving it.
number = int(input("Enter Number: "))
fours = [] #create list to store all the fours
for x in str(number): #loop through the number as a string
if x == '4': #check if the character if 4
fours.append(x) #add it to the list of fours
print("Number of fours: " + str(len(fours))) #prints the length of the array

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

Kind of pyramid numbers pattern exercise

Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?
1
232
34543
4567654
567898765
678901109876
This is the code I made:
c = -1
for y in range(1, 7):
print()
print((6-y) * " ", end="")
c += 1
for x in range(1, y+1):
print(y%10, end="")
y += 1
while y - c > 2:
print(y-2, end="")
y -= 1
First of all, I'm guessing that you didn't really want to print that y value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.
Do not change the value of a loop parameter while you're inside the loop. Specifically, don't change y within the for y loop.
Get rid of c; you can derive it from the other values.
For flexibility, make your upper limit a parameter: you have two constants (6 and 7) that depend on one concept (row limit).
Here's my version:
row_limit = 7
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " ", end="")
for x in range(y, 2*y):
print(x%10, end="")
for x in range(2*(y-1), y-1, -1):
print(x%10, end="")
print()
Output:
1
232
34543
4567654
567898765
67890109876
If you really want to push things, you can shorten the loops with string concatenation and comprehension, but it's likely harder to read for you.
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " " + ''.join([str(x%10) for x in range(y, 2*y)]) + \
''.join([str(x%10) for x in range(2*(y-1), y-1, -1)]), end="")
print()
Each of the loops is turned into a list comprehension, such as:
[str(x%10) for x in range(y, 2*y)]
Then, this list of characters is joined with no interstitial character; this forms half of the row. The second half of the row is the other loop (counting down). In front of all this, I concatenate the proper number of spaces.
Frankly, I prefer my first form.
Here's my implementation.
Python 2:
def print_triangle(n):
for row_num in xrange(1, n + 1):
numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print '{}{}'.format(' ' * (n - row_num), num_string)
Python 3:
def print_triangle(n):
for row_num in range(1, n + 1):
numbers = [str(num % 10) for num in range(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print('{}{}'.format(' ' * (n - row_num), num_string))
Input:
print_triangle(5)
print_triangle(6)
print_triangle(7)
Output:
1
232
34543
4567654
567898765
1
232
34543
4567654
567898765
67890109876
1
232
34543
4567654
567898765
67890109876
7890123210987
n = int(input())
i = 1
while i <= n:
j = 1
spaces = 1
p = i
while spaces <= n - i:
print (" ", end ="")
spaces += 1
while j <= i:
print(p, end = "")
j += 1
p += 1
p -= 2
while p >= i:
print(p, end = "")
p -= 1
print()
i += 1

how to use information given in a python while loop?

I made a program that looks like:
n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
x = x + 1
print (x)
This code produces a list from 1 to the given whole number n.
What would i do to be able to interact with this list making a second column that gave the square of the adjacent number?
something like
1 1
2 4
3 9
If you want to be able to show the square of 1, you need to initialize x as 0 and delete print(x) from your third line
this should do it:
n = eval(input("enter a whole number: "))
x = 0
while x != n:
x = x + 1
print (x, " ", x**2)
This code prints x and x**2 (the value of 'x ^ 2') separated by a space.
Here is what you are looking for:
n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
x = x + 1
p = x * x
print (x, p)
I would urge caution on using eval() so lightly though, you can use the int() function to run a string as an integer. Here is how I would write that code:
n = int(input("enter a whole number: "))
x = 0
while x != n:
x = x + 1
p = x * x
print (x, p)
EDIT: Updated code
Well, you could use a list of lists. Using a generator expression,
nums = [[n, n**2] for n in range(1,int(input("Enter a number"))]
So if you input 10, nums[1,1] will be 2.
So to print this out,
for i in nums:
print(i[0] + " " + i[1])
This is by far the simplest way to go.

Categories

Resources