Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble creating loops
#2
Now there is an interesting problem.
Let's start with the easy part.
You created a function needing two parameters.
In line 2 you empty the first parameter. Why? I think you should remove that line.
In line 6 you start a loop, starting with 0 and ending with len(new_list)+1. Why "+1"? You will get out of range. And you choose a step of "-1". As the loop starts at 0, the end will never be reached. In effect, the loop does not get executed.
In line 7 you compute the sum of the list, but you do not assign the result to a variable.
In line 8 you compute the sum of the list again and compare it correctly to the input number.
In line 12 you increment the loop variable. It is bad practice to manipulate the loop variable in a for loop.

But now the interesting part. Finding the correct algorithm. That is not easy. I tried to set up an example to see what is happening. I chose a list of numbers from 1 through 5 and a target number of 8.
Output:
input list: 1 2 3 4 5 8 = + + + 8 = + + + 8 = + +
We learn from this that the numbers need not be adjacent in the list. So it will not be sufficient to take slices of the list.
The number of numbers to be added is also quite random. It may be 1 or 2 or 3 or...
The algorithm might take one number in the list, and check whether it is equal to the target number.
for i in new_list:
  if i == number:
    result += 1
Then in the next step you should check whether the target number can be found by adding just 2 numbers from the list.
for i in range(0, len(new_list):
  num1 = new_list[i]
  for j in range(i+1, len(new_list):
    num2 = new_list[j]
    if num1 + num2 == number:
      result += 1
Then in the next step you should check whether the target number can be found by adding 3 numbers from the list. Well there seems to be no end to the possibilities. Try by yourself to create a check for 3 numbers.
But we will have to find a better algorithm because there are more possible combinations than there are elements in the list. And as there is no limit on the number of elements in the list we should find something smarter.
Reply


Messages In This Thread
Trouble creating loops - by Den - Oct-19-2019, 07:36 AM
RE: Trouble creating loops - by ibreeden - Oct-20-2019, 12:43 PM
RE: Trouble creating loops - by Den - Oct-20-2019, 01:34 PM
RE: Trouble creating loops - by ibreeden - Oct-23-2019, 05:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help with creating dynamic columns with for loops for stock prices PaDat 2 1,042 Feb-22-2023, 04:34 AM
Last Post: PaDat
  Trouble with While loops jj432 1 1,895 Oct-19-2019, 01:22 AM
Last Post: Aurthor_King_of_the_Brittons
  Troubble creating loops in PyQt LavaCreeperKing 0 5,621 Mar-02-2017, 08:05 PM
Last Post: LavaCreeperKing

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020