Cumulative total from user's input string - python-3.x

I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.

This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.

Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)

Related

Having an issue relating to finding an Armstrong number from a list in Python [duplicate]

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

counting number of pairs with same elem value in python list

I don't understand why the function is returning 4 while it should return 3. Thank you very much.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += w/2
print(int(count))
From your description of what you said, of wanting to count pairs, then I believe you would want to round down the number being added to count instead of count overall, as 2 halves would end up making 1.
The following does return 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(count)
In Python, a single slash ”/“ does a regular divide that returns with decimals. A double slash “//“ returns a whole number rounded down. When you call int() on the number, it rounds it down to nearest whole number.
In your code, you get:
2+1.5+0.5+0.5=4.5
After calling int on 4.5, it becomes 4.
You are adding floats in the for loop, just change that to ints and it will add up to 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(int(count))

Multiplying all the digits of a number in python

If i have a number 101, i want to multiply all the digits of the number (1*0*1) but this result will become Zero. Instead how to split the number into 10 and 1 and multiply(10*1).
Similar examples,
3003033 -> 300*30*3*3 or
2020049 -> 20*200*4*9
You could use a negative look behind to check its not the start of the list and a positive look ahead for nums that are not 0 as your split point.
REGEX: Essentially this says split where the next num is not a 0 and it not the start of the line
/
(?<!^)(?=[^0])
/
gm
Negative Lookbehind (?<!^)
Assert that the Regex below does not match
^ asserts position at start of a line
Positive Lookahead (?=[^0])
Assert that the Regex below matches
Match a single character not present in the list below [^0]
0 matches the character 0 literally (case sensitive)
CODE
import re
from functools import reduce
def sum_split_nums(num):
nums = re.split(r'(?<!^)(?=[^0])', str(num))
total = reduce((lambda x, y: int(x) * int(y)), nums)
return " * ".join(nums), total
nums = [3003033, 2020049, 101, 4040]
for num in nums:
expression, total = sum_split_nums(num)
print(f"{expression} = {total}")
OUTPUT
300 * 30 * 3 * 3 = 81000
20 * 200 * 4 * 9 = 144000
10 * 1 = 10
40 * 40 = 1600
Let a and b be two integer numbers. Let c be a new number made by putting n zeros in the right side of b. Then multiplying a and c is equal to multiplying a and b and 10^n.
Now you can simplify what you want to do to the following: Multiply digits of your number to each other with the agreement that instead of 0, you will put 10. So actually you don't need to split your number.
Here I defined two functions. In both of them the idea is to convert your number to a string, run a for-loop on its digits and by an if condition in the case
1) multiply the previous result to the new digit if it is not 0, otherwise multiply to 10.
def multio1(x):
s = str(x)
ans = 1
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
ans *= 10
return(ans)
2) multiply the previous result to the new digit if it is not 0, otherwise add one unit to the number of zeros. Then at the end put as many as number of zeros, zeros at the right side of your final result.
def multio2(x):
s = str(x)
ans = 1
number_of_zeros = 0
for i in range(len(s)):
if s[i] != '0':
ans *= int(s[i])
else:
number_of_zeros += 1
if number_of_zeros != 0:
ans = str(ans)
for i in range(number_of_zeros):
ans += '0'
ans = int(ans)
return(ans)
Now the multio1(x) and multio2(x) for x=101,3003033,2020049, both gives equal results shown in below.
10,81000,144000
That's kind of odd, but this code will work:
a = '3003033'
num = ''
last_itr = 0
tot=1
for i in range(len(a)-1):
if a[i]=='0' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[last_itr:i+1])
last_itr=i+1
elif a[i]>'0' and a[i]<='9' and a[i+1]<='9' and a[i+1]>'0':
tot*=int(a[i])
last_itr=i+1
tot*=int(a[last_itr:len(a)])
print(tot)
Just put your number at a

Using generator to fill integer values in 2-D array

I want to use the below code (am supposed to not use map(), for an online programming site as gives error on that of : TypeError: 'map' object is not subscriptable
):
arr[i][j] = [int(input("Input score").strip().split()[:l]) for j in range(n) for i in range(t)]
instead of the below working version:
for i in range(t):
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())[:l]
but the error is (assume so) based on providing a list instead of individual values, as stated below:
TypeError: int() argument must be a string or a number, not 'list'
Unable to find a solution by any alternate way, say convert rhs (of desired soln.) to a string in first step & then assign to lhs in the second step; as need assign to arr[i][j].
P.S. Need to make the solution use the individual and row-wise values of arr, as say need find row-wise sum of values or even individual values. The below code uses the row-wise arr values to fill up total.
for i in range(t):
for j in range(n):
# Find sum of all scores row-wise
sum = 0
for m in arr[i][j]:
sum += m
total[i][j] = sum
You can map your nested for loops:
for i in range(t):
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())[:l]
to a list comprehension like:
arr = [map(int, input("Input score").strip().split())[:l] for i in range(t) for j in range(n)]
And without a map like:
arr = [[int(k) for k in input("Input score").strip().split())[:l]]
for i in range(t) for j in range(n)]
We can do a nested list comprehension as follows:
t = int(input("Input number of tests: "))
n = int(input("Input number of rows: "))#.strip().split())
total = [[sum([int(i) for i in input("Input score: ").split()]) for j in range(n)] for t_index in range(t)]
print(total)
Example of an input-output pair:
Input number of tests: 2
Input number of rows: 3
Input score: 1 2 3
Input score: 2 3 4
Input score: 3 4 5
Input score: 4 5 6
Input score: 5 6 7
Input score: 6 7 8
[[6, 9, 12], [15, 18, 21]]

Index Error Problems

So I'm making a calculator that takes in a string and checks to see if it has certain words like add or subtract and then finding integers. However, in my current code, I run it and get this error message:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 7, in calculator
IndexError: string index out of range
The code is typed out below.
def calculator(string):
if "add" in string or "Add" in string:
total = 0
for i in range(len(string)): #loop for length of string
try:
if type(int(string[i])) == int: #checks to see if there is a number in the string
try:
if type(int(string[i+1])): #checks to see if the number is 2 digits
number_1 = int(string[i])*10
except ValueError:
number_1 = int(string[i])
total = total + number_1 #adds all the numbers to a total variable
except ValueError:
pass
print (total)
If someone could help me out that would be great! Thanks so much!
I believe your problem is with type(int(string[i+1]))
as you have a for loop, i can already be pointing to the last index of string. When you add 1 to that, you get an IndexError
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i])
Output:
b
l
a
b
l
a
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i+1])
Output:
l
a
b
l
a
File "C:\Users\python\scratch\untitled-1.py", line 3, in <module>
print(s[i+1])
builtins.IndexError: string index out of range
Sat down with my friend(#Kay Ace Elits) and realised a bunch of things were amiss but we pieced this together
def calculator(string):
if "add" in string:
total = 0
first_string = "" # before a in add
second_string = "" # after d in add
value_list = string.split('add')
for number in value_list:
total += int(number)
print(total)
elif "Add" in string:
total = 0
first_string = ""
second_string = ""
value_list = string.split('Add')
for number in value_list:
total += int(number)
print(total)
### our test your can modify for other factors
### like spellings and different operations
string = "22add43"
calculator(string)

Resources