- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to perform given operation with each element of a list and given value in Python
Suppose we have a list of numbers called nums, we also have another string op representing operator like "+", "-", "/", or "*", and another value val is also given, we have to perform the operation on every number in nums with val and return the result.
So, if the input is like [5,3,8], then the output will be [15, 9, 24]
To solve this, we will follow these steps −
- res:= a new list
- for each i in nums, do
- if op is same as '+', then
- insert i+val at the end of res
- otherwise when op is same as '-', then
- insert i-val at the end of res
- otherwise when op is same as '*', then
- insert i*val at the end of res
- otherwise when val is non-zero, then
- insert quotient of i/val at the end of res
- if op is same as '+', then
- return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, op, val): res=[] for i in nums: if op=='+': res.append(i+val) elif op=='-': res.append(i-val) elif op=='*': res.append(i*val) elif val: res.append(i//val) return res ob = Solution() nums = [5,3,8] print(ob.solve(nums, '*', 3))
Input
[5,3,8]
Output
[15, 9, 24]
Advertisements