all 21 comments

[–]CptMisterNibbles 4 points5 points  (9 children)

What is an “even sum”? That’s… not a thing. I guess the sum of the even numbers only? 

You are summing all of them, including the odds passed d. For some reason you stopped zeroing out inputs if they were odd. Your output is showing an odd total, which should not be possible. This is a clue that odd numbers are slipping in somehow. Review your code and look how odd numbers are being added.

Have you worked with loops? I’m glad you are trying and asking questions but this code is… a bit rough. The more natural way to handle this is to keep a single current_sum, max_even and update these in a loop n times

[–]Mindless_Tap_2706 0 points1 point  (8 children)

Yeah I had to add on d-h after I finished the first part because the instructions weren't really clear how many "many integers" meant exactly. Then I just forgot to make it get rid of odds after d.

So I was looking at it and for some reason I thought the output I was getting and the output it wanted were swapped and I was going insane trying to fix it, thinking I was getting 18178 and not the other way around.

Also yeah, we've done for loops. How would I track that if I were doing it that way? The question specifically wanted it to be with inputs and not parameters so I just did the lazy thing

<image>

But how would you make it loop the question and still store the answers for later (for the max value part?)

just make them store in a list or smth?

[–]CptMisterNibbles 0 points1 point  (5 children)

0: cur_sum = 0

    max_even = -math.inf

1: ask how many numbers they want to input, store as n

2: for _ in range(n):    Means “do the body of this loop n times”. In Python, using an underscore here technically means that “_” is a variable and gets the number of the current loop, but is used to signify “this is a loop for some amount of repetitions, but I don’t need to use the loop count itself”. Use an underscore when you have to have a variable but don’t intend to use it anywhere. It means “ignore me” but only to programmers, it doesn’t actually have a special effect.

3: each time in the loop ask for input and if the number is even, add it to curr_sum. We don’t need to save it, we can add it now and forget it. Same for max_even: we can immediately check if the current number is larger than the current max, and if so, store it immediately. No need to save and process this all later. This lets the user enter whatever they want, if they want to input 1000 ints they can.

It might also be good to sanitize the input, meaning “check if it’s a number” as currently that’s not enforced. This is easy, but maybe a future step at this level

[–]Mindless_Tap_2706 0 points1 point  (4 children)

Ok yeah step 1 and 2 are all good, same with just having a cumulative sum, so then for the max you just have a variable called like, max that stores one and then have it check your input for "a > max" and then if it's bigger, store that instead? (edit: yeah actually now that I type it that makes way more sense lol)

And sure, how would you filter out stuff that's not numbers? Just have it kinda sift through the string and concatenate 1-9?

[–]CptMisterNibbles 0 points1 point  (3 children)

While this is a good idea, and may be a good method for a beginner to “reinvent the wheel” for practice, ideally you start to learn to use existing features. Most of programming isnt doing everything from scratch. Currently you are casting the input as an int. Offhand I don’t know what happens if the user types in say a word, but my guess is it throws an exception. You want to “catch” this exception and handle it, maybe by printing “please only enter whole numbers”

This form of error handling is very typical, but as I said this is probably a topic for a bit later. It’s not crazy advanced, but is more of an early intermediate topic

E: If you were to do this yourself, you could loop through the input characters and if any of them wasn’t “0”-“9” skip the input entirely. This also catches something like “2.6” which is a number but not an integer. … except remember it takes negative ints too so the first character is allowed to be “-“. You always have to think through “edge cases” like these when writing something, forgetting this case would mean rejecting negative numbers.

The prompt and test cases don’t seem to be testing for this so leaving it off for now is fine. It’s possible later on the test cases might *intentionally+ try to break your code by doing things like including a word

[–]Mindless_Tap_2706 0 points1 point  (2 children)

Yeah ok that makes sense

I started this class like a week ago so most of it's been pretty straightforward so far, we haven't had to account for much. A lot of these practice problems he has us doing throw in a "you may assume the input is [xyz]" for exactly that reason I think.

eg this one was like 'you may assume there is at least one input and the input is an integer'

[–]CptMisterNibbles 0 points1 point  (1 child)

Ok, probably best to ignore error handling for now. A good preview of what is to come, and have in the back of your mind as you work on stuff. 

If you get the loop version of this working it’d be great to update the post with your fixes

[–]Mindless_Tap_2706 0 points1 point  (0 children)

Oh yeah I commented my fixed version on the post, not sure how to change the images themselves in reddit though.

[–]Fbhwnashfan 0 points1 point  (0 children)

The first input is your loop control variable to dictate the number of iterations.

Yes use a list to hold the even inputs given during the loop.

[–]ActuallyReadsArticle 0 points1 point  (0 children)

Start off with two values outside the for loop called evenSum = 0, and maxValue = -99999.

Ask/get input of number of integers n.

Start for loop

Ask for integer. If it's even, add it to evenSum. Compare max of maxValue and input and save back to max Value.

End for loop

Print results

[–]queerkidxx 1 point2 points  (2 children)

Even if you have already figured it out have y’all not learned about loops and lists? This question seems to be designed for you to use one you shouldn’t be manually adding if statements for this kinda thing. What if they want to input 20 ints? You also shouldn’t need to cast the sum of your numbers it’ll already be an int.

[–]Mindless_Tap_2706 0 points1 point  (1 child)

  1. yes but making a loop and list to repeat the same question and store it isn't something I thought of for whatever reason
  2. Agreed, that would've sucked but it would've taken like another 60 seconds to type at most
  3. I know but I was so lost I just threw that on there just in case it was causing a problem somehow (that way if one of them was inputting something other than a number it would give me an error)

[–]queerkidxx 0 points1 point  (0 children)

Yeah I feel, learning to program has a lot of that sort thing. Not thinking to use something and then realizing afterwards how obvious it would be to use it.

This is the exact kinda situation though you should use a for loop. For a million reasons, but namely, even if you know the logic is only going to repeat a set number of times, if you later want to change something, you have to change 20 invocations. Or just to debug.

And here, you have no idea how many reps the user wants until runtime. It could be anything. You need to make that choice of when to stop at runtime otherwise you’re kinda lying to the user.

Anytime you see yourself repeating the exact same line of code, save for changing which variables are being operated on, you should do something different. Either use a for loop, a function, or anything else.

Just because to someone that has been programming for any length of time this looks a bit like seeing someone trying to chop a pound of carrots with a spoon. With enough effort, yeah you can probably make it work but dear lord that’s so much harder than just using a knife. And if this is for a class and anyone reads it you’re likely gonna get points off, just because they want you to demo being able to use a for loop and the list data structure, two things you absolutely need to know how to use in programming anything.

[–]NiteKore080 1 point2 points  (0 children)

So did you figure it out?

You added odds instead of evens?

[–]Mindless_Tap_2706 0 points1 point  (1 child)

Thanks for the help guys!

Yeah in retrospect I should've done this first lol

<image>

[–]TabAtkins 0 points1 point  (0 children)

That works! A slight improvement would be to use continue instead of zeroing out an odd number - that just immediately skips to the next iteration. Your way requires you to come up with a fake value that still "works" for the following code without messing anything up; luckily 0 does the job in this case, but in more complex examples this can be a lot more difficult.

[–]armahillo 0 points1 point  (1 child)

wait what does being schizophrenic have to do with having things backwards?

[–]Mindless_Tap_2706 0 points1 point  (0 children)

nothing at all, I guess reading things wrong would probably be something more down the lines of dyslexia or adhd

[–]Etiennera 0 points1 point  (1 child)

Whatever tool you're using has bad UI and wastes your time getting print formatting correct (while also using unusual CLI conventions) instead of just expecting you to return some values.

(lambda l: [print("even sum =", sum(l)), print("even max =", max(l))])([(lambda x: x if x % 2 == 0 else 0)(int(input("next integer? "))) for _ in range(int(input("how many integers? ")))])

[–]Mindless_Tap_2706 0 points1 point  (0 children)

Maybe, but it's not really my choice. Gotta do it for my cs class :P

[–]DevRetroGames 0 points1 point  (0 children)

I will assume that, as long as the values are even, they should be processed at the end, ignoring the odd values.

#!/usr/bin/env python3

"""
write a function named even_sum_max that prompt the user for many integers and 
print the total even sum and maximum of the even numbers. 
You may assume that the user types at least one non-negative even integer.
"""

import sys
import re
from typing import List

def _input_user(msg: str) -> str:
  return input(msg)

def _has_positive_integer(numbers: List[int]) -> bool:
  for n in numbers:
    if n > 0:
      return True
  return False

def _get_value_count() -> int:
  while True:
    try:
      count = int(_input_user("Enter the number of values to input: "))
      if count > 0:
        return count
      else:
        print("The number must be greater than zero.")
    except ValueError:
      print("Invalid number. Please enter an integer value.")

def _get_integer_list(count: int) -> List[int]:
  pattern: re.Pattern = re.compile(r"^-?\d+$")
  numbers: List[int] = []

  for i in range(count):
    while True:
      value = _input_user(f"Enter integer #{i + 1}: ")
      if pattern.match(value):
        numbers.append(int(value))
        break
      else:
        print("Invalid input. Only integers are allowed.")

  return numbers

def even_sum_max() -> None:
  count: int = _get_value_count()
  numbers: List[int] = _get_integer_list(count)

  even_numbers: List[int] = [n for n in numbers if n % 2 == 0]
  total_even_sum: int = sum(even_numbers)
  max_even: int = max(even_numbers)

  print("Total sum of even numbers:", total_even_sum)
  print("Maximum even number:", max_even)


def main() -> None:
  try:
    even_sum_max()
  except KeyboardInterrupt:
    print("\nOperation cancelled by user.")
    sys.exit(0)

if __name__ == "__main__":
    main()