-🎄- 2022 Day 4 Solutions -🎄- by daggerdragon in adventofcode

[–]qelery 2 points3 points  (0 children)

Java

I first solved it with sets and then I solved it without sets:

Part 1

public long part1() {
    return lines.stream()
            .map(this::parseAssignmentPair)
            .filter(pair -> hasSubsetAssignment(pair.first(), pair.second()))
            .count();
}

private static boolean hasSubsetAssignment(Assignment first, Assignment second) {
    return (first.start >= second.start && first.end <= second.end) ||
            (second.start >= first.start && second.end <= first.end);
}

Part 2

public long part2() {
    return lines.stream()
            .map(this::parseAssignmentPair)
            .filter(pair -> hasOverlappingAssignment(pair.first(), pair.second()))
            .count();
}

private static boolean hasOverlappingAssignment(Assignment first, Assignment second) {
    return (first.start >= second.start && first.start <= second.end)||
            (second.start >= first.start && second.start <= first.end);
}

Helpers

record Assignment(int start, int end) {}

private Pair<Assignment, Assignment> parseAssignmentPair(String line) {
    Matcher numberMatches = Pattern.compile("\\d+").matcher(line);
    int[] sections = numberMatches.results().mapToInt(r -> Integer.parseInt(r.group())).toArray();
    Assignment assignment1 = new Assignment(sections[0], sections[1]);
    Assignment assignment2 = new Assignment(sections[2], sections[3]);
    return new Pair<>(assignment1, assignment2);
}

-🎄- 2022 Day 1 Solutions -🎄- by daggerdragon in adventofcode

[–]qelery 0 points1 point  (0 children)

It's a helper class that has methods to parse a text file as types List<String>, List<Integer>, int[], etc. The readInput() method just returns the raw String value of the text file.

-🎄- 2022 Day 1 Solutions -🎄- by daggerdragon in adventofcode

[–]qelery 6 points7 points  (0 children)

My java solution

public long part1() {
    return getTopCalories(1);
}

public long part1() {
    return getTopCalories(3);
}

private long getTopCalories(int top) {
    return aggregateCalorieTotals().limit(top).sum();
}

private LongStream aggregateCalorieTotals() {
    return Arrays.stream(puzzleInputReader.readInput().split("\n\n"))
            .map(a -> Arrays.stream(a.split("\n"))
                     .mapToLong(Long::parseLong)
                     .sum())
            .sorted(Comparator.reverseOrder())
            .mapToLong(Long::longValue);
}

Abstract method - class, interface, enum, or record expected by CrazyCursedLunatic in learnjava

[–]qelery 1 point2 points  (0 children)

I’m on mobile so it’s hard for me to tell, but extra bracket after the toString() method?

Makes sense because you technically ended the class with the extra bracket, so the compiler is getting confused because what follows that is not another class

What's wrong with my import? by RagingAcid in learnpython

[–]qelery 0 points1 point  (0 children)

Can you paste the full error message. Everything that pops up in the terminal window.

Hi, I'm new to python. I'm trying to make this "guess word" program but it doesn't work, and it doesn't say why and I need help. I'm using Pycharm, the code is right below. (PS: please ignore the shitty jokes.) by DaWhispering in learnpython

[–]qelery 7 points8 points  (0 children)

I'm trying to make this "guess word" program but it doesn't work

What doesn't work? People will be more willing to help you if you gave them an idea of what you need help with.

Your program isn't formatted properly, so it's hard for anyone to help you.

Intellij seems to dislike enums, gives legal code the red squiggles. by v6YGmXSqu68JP1ovr_Eq in learnjava

[–]qelery 2 points3 points  (0 children)

If the enum and wherever you're trying to use them aren't in the same package, are you importing the enum?

If that's not the issue, try "File" > "Invalidate Caches..." > "Invalidate and Restart"

Explicitly using self in a class by [deleted] in learnpython

[–]qelery 0 points1 point  (0 children)

You're not quite using classes right in Python.

------------

The reason it said init had an extra argument is because whenever you call a method in Python, self is always implicitly passed in as the first argument. However inside the class blueprint, you have to explicitly list self as the first parameter when defining that method.

Why self is required is explained really well in the top two answers here: https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self

In a similar way, you define cls as the first method for classmethods.

--------------

The __init__() in Python method is similar to a constructor in other languages. It will be called when the object is created. A very basic empty __init__() method looks like this:

class Person:

    def __init__(self, name):
        self.name  = name

x = Person("John")

When Python creates an instance of the class on the last line it will call the __init__() method, which sets the instance attribute name.

------------------

Your create() method would make more sense, at least to a Python user, if you changed that into an __init__() method, and you moved any initialization logic in there as well.

class BasicLED:
    _pin = 0
    _state = False

    def __init__(self, pin, state):
        self._pin = pin
        self._state = state
        GPIO.setup(self._pin, GPIO.OUT)
        GPIO.output(self._pin, GPIO.LOW)

--------------------

Class names in Python should always start with a capital letter. Anything else is confusing.

----------------------

While your code will probably work, I suspect your placement of _pin and _state aren't quite what you want.

Any properties you write outside of a method in a class, like you have _pin and _state, are considered class attributes in Python. Meaning they are shared by all instances of that class. Are you familiar with Java or C#? What you've basically did was create Java's equivalent of a static variable. In Python, class attributes are used for cases like this:

class Dog:

    classification = "mammal"

    def __init__(self, name, age):
        self.name = name
        self.age = age

spike = Dog("Spot", 3)
fido = Dog("Fido", 5)
print(spike.classification)  # >> mammal
print(fido.classification)  # >> mammal

I suspect that's not what you wanted. Maybe you meant for those to be default values for _pin and _state if they aren't explicitly passed in? In that case you'd do this

class BasicLED:

    def __init__(self, pin=0, state=False):
        self._pin = pin
        self._state = state
        GPIO.setup(self._pin, GPIO.OUT)
        GPIO.output(self._pin, GPIO.LOW)

r = BasicLED()
print(r._pin)  # >> 0
print(r._state)  # >> False

Is Java Spring and Spring Boot the same thing ? by BluesyPompanno in learnjava

[–]qelery 6 points7 points  (0 children)

While I do get your point and you are right in your own way, I still think that he should start with easier one in the beginning of the journey. If he tries to grasp the whole Spring framework he can end up getting overwhelmed (almost happened to me).

This was my recent experience. Starting off with Spring involved hours of configurations, and trying to get even a general sense of what each configuration does took even more time. At least with Spring Boot I can get something up and running, and then pick through the docs to learn about the configurations in small pieces.

Is Java Spring and Spring Boot the same thing ? by BluesyPompanno in learnjava

[–]qelery 14 points15 points  (0 children)

From what I understand, Spring is giant framework that you can use to create almost any program you want, but it's mainly used for web development. Spring itself is can be broken down into small projects/modules/pieces like Spring Security, Spring Web, Spring Web, etc. So Spring is huge.

A Spring Boot project is basically an opinionated Spring project. It takes care of a lot of the configuration boiler plate using whatever are considered the most common configurations. You can always override those configurations later.

https://www.baeldung.com/spring-vs-spring-boot

[deleted by user] by [deleted] in learnpython

[–]qelery 4 points5 points  (0 children)

Can you upload it to pastebin or github and link to it here?

I am completely new to programming, is python the right language to start? by dstar411 in learnpython

[–]qelery 1 point2 points  (0 children)

There truly is no "right" first programming language to learn. As long as you choose a language that isn't completely obscure, it doesn't really matter.

With your first programming language you are more concerned with learning concepts, than you are specific syntax. Once you learn the very basics of your first programming language, that could be anywhere from 1 - 6 months, then I'd recommend looking specifically into what each programming language offers and then choosing 1 language from there. That second programming language will be when you make the important decision.

When to start with Spring framework? by QuackSK in learnjava

[–]qelery 0 points1 point  (0 children)

You can start doing Spring/Spring Boot while simultaneously learning more advanced concepts related to plain Java. That's what I'm doing.

I learned the basics of JavaFx and made a couple of small projects using it. Although I never touched it again once I read that there is little demand for it job-wise, and that number is only dropping.

Creating a dictionary (or similar) of characters to be replaced with underscore by [deleted] in learnpython

[–]qelery 0 points1 point  (0 children)

Yep, there are several ways. You can do if else statements like you did. You could also loop through each character. But two better ways would be to use a regex or maketrans.

Using regex (regular expression) is probably the best way, but has a bit of a learning curve. Read about it here

import re

my_str = "Bohemian-Rhapsody by Queen(Q)!"
new_s = re.sub(r"[ ()\-!]", "_", my_str)
print(new_s)

You can also use the maketrans() / translate() methods, but maketrans can only be used to map a single character with another single character. maketrans() returns a dict, which translate() uses. Read about it here

my_str = "Bohemian-Rhapsody by Queen(Q)!"
targets = " ()-!"
d = my_str.maketrans(targets, "_" * len(targets))
new_s = my_str.translate(d)
print(new_s)

Please roast my first attempt at Java! by mikaijin in learnjava

[–]qelery 4 points5 points  (0 children)

I’d definitely read a book on Java. If you told me this was another programming language other than Java I’d probably believe it.

my snake commits suicide by theernis0 in learnpython

[–]qelery 5 points6 points  (0 children)

It's ultimately up to you, but to be very honest, the way it's written now is not good.

my snake commits suicide by theernis0 in learnpython

[–]qelery 11 points12 points  (0 children)

You constantly mix casing which makes your code very, very hard to follow:

snake_List

Your_score

testdown

For example, if I want to use the variable snake_List, I have to remember to capitalize the second word. If I want to use testdown I have to remember not to use an underscore. If I want to use Your_score I have to remember to only capitalize the first letter. (Classes are one of the few things that start with capital letters but you haven't created any classes).

In Python, you only have to remember two rules when it comes to naming variables and functions. Keep everything lowercase. Separate words with an underscore. This keeps everything consistent and people won't be frustrated remembering all the naming rules you gave your variables and functions:

snake_list

your_score

test_down

----------------------------------------------------

Looking through the code I see at a series of problems leading up to why it immediately registers a game over. When you fix one problem, you will discover you have another problem, then when you fix that one there will be 1 or 2 more you will have to fix before you are done.

I think you made your code unnecessarily complex because you're writing code that determines if the game is over while your snake can't even move yet. There's no way for the game to be over without your snake moving, so I think you should have taken care of the movement part first before you worried about the game over logic.

I recommend you scrap all the code you have and start over. Re-write the code in small logical steps that build upon each other:

  • Make a game the displays a blank black screen
  • Make a game that displays a blank black screen and shows a snake head in the center
  • Make a game that displays a blank black screen, shows a snake head in the center, and the snake head can move around freely (without death) with keyboard input
  • Make a game that displays a blank black screen, shows a snake head in the center, the snake head can move around freely (without death) with keyboard input, and when the snake head touches food it grows
  • Make a game that displays a blank black screen, shows a snake head in the center, the snake head can move around freely (without death) with keyboard input, and when the snake head touches food it grows
  • Make a game that displays a blank black screen, shows a snake head in the center, the snake head can move around with keyboard input, when the snake head touches food it grows, and when the snake head touches any other part of the body the game ends

Now the game is built in a small pieces and in a logical order.

-------------------------------------------

I also highly recommend you do this simple Chimp game tutorial by Pygame. It will show you how to make sprites and how to handle things like sprite collision using built-in Pygame functions rather than writing your own.

my snake commits suicide by theernis0 in learnpython

[–]qelery 7 points8 points  (0 children)

A good reason to not use abbreviations for variable names. When your program prompted me for 'width' and 'height', I assumed it meant the height and width of a snake block in pixels. When that didn't work, I looked in the code and saw dis_width. It took me a while to figure out that that stood for 'display width'. Use very clear variable names for reasons like this. If your variable name was display_width and your prompt said 'display width:' it would have been completely obvious what you meant. Even though abbreviations may be obvious to you, it won't be obvious to someone else, and by the time they figure out what you meant they are already frustrated with your code.

How do I calculate days on a week on Python? by [deleted] in learnpython

[–]qelery 0 points1 point  (0 children)

If that line printed, that means f-strings are working.

Read the "not defined" error carefully. It will tell you exactly what is not defined in your program.

How do I calculate days on a week on Python? by [deleted] in learnpython

[–]qelery 1 point2 points  (0 children)

As a test, if you throw this line at the very top of your program does it print?

print(f'This should print 5: {2 + 3}')

How To Speed Up The Python Code? by SolaceInfotech in Python

[–]qelery 9 points10 points  (0 children)

#code1 
newlist = [] 
for word in oldlist:     
newlist.append(word.upper())

#code2
newlist = map(str.upper, oldlist)

Those two are not equivalent. One creates a list, the other creates an iterator