975 / github-slideshow

A robot powered training repository :robot:
https://lab.github.com/githubtraining/introduction-to-github
MIT License
0 stars 0 forks source link

FOOO #2

Closed j0sh21 closed 1 month ago

j0sh21 commented 1 month ago

Sure, let's go through the code example row by row:

is_valid Function

def is_valid(board, row, col, num):
    # Check if num is in the row
    if num in board[row]:
        return False
    # Check if num is in the column
    if num in [board[i][col] for i in range(9)]:
        return False
    # Check if num is in the 3x3 subgrid
    start_row, start_col = 3 * (row // 3), 3 * (col // 3)
    for i in range(3):
        for j in range(3):
            if board[start_row + i][start_col + j] == num:
                return False
    return True

solve_sudoku Function

def solve_sudoku(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:  # Empty cell found
                for num in range(1, 10):  # Try numbers 1 to 9
                    if is_valid(board, row, col, num):
                        board[row][col] = num  # Make a choice
                        if solve_sudoku(board):  # Explore further
                            return True
                        board[row][col] = 0  # Backtrack
                return False  # No valid number found, trigger backtracking
    return True  # Solved

Example Sudoku Board and Solving

# Example Sudoku board (0 represents empty cells)
sudoku_board = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]

solve_sudoku(sudoku_board)

# Printing the solved Sudoku board
for row in sudoku_board:
    print(row)

This code uses backtracking to try every possible number in each empty cell, backtracking whenever a number leads to an invalid state, until the entire board is correctly filled.

Does this step-by-step explanation help you understand how the code works?

j0sh21 commented 1 month ago

Sure! Think of the backtracking algorithm as a smart way to solve problems where you have to make a series of choices, and some choices might lead to dead ends. It's like exploring a maze: you try a path, and if you hit a wall, you go back and try a different path.

Here's a simple step-by-step explanation:

  1. Choose: Make a choice to move forward.
  2. Explore: Go forward and see if that choice leads to a solution.
  3. Backtrack: If it doesn't lead to a solution, undo the choice and try a different one.

Let's say we're solving a simple puzzle like a Sudoku. We fill in a number in an empty cell (choice), check if it fits with the rest of the puzzle (explore), and if it doesn't fit, we remove the number and try another one (backtrack).

Here's a basic Python example solving a simple problem: finding all possible ways to arrange numbers 1, 2, 3 in a sequence.

def backtrack(path, options):
    if not options:  # No more options to choose from
        print(path)  # We've found a valid sequence
        return
    for i in range(len(options)):
        # Make a choice
        next_option = options[i]
        new_path = path + [next_option]
        remaining_options = options[:i] + options[i+1:]
        # Explore further with this choice
        backtrack(new_path, remaining_options)
        # No need to explicitly backtrack as we are using new lists

# Start with an empty path and all options available
backtrack([], [1, 2, 3])

In this example, the function backtrack tries every possible arrangement of the numbers one, two, and three by making a choice, exploring further, and automatically backtracking by using new lists.

Does that make sense?

j0sh21 commented 1 month ago

import requests from bs4 import BeautifulSoup from sqlalchemy import create_engine, Column, String, Integer, Float, Base from sqlalchemy.orm import sessionmaker

Define the SQLAlchemy ORM model

Base = declarative_base()

class OfficeListing(Base): tablename = 'office_listings' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String) price = Column(Float) address = Column(String) size = Column(String) url = Column(String)

Set up the database

engine = create_engine('sqlite:///office_listings.db') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session()

def scrape_immobilienscout24(): url = 'https://www.immobilienscout24.de/gewerbe-flaechen/de/nordrhein-westfalen/neuss-rhein-kreis/neuss/bu

j0sh21 commented 1 month ago

Natürlich, hier ist ein vollständiger Prototyp einer Flask-App, die Echtzeit-Flugdaten für den Düsseldorf Airport und den Flughafen Mönchengladbach anzeigt.

Stelle sicher, dass du die notwendigen Python-Bibliotheken installiert hast:

pip install flask requests

Speichere den folgenden Code in einer Datei namens app.py:

from flask import Flask, render_template_string
import requests

app = Flask(__name__)

# Replace with your actual FlightAware API credentials
FLIGHTAWARE_API_KEY = 'your_api_key_here'
BASE_URL = 'http://aviation-edge.com/v2/public/flights?key={api_key}&airportIata={airport_code}'

def get_flight_data(airport_code):
    url = BASE_URL.format(api_key=FLIGHTAWARE_API_KEY, airport_code=airport_code)
    response = requests.get(url)
    return response.json()

@app.route('/')
def index():
    dus_data = get_flight_data('DUS')  # Düsseldorf Airport IATA code
    mgb_data = get_flight_data('MGL')  # Mönchengladbach Airport IATA code

    template = '''
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Flight Tracker</title>
      </head>
      <body>
        <h1>Flight Tracker</h1>
        <h2>Düsseldorf Airport (DUS)</h2>
        <ul>
        {% for flight in dus_data %}
          <li>{{ flight['flight']['iataNumber'] }} - {{ flight['status'] }}</li>
        {% endfor %}
        </ul>

        <h2>Mönchengladbach Airport (MGL)</h2>
        <ul>
        {% for flight in mgb_data %}
          <li>{{ flight['flight']['iataNumber'] }} - {{ flight['status'] }}</li>
        {% endfor %}
        </ul>
      </body>
    </html>
    '''

    return render_template_string(template, dus_data=dus_data, mgb_data=mgb_data)

if __name__ == '__main__':
    app.run(debug=True)

Erläuterung des Codes:

  1. API-Zugriff: Der Code nutzt die API von FlightAware (oder eine ähnliche API), um Flugdaten für die Flughäfen Düsseldorf (DUS) und Mönchengladbach (MGL) abzurufen.
  2. Flask-Anwendung: Flask wird verwendet, um eine einfache Webanwendung zu erstellen, die die abgerufenen Daten anzeigt.
  3. HTML-Template: Das HTML-Template wird in der index-Funktion definiert und zeigt eine Liste von Flügen für beide Flughäfen.

Ausführen der Anwendung:

  1. API-Schlüssel einfügen: Ersetze 'your_api_key_here' mit deinem tatsächlichen API-Schlüssel.
  2. Starten der Anwendung: Führe die Flask-App mit folgendem Befehl aus:
    python app.py
  3. Anzeigen im Browser: Öffne einen Webbrowser und navigiere zu http://127.0.0.1:5000/, um die Echtzeit-Flugdaten zu sehen.

Du kannst dieses Grundgerüst weiter ausbauen, um zusätzliche Funktionen hinzuzufügen oder das Layout zu verbessern. Viel Erfolg bei deinem Projekt!

j0sh21 commented 1 month ago

import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import json

Dein JSON-Template

email_template = '''{ "to": "umweltamt@stadt.neuss.de", "subject": "Anfrage zur aktuellen Süßwasserqualität des Sees in Neuss", "body": "Sehr geehrte Damen und Herren,\n\nich hoffe, Sie können mir weiterhelfen. Ich möchte mich nach der aktuellen Süßwasserqualität des Sees in Neuss erkundigen. Könnten Sie mir bitte Informationen über die neuesten Wasseranalysen und die allgemeine Wasserqualität des Sees zur Verfügung stellen?\n\nVielen Dank im Voraus für Ihre Unterstützung." }'''

Lade das JSON-Template

email_data = json.loads(email_template)

E-Mail-Parameter

from_address = "deine.email@domain.de" to_address = email_data['to'] subject = email_data['subject'] body = email_data['body']

SMTP-Server-Details

smtp_server = "smtp.your-email-provider.com" smtp_port = 587 smtp_username = "deine.email@domain.de" smtp_password = "deinpasswort"

E-Mail-Nachricht erstellen

msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = subject msg.attach(MIMEText(body, 'plain'))

E-Mail senden

try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(smtp_username, smtp_password) server.send_message(msg) server.quit() print("E-Mail erfolgreich gesendet!") except Exception as e: print(f"Fehler beim Senden der E-Mail: {e}")

j0sh21 commented 1 month ago

done