I have problem with using the *mul* operator to multiply varibales - python-3.x

I splited and converted string into int and i want use the mul
operator to multiply directly. But they is an error when printing the last output.
from operator import mul
# mulptiply user input
input_string = input("Enter numbers for summing :")
print("/n")
user_list = input_string.split()
print('list:', user_list)
# for loop to iterate
for x in range(len(user_list)):
user_list[x] = int(user_list[x]
# calc the mul of the list
print("Multiplication of list =", mul(user_list))

The mul function takes 2 arguments at a time and returns their product. If you want to use mul to calculate the product of a list of numbers you can use functools.reduce to apply the function cumulatively to every list item for an aggregated result:
from functools import reduce
from operator import mul
user_list = [2, 3, 4]
print(reduce(mul, user_list)) # outputs 24
Beginning in Python 3.8 you can also use math.prod to calculate the product of a list of numbers directly.

Related

How to write a function in Python to perform subtraction on numbers that are given as arguments? for eg, subt(a, b, c...) O/P : value of a-b-c- [duplicate]

This question already has answers here:
What is a subtraction function that is similar to sum() for subtracting items in list?
(3 answers)
Closed 3 months ago.
Require to write a Python function to perform the subtraction operation on multiple numbers (left to right direction) given as arguments.
User should be able to give a variable number of arguments to that function.
For eg, subt(a, b, c…) must return the value of a-b-c-… where a, b, c are the numbers given as arguments to the function
Initially I wrote a function to perform subtraction operation on two numbers as below:
def subt(a, b):
return a-b
later, I extended it for three numbers as below:
def subt(a, b, c):
return a-b-c
Now I want to extend the above function for variable number of arguments but do not know how to proceed from below:
def subt(…):
diff =
for i in range(…,len(…)):
diff = diff - […]
return diff
What you are looking for is *args argument.
def subt(*num):
diff = num[0]
for i in range(1,len(num)):
diff = diff - num[i]
return diff
What does the asterisk in front of the argument do? It takes as many arguments you give and wraps them in a list object. Thus
diff(1,2,3) #=> *num = [1,2,3]
PythonTips have a full Section on *args and **kwargs.
The upper answers are correct, but I want to make it a bit more pythonious!
def subt(*nums):
first_num = nums[0] # The first number
for num in nums[1:]: # index 1 to the last number
first_num -= num
return first_num
print(subt(33, 2, 3, 4, 7)) # -> 17
print(subt(13, 7)) # -> 6
Method 2
def subt(*nums):
first_num = nums[0] # The first number
sum_of_rest = sum(nums[1:]) # The sum of all the number except the first number
# Or you can say, sum of numbers from index 1 to the last
# nums[1:] -> list slicing. More info in the comments
return first_num - sum_of_rest
print(subt(33, 2, 3, 4, 7)) # -> 17
print(subt(13, 7)) # -> 6
Method 3
I just wanted to make this shorter for python one-liners.
subt = lambda *n:n[0]-sum(n[1:])
print(subt(33, 2, 3, 4, 7))
There are two methods to solve this:
Method-1
Using the logic for subtraction a-b-c-… = ((a-b)-c)-…
def subt1(*numbers): # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.
try: # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.
diff = numbers[0] # assigning the first element/number to the variable diff
for i in range(1,len(numbers)): # iterating through all the given elements/ numbers of a tuple using a for loop
diff = diff - numbers[i] # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c
return diff # returning the final value of the above operation
except: # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed
return 'please enter numbers as arguments'
subt1(10, 5, -7, 9, -1) ----> here subt1 performs 10-5-(-7)-9-(-1) and returns the value
4
subt1(25.5, 50.0, -100.25, 75) ----> here subt1 performs 25.5-50.0-(-100.25)-75 and returns the value
0.75
subt1(20j, 10, -50+100j, 150j) ----> here subt1 performs 20j-10-(-50+100j)-150j and returns the value
(40-230j)
subt1() ----> here the statement in the except block is returned as no input is passed
'please enter numbers as arguments'
subt1('e', 1, 2.0, 3j) ---> here the statement in the except block is returned as a string 'e' is passed which is not a number
'please enter numbers as arguments'
Method-2
Using the logic for subtraction a-b-c-… = a-(b+c+…) = a-add(b,c,…)
def subt2(*numbers):
try:
add = 0 # initializing a variable add with 0
for i in range(1,len(numbers)):
add = add+ numbers[i] # performing the addition operation for the numbers starting from the index 1
return numbers[0]-add # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)
except:
return 'please enter numbers as arguments'
subt2(10, 5, -7, 9, -1) ----> here subt2 performs 10-5-(-7)-9-(-1) and returns the value
4
subt2(25.5, 50.0, -100.25, 75) ----> here subt2 performs 25.5-50.0-(-100.25)-75 and returns the value
0.75
subt2(20j, 10, -50+100j, 150j) ----> here subt2 performs 20j-10-(-50+100j)-150j and returns the value
(40-230j)
Note : All the above test cases have been tested in Jupyter notebooks.

Currying in python

I wrote the following function
def addsub(a):
def add(a):
def subtract(b):
return a-b
return subtract
return add(a)
addsub(9)(4)
returns 5
but what if I do not know to number of add subtract I want to perform
addsub(9)(3)(4)(5).
The above function does not work for it
could I write something general which works for any length of input?
PS. I do not want to use functools
It is not possible exactly like you describe (with currying). But if all you want is to sum the numbers of a list with a varying sign, this looks the most straightforward to me:
import itertools
coefficients = itertools.cycle((1, -1))
numbers = [9, 3, 4, 5]
result = sum(a * c for a, c in zip(numbers, coefficients))

How to multiply each integer "one by one" and display result "in progressive order" until all integers multiplied leads to the overall product

Recently, I've tried creating a for loop that multiplies each integer in the list and returns each sequential product until the overall product of all integers is given.
import operator
from operator import mul
from functools import reduce
s = list(map(int, input('Enter numbers WITH SPACES: ').split(' ')))
progression_product = [];
for i in s:
progression_product.append(reduce(mul, s[0:i]))
#This loop below removes repeating results. As for progressive order multiplication of positive
#integers. It's impossible to have a repeating result.(excluding multiple 1's and 0)
for ss in progression_product:
if progression_product.count(ss) > 1:
progression_product.remove(ss)
print(progression_product)
-
Notice that the output skips the result for 13 below. But finishes correctly for the overall product of all integers at the end of the listed output
Enter numbers WITH SPACES: 12 2 3 4 13 133
[24, 72, 288, 497952]
> 12*2*3*4*13
>3744
Question
Is there any way to fix this bug? Why would python skip the result at 13? And, how do I fix it?
You are iterating over the elements of s, not the indexes. Print the list before removing the duplicates, it will be:
[497952, 24, 72, 288, 497952, 497952]
# Which are the products of:
[s[0:12], s[0:2], s[0:3], s[0:4], s[0:13], s[0:133]]
Replace the first loop by a index loop, either by range(len(s)) or by enumerate(s):
# Either this:
progression_product = [];
for i in range(len(s)):
progression_product.append(reduce(mul, s[0:i]))
# Or this:
progression_product = [];
for i, v in enumerate(s):
progression_product.append(reduce(mul, s[0:i]))

How can i convert many variable to int in one line

I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)
You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]
Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].
This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.
There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)
You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!

Most efficient way to make range between 2 numbers

Right now i'm using the simple for loop,
p1 += ([(x,i) for i in range(j,y+1)])
Just an example from my code, i'm making ranges of tuples, for example
j = 1, y= 9998 , x=1
So I should get (1,1),(1,2)......(1,9998) It's a list of tuples.
The loop will take a lot of time if we having big number.
There is a way to improve without using libraries.
You can use the zip(iter1, iter2, ...) function to create an iterator wich yields a tuple consisting of the elements in the iterables passed in the argument.
Use itertools.cycle() to provide the constant element in your tuples.
You can save time if you use the iterator returned by the zip() (i.e not making it a list()), but you can only use that once. If the iterator is exhausted you need to create a new one, but that is ridiculously fast.
That way is about 30% faster, on Python 3.7.1
Here is the code to test it yourself:
import timeit
from itertools import cycle
x = 5
j = 1
y = 10000
def method1():
return [(x, i) for i in range(j, y + 1)]
cycling_x = cycle([x])
def method2():
return list(zip(cycling_x, range(j, y + 1)))
print(timeit.timeit("method1()", number=10000, globals=globals()))
print(timeit.timeit("method2()", number=10000, globals=globals()))
>>> 10.956179626
>>> 7.571100585999998
The zip() function combines two iterators into a series of tuples. itertools.repeat() creates an iterator that always yields the same object.
import itertools
zip(itertools.repeat(x), range(j, y+1))
This will return a lazy iterator, which you can loop over once (e.g. for a, b in zip(...): ...). If you want all of the tuples collected into a list which you can access repeatedly and out of order, call list() on the result of zip(...).

Resources