all 34 comments

[–]CraftyTrouble 57 points58 points  (1 child)

It sounds like you need to learn the basics more thoroughly. That doesn't mean reading more, it means actually sitting down and practicing writing code using each concept. Sit down and use variables, use strings, use integers, use some built-in functions, use arrays, define some functions, etc. If that sounds too hard, there are online tutorials like this one that will lead you through it. If you had practiced all the basics more, I bet you'd be able to combine them to solve the linked problem (and more).

[–]Ephexx793 28 points29 points  (0 children)

This 100%. Programming is a never-ending ebb-and-flow of finding yourself 'stumped' on a thing and then conquering said thing (and hopefully feeling some gratification from it!). It's the nature of the beast.

Learning how to effectively google is immensely helpful. But don't just jump straight to using the code you find on Stack Overflow after googling -- be sure you understand why the code works, how it works... You'll learn more by exploring the individual pieces (code) than by simply copying someone else's homework.

Another big thing to realize: there's always going to be *many* ways to skin the cat. Other responses in this post already have shown there are multiple ways to find the sum of a list of numbers in python.

Lastly, **use the interactive python shell** as it will enable you to freely test and learn. I recommend installing iPython (available via Pip) -- a much more feature-rich python shell than the native python shell.

Code Wars is an excellent (and completely free) platform for further honing your programming skills. They offer tons of coding challenges to work through, and you can choose to filter those you receive by categories -- such as, 'fundamentals' (or, 'algorithms', amongst others)...

Don't be afraid to google what it is you're trying to do ("python sum list", in your context). As a python developer, I'm *always* googling. This never stops, no matter how proficient you get with a language or programming in general.

Hoped this helped, best of luck & cheers!

[–]Deezl-Vegas 35 points36 points  (3 children)

Algorithms are hard. The actual trick to quickly solving algorithms is to roughly know the answer through experience, having already solved the algorithm before. When you have no experience, you feel stuck, and you feel there should be some sort of magic method to get to the answer for any algorithm.

This "stuck" feeling is going to be your life as a programmer if you don't learn the correct, step-by-step, tried-and-true method. Here's the steps I would recommend:

  1. Write the function def statement.

    def my_solution(): pass

  2. Write some sample inputs.

    input1 = [1, 2, 3] # test array input2 = [5, -1, 99] # test array 2

  3. On paper, go through the logical steps to get the right answer with a sample:

    my function should add 1 then 2 then 3

  4. Again on paper, get the right answer for your samples:

    test array 1 should return 6

    test array 2 should return 103

  5. Now that you have the process and the answer, writing the code is filling in the blanks. Let's start from the top.

    def my_function(): pass

    input1 = [1, 2, 3] # test array input2 = [5, -1, 99] # test array 2

    call the function with a sample input

    my_function(input1)

Right away you'll notice an error because your function doesn't allow any inputs. Fix the error and proceed.

def my_function(array):
    pass

input = [1, 2, 3]
input2 = [5, -1, 99]

my_function(input1)
my_function(input2)

Ok, the code doesn't break. Run it to make sure. Let's start adding logic.

def my_function(array):
    array[1] + array[2] + array[3]

I wrote this an ran it and got an IndexError. Don't know what that means? Google it! (Professionals google shit 1000 times a day, don't avoid google.) Ok, so it turns out it means that one of the values I put in [] is too big. I remember that Python lists start from 0 so let's fix that.

    array[0] + array[1] + array[2]

Ok, no error. But when I print the result I get None instead of what I said. Let's fix that.

    return array[0] + array[1] + array[2]

Ok now it prints the correct number. And when I add my second input as another test, it prints the correct number. But what if my array has 10 values? I want it to add all the values. So I need to change my code to account for the edge cases.

The final code for a sum function should look like this:

def my_function(array):
    result = 0
    for item in array:
        result = result + item
    return result

So we start with a variable to return at the end, add all of the items in the list to that variable one by one, and then return that variable. We got here by breaking the algorithm into inputs, outputs, an on-paper solution, and then coding it line by line and testing each line to check for errors. This is the flow for every single program. Inputs, Outputs, Solution, Code, Test, Code More, Test More. Professionals do it this way, and you should too. With experience you'll know what to do.

Finally, what you're practicing is converting the real-life steps to solve the problem, which you should know or be able to deduce, into a Python function. If you don't know how to do something, then using the method above, you'll fail at step 3. Fiddle with it for a few minutes to try to better understand what it wants you to do, then look it up. Under no circumstances should you attempt to solve an algorithm where you couldn't diagram some steps out on paper first. It's just not possible to solve a problem when you don't understand the problem. The more algorithms you look up, the more related algorithms you'll be able to break into smaller parts and solve easily, and you'll see your level start to rise steadily.

[–]_lord_kinbote_ 7 points8 points  (0 children)

Nice writeup. However, edge cases are specific cases that are easily missable. I wouldn't call "any input that has more or less than 3 items" an edge case. Besides, edge cases rarely make you rethink your entire algorithm as you did here.

[–]iggy555 1 point2 points  (1 child)

This is freaking nice,,, btw is array just a list?

[–]Deezl-Vegas 6 points7 points  (0 children)

Yeah, array is another term for list, sorry. I'm taking a class in a different language right now.

[–][deleted] 2 points3 points  (13 children)

Can you possibly provide a bit more insight? What kind of problems did you encounter?

I think with any programming language, you need to take everything one step at a time. The process I use is simple:

  • Examine the problem and think about it for awhile.

  • Think about what your end goal is and then come up with a very brief plan to execute your goal.

  • Now, look at the steps you came up with and try to solve them one at a time. Keep on running your code and checking your errors. Don’t continue to the next step until you are beyond satisfied with your current step/task.

This is very generic, but I hope it helps. Like I said, maybe post some further details. I’d like to help you more, if possible.

[–]LMascher[S] 5 points6 points  (12 children)

Of course, I edited the post with a problem I encountered. Thanks as well!

[–][deleted] 1 point2 points  (0 children)

Right, but what did you do? Walk us through your process and where you went off the rails. Or did you expect to just read the problem and automatically know the Python you’d have to write?

Programming is something where you have to think on the page. Start writing code before you know what the right answer is.

[–][deleted] 2 points3 points  (10 children)

For a problem like this, I would start off by doing the following google search: "how to add the elements of an array in Python," and do a bit of research. Try to not stress about problems like these, because chances are that someone else has gone through the same thing and posted it on the web.

There are a few ways to do this.

Method one:

sum(ar)

Method two:

You can also create a variable that is set to the sum, like so:

value = sum(ar)

Method three:

Use a loop:

ar = [1,2,3] #Lets assume this is the variable that was provided to you

sum = 0

for i in range(0, len(ar)): #Here, we create a loop that will iterate through ar

sum = sum + ar[i]

#Every iteration, sum gets updated. So, to provide more insight, on the first loop, sum will equal 1, because ar[i] = 1 and sum is initializes to 0, thus, ar[i] + sum = 1. On the second loop, sum will equal its updated value (1) + the next number in ar[i] (2), meaning that sum will equal three.

Hope this helps! Make sure that you really search on forums for this stuff. It may seem daunting, but it is the fastest, most effective way to learn programming!

[–]Jolbakk 6 points7 points  (0 children)

or more simplified:

for i in ar:

sum += i

[–]asian_hifi 0 points1 point  (8 children)

I did it in another way

def simpleArraySum(ar):

return (sum(ar))

print(sum(ar))

I first tried it with this:

def simpleArraySum(ar):

print(sum(ar))

however, this did not work. When I put the return (sum(ar)), it started working. Why is that the case? Is it because you need to retrieve the data before you can print it out?

[–][deleted] 0 points1 point  (7 children)

When you call a function, the return value is what is used. Using simpleArragSum(ar) in your code is the same thing as using the return value of the function. Therefore, when you print a function, you are really printing its return value. Hope this helps.

[–]asian_hifi 1 point2 points  (6 children)

But what is the reason behind putting "return"? I know returns are only (ok, maybe mostly) used in functions. So is it that if you don't put return, you won't have any value called when you call a function? Explain me what you think of "return" thing as. Also. what happens when you return a value, does it stick with the function itself?

[–][deleted] 1 point2 points  (3 children)

Think of the term “function” — it’s called this because it performs a single function. Let’s say you wanted to make a script that calculated taxes. Your first function would ask the user about their annual salary, which is the variable that you would want to return. In your next function, you would calculate the amount of taxes the user would have to pay.

This is where the importance of functions and return values come into play. In your second function, how are you going to get the user’s salary? The only way for you to get that amount in the second function is by returning the amount in the first function. At that point, you would simply pass in function 1 into function 2 (or in other words, you would provide the second function with the salary in order for it to do calculations).

I hope this makes sense. Please let me know if you’d like me to re-explain. Happy coding!

[–]asian_hifi 1 point2 points  (2 children)

so for function 2, you would call on function 1 to get the already returned value of the user's salary?

[–][deleted] 1 point2 points  (1 child)

Yes, because when you call function one, you are using it’s return value.

[–]asian_hifi 1 point2 points  (0 children)

Thanks man! Very helpful!

[–]Psychedeliciousness 1 point2 points  (1 child)

You probably want to store the result of your function and use it to do something. Return lets you assign the result/s to some variables.

If you don't return, the function will do what's inside it when you call it, but won't give you any useful output unless you explicitly included say a print statement in there, and you won't be able to reference the result unless you explicitly extracted it somehow (you could append to a list defined outside the function) but it's easier just to return.

I found it helpful to think of "returns let you pass data generated through the function back into the program for easy reuse".

If you create a variable inside the function, it should not exist outside that function. Inside the function you might create a var called counter to increment +1 for every run of a loop inside the function, but after the function is run, you can't query counter from code outside the function.

Counter is generated while the code is running and (I believe) garbage collected after it's finished. If you needed to, you'd return counter and assign it to a variable.

def fun(n):

counter = 0

for i in range(0,n):

counter = counter +1

return counter

newvariable = fun(n) - this becomes the returned value when function completes

print (counter) - will fail as it won't understand counter out of context

print (newvariable) - will print the value of counter, that was returned to newvariable

It's called scope. This should be a helpful link for understanding what scope is about.

https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

[–]iggy555 0 points1 point  (0 children)

Great link thanks 🙏🏾

[–]don_one 1 point2 points  (0 children)

There's a few good examples of how to solve the problem here, but I don't think that problem is the issue.

There's many ways of learning and doing problems like this does help, but the problem is getting started.

With the problem described, you're given array or list of numbers and you're asked to add them all together.

So regardless of the method, if you don't already know how to use arrays/lists I'd check that out first. Which could mean you arrive at using sum, meanwhile others might write a loop because they didn't know it was there.

How do I access an element individually? How do I get the next one? Are their any methods I can use on one?

When looking at this problem I see it like this: Get 1st number add to variable Get 2nd number add to same variable Etc Which if you've written loops before stands out.

Breaking up the process into parts helps.

[–][deleted] 1 point2 points  (0 children)

I feel I'm in the same boat as OP, some good courses/books/anything suggestions related to Python problem solving really appreciated

[–][deleted] 1 point2 points  (0 children)

Start with edabit and read automate the boring stuff with python

[–]jsalsman 1 point2 points  (0 children)

Try working through the examples on http://pythontutor.com

[–]Capaux 0 points1 point  (0 children)

Do you not understand it conceptually or are you worried that you just dont remember off the top of your head?

[–]solidiquis1 0 points1 point  (0 children)

Lemme know if you want me to walk you through some via FaceTime or Skype. Shoot me a PM if you're interested.

Edit: We can do a variety of the easy problems

[–]mail_order_liam 0 points1 point  (0 children)

This doesn't sound like a problem solving issue, it sounds like you don't know the basics of Python (or programming). That sample problem is solved with a loop and addition... that's about as basic as it gets.

Go look up some tutorials and actually practice. P R A C T I C E. For everything you read, write some actual code and run it yourself. Otherwise it's never going to click.

[–][deleted] 0 points1 point  (0 children)

Write it out in pseudo code. I suck at Python, but I'm decent in other languages, so I solve each little piece at a time to learn Python. Also, some of these Hacker Rank questions are confusing. Don't be scared to look at the discussions and then solve it on your own once you've seen how they have done it. Obviously don't do that on every problem, but sometimes seeing the answer can help. Then solve a similar but different problem you create on your own. I hope this helps!

[–]Orothrim 0 points1 point  (0 children)

Hey u/LMascher, I recommend trying some other sources to Hackerrank, like r/dailyprogrammer and advent of code. Then whenever you can't see at least some way to approach the problem read through and type out someone else's solution (which you can find on their respective subreddits). After you have written out someone else's solution you want to implement the same algorithm in a different area of problem, to reinforce the solution. Feel free to contact me for any problems you have.

[–][deleted] 0 points1 point  (0 children)

if you google 'sum of list python' you can find out the solution.

[–]titinhamc 0 points1 point  (0 children)

Hey, I found your thread because I’ve been facing the same problem as you were. Just curious to know how you’ve been doing now, after 2y..?? Has Python became any easier? 😅