Multiply input by order and sum multiplied result then print - python

Hey guys I'm new to python and right now I'm stuck in this:
Get user number input like "98751", then multiply them by order and sum the multiplied result like this:
"9^1" + "8^2" + "7^3" + "5^4" + "1^5"
So far I got here without input:
num = 34532
x = [int(a) for a in str(num)]
print(x)
a=1
multilist = [number * a for number in x]
print(multilist)
then print the result.
Thanks in advance
Edit:
final result for whoever needs it, thanks to Jhanzaib Humayun
num = input("Please enter desired number: ")
sumn = 0
for i in range(len(num)):
sumn+=int(num[i])**(i+1)
s = [int(n)*(i+1) for i,n in enumerate(num)]
print("Multiply result by order:")
print(s)
print("Final result:")
print(sumn)

You can use something like this:
num = input("Input a number: ")
sum = 0
for i in range(len(num)):
sum+=int(num[i])**(i+1)
print(sum)
Edit: You can use something like this if you want to use list comprehension
num = "34532"
s = sum([int(n)**(i+1) for i,n in enumerate(num)])
print(s)
By using enumerate, you get the index i and the element n. Which you can use according to your needs, and lastly sum can be used to sum upp all the elements in the array.

If the number is presented as a string then:
num = '34532'
sum_ = sum(int(n)**i for i, n in enumerate(num, 1))
print(sum_)
Output:
257
Alternative:
sum_ = sum(n**i for i, n in enumerate(map(int, num), 1))

Related

How to print a '+' between values and a'=" at the end before the result?

If the user input of the following code is 5 for example. Then the output I get is 3+33+333+3333+33333+37035. How can I have my output be 3+33+333+3333+33333=37035.
I've tried sep, end, but can't seem to get it to print the + as a separator and the = at the end before the result (=370350).
n = int(input('Enter a positive integer: '))
sequence_number=3
sums = 0
for i in range(n):
print(sequence_number, end='+') with + between each
sums = sums+sequence_number # this will add the numbers
sequence_number = sequence_number * 10 + 3
print(sums)
If you have a better way to write this code im all ears!
You have two options:
Check if this is the last iteration, and use a space instead of + if it is:
for i in range(n):
if i == n-1: end_char = ' '
else: end_char = '+'
print(sequence_number, end=end_char)
...
Append all numbers to a list, and then join them with + outside the for loop:
lhs = []
for i in range(n):
lhs.append(sequence_number)
...
print("+".join(lhs), f"= {sums}")
It'd actually be easier to keep your sequence_number as a string for repetition:
limit = 5
digit = '3'
sequence = [digit * count for count in range(1, limit+1)]
# ['3', '33', '333', '3333', '33333']
total = sum(map(int, sequence))
# 37035
print(f'{"+".join(sequence)}={total}')
# 3+33+333+3333+33333=37035
Some print statements omitted for brevity.
Use list comprehension and string operations:
lst = [str(sequence_number)*(i+1) for i in range(n)]
>>> "=".join(["+".join(lst),str(sum(map(int,lst)))])
'3+33+333+3333+33333=37035'
Using join and f-strings to build the actual string you want to print is almost always a better option than messing around with the print parameters IMO; if nothing else, it makes it easier to reuse the string if you ever need to do something other than print it.
Some other answers have shown how to do this by building a list; I'll show a way to do it with inline generator expressions. Assigning the things you'll be using more than once (namely the stringified sequence_number and the range you need to iterate over) to short variable names makes it possible to express it very compactly:
n = range(1, int(input('Enter a positive integer: '))+1)
s = "3"
print(f"{'+'.join(s*i for i in n)}={sum(int(s*i) for i in n)}")
This is a possible solution:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = sequence_number
print(sequence_number, end='')
for i in range(1, n):
print(f'+{sequence_number}', end='')
sums += sequence_number
sequence_number = sequence_number * 10 + 3
print(f'={sums}')
Another option:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = 0
for i in range(n):
print(sequence_number, end=('+' if i != n-1 else '='))
sums += sequence_number
sequence_number = sequence_number * 10 + 3
print(sums)

while loop won't works right in python

I wrote this code for summing up digits of a number which is bigger than 10 until the result only have one digit and when I try to compile it, it won't even give me an error until I stop it. I want to know what's the problem.
number = input()
#sumed_up_digits = result
result = 0
while len(number) != 1:
for i in number:
int_i = int(i)
result = result + int_i
number = str(result)
print(result)
Try the following code:
s=input()
n=len(s)
result=0
for i in range(n-1):
result=result+int(s[i])
print(result)
This for loop runs from 0th to (n-2)th index of the given string, hence the last digit will not be added to the result. Like for 1245, it will add 1,2 and 4 to result, but not 5.
result is cumulative and include previous sums.
try:
number = input()
#sumed_up_digits = sum
sum = 0
while len(number) != 1:
result = 0
for i in number:
int_i = int(i)
result = result + int_i
sum = sum + result
number = str(result)
print(sum)
You can do it like this:
number = input()
if len(number) <= 1:
print(0)
while len(number) > 1:
number = str(sum(int(i) for i in number))
print(int(number))
Of course, you would need to check that the initial input number is made of digits...
the problem is number isn't being shortened so the condition for the loop to stop is never reached.
number = input()
result = 0
while len(number) != 1:
# set digit to last number
digit = int(number) % 10
result += digit
number = number[:-1]
print(result)

I need help figuring out how to find the sum of odd numbers in python

I am struggling to write a program that finds the sum of every odd number in a list of 21. this is what I have so far...
sum = 1
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1;
total += numbers
print(total)
Any help is appreciated.
You can try either already creating a range of odd numbers simply by asking the range to "jump" by 2, starting from 1: 1,3,5,.. and then summing it all:
res = sum(range(1,21,2))
print(res)
>> 100
Or,
create the range, and filter the odd numbers, and then sum it all:
r = range(1,21)
filtered = filter(lambda x: x%2, r)
res = sum(filtered)
#or in 1 line: sum(filter(lambda x: x%2, range(1,21)))
print(res)
>> 100
You had 3 issues:
1) You called on total but never defined it (total+=numbers) while i think you meant to use sum
2) You wrote Total += numbers instead of +=number
3) In this line if number % 2 == 1: you accidentaly used ; instead of :
Here is the fixed code, Enjoy!
EDIT: I want to add that range() is non inclusive, so if you want 21 to be in the list you should use range(1,22,1)
sum = 0
numbers = range(1,21,1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
sum = 0
numbers = range(1,21+1)
for number in numbers:
if number % 2 == 1:
sum += number
print(sum)
or
sum = 0
numbers = range(1,21+1, 2)
for number in numbers:
sum += number
print(sum)
by the way:
range(start, stop, steps) doesn't include stop.
# Imported Modules
import time
import decimal
# Functions
def FindOddNums(a, b):
b = b + 1
for i in range(a, b):
# checks if i / 2 is a float and if float cannot be converted into a int if so than execute below code
if isinstance(i / 2, float) and not float.is_integer(i / 2):
# Check if b is more than 20 if so then no need to wait 1 sec before printing
if b > 20:
print(i)
elif b < 20:
time.sleep(1)
print(i)
def AskWhat():
time.sleep(1)
num1 = input("What first number do you want to check?: ")
time.sleep(1)
num2 = input("What second number do you want to check?: ")
time.sleep(1)
# User input is strings so need to be converted to ints
num1 = int(num1)
num2 = int(num2)
FindOddNums(num1, num2)
if __name__ == '__main__':
AskWhat()
Is this what you're looking for?
This actually calculates the thing but using steps is also a good way to go. But this is another way

i want to add the following from a list but the result only concatinates

Sample value of n is 5
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Expected Result : 615
You can use this.
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
out=sum([int(i) for i in n.split('+')])
if you want only the first three elements to be added then use this.
out_3=sum([int(i) for i in n.split('+')[:4]])
After splitting n is a list of strings, you should cast them to int.
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=int(n[0])
b=int(n[1])
c=int(n[2])
n = (a + b + c)
print(n)
And if necessary add try/except to handle correctly situations when not a valid number would be passed.
You just have to add 1 extra line in your code and it should be running.
You need to convert all the elements in your list to int for performing addition.
Try this :
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
n = list(map(int, n))
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Here, how you should do it:
n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = list(map(int, n.split("+")))
print(sum(n))
I have used map to convert a list of string to a list of int and sum to sum all the elements of the list. I assume you need to sum all the elements of your list. If you want to sum only first three elements, then:
a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
Note: If you are using latest version of Python, then n = map(int, n) will return a TypeError: 'map' object is not subscriptable. You need to explicitly convert object returned by map to a list.

Linear Search Code in python

This is linear search code but it is not working can anyone help me out!!
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
def lSearch(data, s):
for j in range(len(data)):
if data[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(data, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)
s is an integer, but your list will be full of strings since you append x to it.
x = raw_input('Enter the numbers into the array: ')
See here x is a string. You have not converted this to an int (unlike at other places)
If this is actually Python 3 and not Python 2 (as it says in your tags), then you should be using input() not raw_input() (raw_input doesn't actually exist in Python 3). input() will return a string in Python 3 (unlike in python2, where it might return an integer).
thanks to everyone.Now , my code is running by a simple change raw_input to input().
data = []
n = int(input('Enter how many elements you want: '))
for i in range(0, n):
x = input('Enter the numbers into the array: ')
data.append(x)
k = sorted(data)
print(k)
def lSearch(k, s):
for j in range(len(k)):
if k[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(k, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)

Categories