
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Buying Cars in Python
Suppose we have a list of prices of cars for sale, and we also have a budget k, we have to find the maximum number of cars we can buy.
So, if the input is like [80, 20, 10, 30, 80], k = 85, then the output will be 3 as we can buy three cars with prices 20, 10, 40
To solve this, we will follow these steps −
count := 0
sort the list prices
for i in range 0 to size of prices, do
if prices[i] <=k, then
k := k-prices[i]
count := count + 1
otherwise,
come out from the loop
return count
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, prices, k): count =0 prices.sort() for i in range(len(prices)): if(prices[i]<=k): k = k-prices[i] count += 1 else: break return count ob = Solution() p = [80, 20, 10, 30, 80] print(ob.solve(p, 85))
Input
[80, 20, 10, 30, 80], 85
Output
3
- Related Articles
- Alternative Evaluation In Buying Decisions
- Organizational Buying Behaviour
- Problem Recognition in the Buying Process
- Factors Influencing Organizational Buying
- What are the upcoming cars in 2018?
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Classification of Consumer Buying Motives
- Compulsive Buying Behavior: Meaning & Examples
- Causes of Compulsive Buying Behavior
- Patterns of Compulsive Buying Disorder
- Psychological Models of Buying Behavior
- Factors Affecting Consumer Buying Behavior
- Program to find maximum profit after buying and selling stocks at most two times in python
- How to invest in crypto without buying crypto?
- Program to find the maximum profit we can get by buying on stock market once in Python

Advertisements