Algorithm for finding if an array is balanced [closed]

2024/7/7 6:53:48

I'm trying to create a program that will create a 10 element array and then assign random values to each element. I then want the program to tell if the array is balanced. By balanced I mean, is there anywhere in the array values that at a certain element the sum of the values in the elements are equal to the sum of the array values in the elements greater than that current element.

Example

Element (1,2,3,4) Values (2,1,3,0) The program would then display that elements 1-2 are balanced to elemtns 3-4, because they both equal 4.

So far I have

import randomsize = 10
mean = 0
lists = [0] * size
for i in range(size):var = random.randint(0,4)lists[i] = varfor i in lists:mean += iavg = (mean)/(size)

I figured the only way the elements could be balanced is if the values average is equal to 2, so I figured that's how I should start.

I'd appreciate any help in the right direction.

Answer

If I understand the question, the simplest solution is something like this:

def balanced(numbers):for pivot in range(len(numbers)):left_total = sum(numbers[:pivot])right_total = sum(numbers[pivot:])if left_total == right_total:return pivotreturn None

For example:

>>> numbers = [2, 1, 3, 0]
>>> balanced(numbers)
2
>>> more_numbers = [2, 1, 3, 4]
>>> balanced(numbers)

(That didn't print anything, because it returned None, meaning there is no pivot to balance the list around.)


While this is the simplest solution, it's obviously not the most efficient, because you keep adding the same numbers up over and over.

If you think about it, it should be pretty easy to figure out how to keep running totals for left_total and right_total, only calling sum once.

def balanced(numbers):left_total, right_total = 0, sum(numbers)for pivot, value in enumerate(numbers):if left_total == right_total:return pivotleft_total += valueright_total -= valuereturn None

Finally, here's how you can build a program around it:

size = 10
numbers = [random.range(4) for _ in range(size)]
pivot = balanced(numbers)
if pivot is None:print('{} is not balanced'.format(numbers))
else:print('{} is balanced, because elements 1-{} equal {}-{}'.format(numbers, pivot+1, pivot+2, size+1))
https://en.xdnf.cn/q/120346.html

Related Q&A

Merging two dataframes in python pandas [duplicate]

This question already has answers here:Pandas Merging 101(8 answers)Closed 5 years ago.I have a dataframe A:a 1 a 2 b 1 b 2Another dataframe B:a 3 a 4 b 3I want my result dataframe to be like a 1 3 a …

Searching for the best fit price for multiple customers [duplicate]

This question already has an answer here:Comparing multiple price options for many customers algorithmically(1 answer)Closed 10 years ago.A restatement of Comparing multiple price options for many cust…

Can we chain the ternary operator in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.The com…

evaluate a python string expression using dictionary values

I am parsing a text file which contain python "string" inside it. For e.g.:my_home1 in houses.split(,) and 2018 in iphone.split(,) and 14 < maskfor the example above, I wrote a possible di…

How to simply get the master volume of Windows in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 1 year ago.Improve …

Python: Adding positive values in a list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Python IM Program [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Changes in Pandas DataFrames dont preserved after end of for loop

I have a list of Pandas DataFrames and I want to perform some operations on them. To be more precise, I want to clean their names and add new column. So I have written the following code:import numpy a…

How can I prevent self from eating one of my test parameters?

I have in my test module:import pytest from src.model_code.central import AgentBasicclass AgentBasicTestee(AgentBasic):pass@pytest.fixture() def agentBasic():return AgentBasicTestee()@pytest.mark.param…

distance from a point to the nearest edge of a polygon

in the below code i want to calculate the distance from a point to the nearest edge of a polygon.as shown in the results section below, the coordinates are provided.the code posted below shows how i fi…