#homework basic python

99 messages · Page 1 of 1 (latest)

sullen kelp
#

What code do you have right now?

limber plover
#

Nothing really

#

I have a class with the dunder init and str

#

I have opened the file using with as

sullen kelp
#

Could you just share what you have?

#

!format

topaz stagBOT
#
Code Formatting

When sharing code with the community, please use the correct formatting for ease of readability.

Example

```py
YOUR CODE HERE
```

Those are back ticks not single quotes, typically the key above TAB

limber plover
#

Absolutely

#

I’ll do so in a sec tho, I’m on the train rn

sullen kelp
#

Easier than explaining it lol

limber plover
#

I dont have discord on my laptop

#

Could I send a picture

#

The code is not very long

sullen kelp
#

You just said you have nothing lol

limber plover
#

Yea but you asked me to share what I had

#

What did you mesn by that

sullen kelp
#

Share your code

#

Not as a photo preferably

narrow cloud
#

You can readlines below row 0,
then use split() on each line to make out of 1 string a kist of strings (based on seperator)
append this list on another list (so you have a list of lists)

You need to create a class for your country objects (best to also have a class attribute for appending each new created object and one class method to get a list of these objects)

Then it just matters how you builded up your class and you can take the list_list with a for loop and go through it.
Then do smth like:
CountryClass(element[0], element[1]...)

and so on for the list elements per line.
There you have your clas with a object list you can call 🙂
(you csn also create the objects while reading in lines, so you dont need to create a list first)

hybrid pine
#

Hey @limber plover, Could you please share some of the code you’ve written so far? It would help the community better understand where you’re encountering issues, and we can provide more specific guidance.

sullen kelp
#

Literally what I was saying lol

hybrid pine
hybrid pine
limber plover
#

Thanks a lot

#

You’re too kind

#

Sorry for being afk

#

I was in a call and had my hands full

#

But I think I’ve made some headway in the code

#

class Land():
    def __init__(self, namn, folkmÀngd, landlÄst):
        self.namn = namn
        self.folkmÀngd = folkmÀngd
        self.landlÄst = landlÄst

    #def __repr__(self):
        #return f" Namn: {self.namn}"
 


lista_lÀnder = []
with open("europa.txt") as infil:
    infil.readline()
    for line in infil:
        lista = []
        for word in line.split(","):
            if word:
                lista.append(word.strip())

        land = Land(namn=lista[0], folkmÀngd=lista[2], landlÄst=lista[3])
        lista_lÀnder.append(land)
        
for land in lista_lÀnder:
    print(land.namn)

#

this is my code rn

#

so I had an issue with converting a file into lines which creates an object of each file

sullen kelp
#

btw using code blocks means discord won't screw up your code

#

!format

topaz stagBOT
#
Code Formatting

When sharing code with the community, please use the correct formatting for ease of readability.

Example

```py
YOUR CODE HERE
```

Those are back ticks not single quotes, typically the key above TAB

sullen kelp
#

Instead, you can directly loop over infil to get each line, or loop over infil.readlines(), or infil.read().split("\n")

limber plover
hybrid pine
#

Convert the 'folkmÀngd' value to an integer when you create the 'Land' object. This is how you can update the code:

land = Land(namn=lista[0], folkmÀngd=int(lista[2]), landlÄst=lista[3])

This way, the population is stored as an integer, allowing you to use it for numerical operations, such as sorting countries by population or performing calculations. Just make sure the file data is correctly formatted (i.e., no missing values) to avoid errors during conversion.

sullen kelp
#

Could you use code blocks? It's hard to read your code

hybrid pine
# sullen kelp Could you use code blocks? It's hard to read your code
    def __init__(self, namn, folkmÀngd, landlÄst):
        self.namn = namn
        self.folkmÀngd = folkmÀngd
        self.landlÄst = landlÄst

    #def __repr__(self):
        #return f" Namn: {self.namn}"


lista_lÀnder = []
with open("europa.txt") as infil:
    infil.readline()
    for line in infil:
        lista = []
        for word in line.split(","):
            if word:
                lista.append(word.strip())

        land = Land(namn=lista[0], folkmÀngd=lista[2], landlÄst=lista[3])
        lista_lÀnder.append(land)

for land in lista_lÀnder:
    print(land.namn)```
limber plover
limber plover
#

Oh

#

Yea I could do that

#

I’m kinda stuck on something else rn

#

When I append the ”land” objects to the list

#

It creates a whole list of objects

#

Should I append the land objects one at a time to a list in a loop then append that to a new list?

#

So I get each object as a list in a big list

limber plover
#

@narrow cloud hey

#

Have i been forgotten 😭

narrow cloud
#
class Country():
  _country_list = []
  
  def __init__(self, name: str, area: int, num_residents: int, landbound: bool)
    self.name = name
    self.area = area
    self.num_residents = num_residents
    self.landbound = landbound
    Country._country_list.append(self)

  @classmethod
  def get_all(cls):
    return cls._country_list


def readout_doc(doc_path, has_title_line: bool = True, seperator: str = ","):
  with open(doc_path, "r") as doc:
    for line in doc:
      if has_title_line:
        has_title_line = False
        continue
      name, area, num, bound = (line.strip()).split(seperator)
      Country(name, area, num, bound)


def start():
  readout_doc("my_textfile.txt")
  country_list = Country.get_all()
  for co in country_list:
    print(co)


if __name__ == "__main__":
  start()

This is basically what your goal should be (if i understood you correct)
(NOT TESTED! Just wrote that on top of my head, so minor errors you need to solve yourself :D)

hybrid pine
# limber plover Have i been forgotten 😭

No u haven't.. I am sorry for not replying earlier....

There's no need to create a list of lists. You're already on the right track with appending each 'Land' object to a single list as you loop through the file. When you append each 'Land' object to 'lista_lĂ€nder' one at a time, you’re building a list where each element is a 'Land' object, which is exactly what you want. This way, you can easily access each object later by iterating over 'lista_lĂ€nder' directly. If you created a list of lists, it would make accessing and managing the objects more complicated. So, just keep appending the 'Land' objects directly to the list within your loop, and you should be good to go

limber plover
#

The code ended up being shitty as hell

#

But it works

#

Just got done

#

            lista = [] # 
class Land():
    def __init__(self, namn, folkmÀngd, landlÄst):
        self.namn = namn
        self.folkmÀngd = folkmÀngd
        self.landlÄst = landlÄst

    def __str__(self):
        return f" {self.namn}, {self.folkmÀngd}"

    def __repr__(self):
        return f" {self.namn}, {self.folkmÀngd}"
 

def fil_till_lista(fil):
    lista_lÀnder = []
    with open(fil, "r", encoding = "utf-8") as fil:
        fil.readline() # ta bort rad 1
        for line in fil: # line gÄr över alla rader 1 och 1
skapar 1 tom lista
            for word in line.split(","): # för ord i rad som gjorts till lista
                word = word.strip()
                if word: # om ordet inte Àr tomt
                    lista.append(word) # lÀgg till ordet i lista
            lista_lÀnder.append(lista)
    return lista_lÀnder
        

def landlÄsta_lÀnder(fil):
    ny_lista = []
    for lista in fil:
        namn = lista[0]
        folkmÀngd = int(lista[2])
        landlÄst = lista[3]
        land = Land(namn, folkmÀngd, landlÄst)
        if landlÄst == "Y":
            ny_lista.append(land)

    return ny_lista


def rÀkna_ut_invÄnare(lista):
    total = 0
    for i in lista:
        total += i.folkmÀngd
    return total


def main():
    fil = input("VĂ€lj en fil:")
    call = fil_till_lista(fil)
    call2 = landlÄsta_lÀnder(call)
    print("I Europa har följande lÀnder inte tillgÄng till hav:")
    for i in call2:
        print(i.namn)
    invÄnare = rÀkna_ut_invÄnare(call2)
    print(f"Totalt bor i dessa 14 lÀnder: {invÄnare} mÀnniskor")

main() 
final jay
#

Swedish variable names give me anxiety but if it works it works đŸ—Łïž

limber plover
#

its not swedish

#

looks up in a lying manner

#

backflips out of the channel

final jay
#

defo scandinavian and doesn't look Danish or Norwegian kek

#

I didn't know you could use funny characters in Python variable names, learned something new today damn

#

Thought that was a Swift thing

limber plover
#

I’ve been programming for a week

#

and yes it is swedish

#

Allow it man

#

😭

final jay
limber plover
#

Ok can you help with my code

#

😭

final jay
#

What do you need help with exactly?

limber plover
#

The code looks horrible

#

Sure it gets the job done

#

But do you see any ways of making it shorter

#

Any thing you’d change (without it being everything)

final jay
#

will check in a bit but I'd probably add type hints

hybrid pine
# limber plover But do you see any ways of making it shorter
    def __init__(self, namn, folkmÀngd, landlÄst):
        self.namn = namn
        self.folkmÀngd = folkmÀngd
        self.landlÄst = landlÄst

    def __str__(self):
        return f"{self.namn}, {self.folkmÀngd}"

def fil_till_lista(fil):
    with open(fil, "r", encoding="utf-8") as f:
        f.readline()  # Remove header
        return [line.strip().split(",") for line in f if line.strip()]

def landlÄsta_lÀnder(data):
    return [Land(namn, int(folkmÀngd), landlÄst) for namn, _, folkmÀngd, landlÄst in data if landlÄst == "Y"]

def rÀkna_ut_invÄnare(lÀnder):
    return sum(land.folkmÀngd for land in lÀnder)

def main():
    fil = input("VĂ€lj en fil: ")
    data = fil_till_lista(fil)
    landlÄsta = landlÄsta_lÀnder(data)
    
    print("I Europa har följande lÀnder inte tillgÄng till hav:")
    for land in landlÄsta:
        print(land.namn)
        
    print(f"Totalt bor i dessa {len(landlÄsta)} lÀnder: {rÀkna_ut_invÄnare(landlÄsta)} mÀnniskor")

main() ```

I hope it helps
limber plover
final jay
#

type hints are good

limber plover
#

The return in the first function, does the [ ] create a list of is it used in all list comprehensions?

#

@hybrid pine

hybrid pine
limber plover
#

You cant say yes to a either or question @hybrid pine

#

😭

limber plover
narrow cloud
#

could it be that you totaly oversaw my script? xD
Basically that should include all you need to do.
Just need to rewrite it in your style & test
"read a text file into a program and make objects of each country"
as simple as possible pretty simple solved (except that i added the list as class attribute, so you dont have to work with globalizing vars in your script.

dense yarrow
#
class Land:
    def __init__(self, name, folkmangd, landlast):
        self.name = name
        self.folkmangd = folkmangd
        self.landlast = landlast
    def __repr__(self):
        return f"Land: {self.name}, {self.folkmangd}, {self.landlast}"

lista_lander = [Land(*[x.strip() for x in line.split(',')]) for line in open('europa.txt')]

print(*lista_lander, sep='\n')
narrow cloud
#

also its just taking 3 attributes, but each line has 4 elements xD

sullen kelp
#

How about we stop trying to just give answers and instead try teach them how to get to the answer themselves :))

narrow cloud
#

Then we should teach programming, not python code now 😉

  1. What should be the final output?
  2. How should it be saved/build up before?
  3. What do you need for that?
  4. Where do you get the data from?
  5. How do you get the data?
  6. What do you need to look after, when reading in the data?

Just following this questions one by one will result in that script above xD

dense yarrow
limber plover
#

!close

#

@narrow cloud how do I close this channel?