So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:
z= 1
while z > 0:
for i in range(len(list)):
print(list[i],"+", end=" ")
z = 0
print("=",sum(list),end=" ")
This is what i am trying and output is:
2 + 5 + 6 + 9 + 1 + = 23
What should I do if I want to output n integers and n-1 plus signs between integers?
You may use str.join that accept an iterable of strings. You need to map each int to str then join them using the + and print the result
values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values)) # 2 + 5 + 6 + 9 + 1 = 23
# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)
Use join:
def printfn(alist):
expr = " + ".join((map(str, alist)))
sum_val = sum(alist)
print("{} = {}".format(expr, sum_val))
a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6
b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10
Another possibility is to use sep= parameter of print() function.
For example:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
Prints:
2 + 5 + 6 + 9 + 1 = 23
You can use enumerate(), starting with an index of 1
>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
if i == len(l):
# If the current item is the length of the list then just append the number at this index, and the final sum
s += str(v) + ' = ' + str(sum_)
else:
# means we are still looping add the number and the plus sign
s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23
Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0
list = [2,5,6,9,1]
z= 1
while z > 0:
for i in range( len(list)-1 ):
print(list[i],"+", end=" ")
print (list[len(list)-1],end=" ")
print("=",sum(list),end=" ")
z = 0
Related
I have Two object:
total_statuses = 10
status = {"A":2, "B":5, "C":3}
I want to print them in a simple table style without using any extra library such as tabulate.
Total A B C
-------------------
10 2 5 3
headers = ["Total"] + list(statuses.keys())
[print(f"{h:15}", end='') for h in header]
What is the effecient way to achieve this output?
Another solution is use a function:
In [9]: def show(headers, statuses):
...: [print(f"{h:15}", end='') for h in headers]
...: print('\n' + '-' * (15 * len(statuses)+1))
...: print(f'{str(sum(statuses.values())):15}', end='')
...: for _, v in sorted(statuses.items()):
...: print(f'{str(v):15}', end='')
...: print()
...:
Output:
In [10]: show(headers, statuses)
Total A B C
----------------------------------------------
10 2 5 3
Here is a possible solution:
total_statuses = 10
status = {"A":2, "B":5, "C":3}
l1 = max(5, len(str(total_statuses))) + 4
l2 = len(str(status['A'])) + 3
l3 = len(str(status['B'])) + 3
l4 = len(str(status['C']))
lines = [
'Total '.ljust(l1) + 'A'.ljust(l2) + 'B'.ljust(l3) + 'C'.ljust(l4),
'-' * (l1 + l2 + l3 + l4),
str(total_statuses).ljust(l1) + str(status['A']).ljust(l2) + str(status['B']).ljust(l3) + str(status['C']).ljust(l4),
]
print(*lines, sep='\n')
Output:
Total A B C
------------------
10 2 5 3
So given an input of 0o11110000000 base 8 ('0o' is ignored) i have to generate and count how many possible numbers that when the individual numbers are added they are the same. for example
0o1111000000 : 1 + 1 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 = 4
0o0000001111 : 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 1 + 1 = 4
0o0000000201 : 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 2 + 0 + 1 = 3
so for an input of 0o0000000001 i should get an answer of 10
0000000001
0000000010
0000000100
0000001000
0000010000
0000100000
0001000000
0010000000
0100000000
1000000000
My method is a very very brute force method in which i have to check every possible number from 0 to 7777 7777 77 base8. It uses the decimal represtation of the octal numbers and i use a recursive function to retrieve the octal sum of a number
How can i improve this to be a lot more faster. If possible no python modules as i doubt the machine running the program is unable to import a lot of stuff
def sum_of_octal_digits( n ):
if n == 0 :
return 0
else:
return int(n) % 8 + sum_of_octal_digits( int(n / 8) )
octInput = input("Enter hex: ")
int_octInput = int(octInput , 16)
total = sum_of_octal_digits(int_octInput )
allcombinations = list()
for i in range(pow(8,len(e[2:]))):
if sum_of_octal_digits(i) == total :
allcombinations.append(i)
print(len(allcombinations))
You're counting the number of sequences of {0, 1, 2, 3, 4, 5, 6, 7} of length n that sum to t. Call that value S[n, t].
There's a recurrence relation that S[n, t] satisfies:
S[0, 0] = 1
S[0, t] = 0 (t != 0)
S[n+1, t] = sum(S[n, t-d] for d=0...min(t, 7))
Once you have the recurrence relation, solving the problem using dynamic programming is straightforward (either by using memoization, or using a bottom-up table approach).
The program should run in O(nt) time and use O(nt) space.
Salam, I'm given a user input that I have to sum it by itself n-times. Which means if the input is "5" for example, I should return 5 + 5 + 5 + 5 + 5 = 25
I used:
def sum(user_input):
inp_sum = 0
string = ''
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input -1:
string+= "5 + "
else: string += '5'
return string + ' = ' + str(inp_sum)
but it returns
Failed for value=6
Expected: 6 + 6 + 6 + 6 + 6 + 6 = 36
Actual: 5 + 5 + 5 + 5 + 5 + 5 = 36
what is the solution?
You hardcoded 5 in to the logic of your function, when you should be passing in the user input to the string format logic. Also, do not name your function sum as you will shadow the built-in function sum.
def mysum(user_input):
inp_sum = 0
string = ""
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input - 1:
string += "{} + ".format(user_input)
else:
string += str(user_input)
return "{} = {}".format(string, inp_sum)
You can simplify it like this:
def user_input(n):
return "{} = {}".format(' + '.join([str(n) for _ in range(n)]), str(n*n))
print(user_input(5))
# 5 + 5 + 5 + 5 + 5 = 25
print(user_input(6))
# 6 + 6 + 6 + 6 + 6 + 6 = 36
My code looks like this at the moment:
limit = int(input("Limit:"))
number = 1
sum = 1
while sum < limit:
number = number + 1
sum = sum + number
print(f"The consecutive sum:{sum}")
Add the numbers you're using in a separate list. Then use str.join() to join these numbers with a ' + '.
limit = int(input("Limit:"))
number = 1
total = number
numbers = [str(number)]
while total < limit:
number = number + 1
total = total + number
numbers.append(str(number)) # Need to convert to string here because str.join() wants a list of strings
print(f"The consecutive sum: {' + '.join(numbers)} = {total}")
Which prints the required output:
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
limit = int(input("Limit:"))
number = 1
sum = 1
print("The consecutive sum: 1", end = " ")
while sum < limit:
number += 1
sum += number
print(f'+ {number}', end = " ")
print(f'= {sum}')
Output Will Be:
Limit:18
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion