In [ ]:
#airplain_ticket.py

seats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
n = 0

while n < 10:
    my_seat = 0

    print("Choose the arrangement you want:")
    print("Enter 1 for First Class")
    print("Enter 2 for Economy Class")
    my_num = int(input())

    if my_num == 1:
        print("You chose First Class")
        if 0 in seats[:5]:
            for i in range(5):
                if seats[i] == 0:
                    my_seat = i + 1
                    seats[i] = 1
                    print("Your seat number is", my_seat)
                    break
        else:
            print("First Class seats are full.")
            print("Would you like to try Economy Class? (Y/N)")
            choice = input()
            if choice.upper() == "Y":
                for i in range(5, 10):
                    if seats[i] == 0:
                        my_seat = i + 1
                        seats[i] = 1
                        print("Your seat number is", my_seat)
                        break
            else:
                print("Next flight leaves in 3 hours.")

    elif my_num == 2:
        print("You chose Economy Class")
        if 0 in seats[5:10]:
            for i in range(5, 10):
                if seats[i] == 0:
                    my_seat = i + 1
                    seats[i] = 1
                    print("Your seat number is", my_seat)
                    break
        else:
            print("Economy Class seats are full.")
            print("Would you like to try First Class? (Y/N)")
            choice = input()
            if choice.upper() == "Y":
                for i in range(5):
                    if seats[i] == 0:
                        my_seat = i + 1
                        seats[i] = 1
                        print("Your seat number is", my_seat)
                        break
            else:
                print("Next flight leaves in 3 hours.")

    n += 1
In [ ]:
#calculate_monthly_average_rainfall.py

def calculate_monthly_average_rainfall(list_of_annual_values):
    total_rainfall = sum(list_of_annual_values)
	
    average = total_rainfall / 12

    return average

rainfall_values =   [10, 12, 8, 15, 10, 6, 9, 11, 13, 14, 9, 7]
monthly_average = calculate_monthly_average_rainfall(rainfall_values)
print('Average monthly rainfall: ', "{:.2f}".format(monthly_average))
In [ ]:
#char_read_ansihexoct.py

def extract_ansi(data):
    return data.decode('ascii', 'replace')

def convert_to_octal_decimal(data):
    return " ".join(f"{byte:03o}" for byte in data)

def convert_to_hexadecimal(data):
    return " ".join(f"{byte:02X}" for byte in data)

try:
    with open("data.bin", "rb") as file:
        binary_data = file.read()
        binary_data_lines = binary_data.splitlines()
except FileNotFoundError:
    print("\033[91mCould not open data.bin. Please create the file with some content.\033[0m")
else:
    print("\033[1m\033[95m" + r"""
 _______  _______  _______  _______           _______ 
(  __   )(  __   )(  __   )(  __   )|\     /|(  __   )
| (  )  || (  )  || (  )  || (  )  |( \   / )| (  )  |
| | /   || | /   || | /   || | /   | \ (_) / | | /   |
| (/ /) || (/ /) || (/ /) || (/ /) |  \   /  | (/ /) |
|   / | ||   / | ||   / | ||   / | |   ) (   |   / | |
|  (__) ||  (__) ||  (__) ||  (__) |   | |   |  (__) |
(_______)(_______)(_______)(_______)   \_/   (_______)
                                                     
    """ + "\033[0m")

    while True:
        print("\033[1m" + "Choose what to do with the data in 'data.bin':\033[0m")
        print("\033[94m1. Extract to ANSI format\033[0m")
        print("\033[93m2. Convert to hexadecimal format\033[0m")
        print("\033[92m3. Convert to octal decimal format\033[0m")
        print("\033[91mq. Quit\033[0m")

        user_choice = input("\033[95mEnter the number of your choice (or 'q' to quit):\033[0m ")

        if user_choice.lower() == "q":
            print("Exiting...")
            break
        elif user_choice == "1":
            print("\033[94mANSI Format:\033[0m")
            print(extract_ansi(binary_data))
        elif user_choice == "2":
            print("\033[93mHexadecimal Format:\033[0m")
            print(convert_to_hexadecimal(binary_data))
        elif user_choice == "3":
            print("\033[92mOctal Decimal Format:\033[0m")
            print(convert_to_octal_decimal(binary_data))
            print("\n\033[95mPress Enter to continue (or 'q' to go back to the main menu):\033[0m ", end="")
            user_input = input()
            if user_input.lower() == "q":
                print("Returning to the main menu...")
        else:
            print("\033[91mInvalid choice. Please enter a valid number.\033[0m")

    print("\033[1m\033[95mThank you for using the script! Goodbye!\033[0m")
In [ ]:
#colorful_firework_counteroffensive.py

import time
import random
def generate_fireworks_pattern():
    patterns = [
        (r"""
 *         .   *  .  *
    .  * .    .    .
 * .  .    .  *.   *
    .     .*           *
.  *    .    .  *    *.
  *      .*  .  *
""", "\033[91m"),  # Red
        (r"""
    \ /     *    .     .   /     *   \ /
. -- .  *  .   .*   .   \./ .    . -- .
    / \     .  .    .   / \         /
   /  *\  .      *    /.       *    * .
""", "\033[93m"),  # Yellow
        (r"""
    *    .     .    .    .
  .   .    .  *  .
    .     .  .    .     .
  .    *     .  .  *
       .    .   *    .    *
    *    .     . .  *  .
.     .    *   .    .
""", "\033[92m"),  # Green
        (r"""
       .      .      .  . .
   .     .      .   .    .
     .     .  .    .    .    .
      .    .     .    .
   .    .   .      .   .    .  .
.    .     .     .   .    .     .
   .    .     .     .    .
     .  .   .    .    .  .
       .    .   .   .
""", "\033[96m"),  # Cyan
        (r"""
 *         .   *  .  *
    .  * .    .    .
 * .  .    .  *.   *
    .     .*           *
.  *    .    .  *    *.
  *      .*  .  *
""", "\033[95m"),  # Red
        (r"""
    \ /     *    .     .   /     *   \ /
. -- .  *  .   .*   .   \./ .    . -- .
    / \     .  .    .   / \         /
   /  *\  .      *    /.       *    * .
""", "\033[97m"),  # Yellow
        (r"""
    *    .     .    .    .
  .   .    .  *  .
    .     .  .    .     .
  .    *     .  .  *
       .    .   *    .    *
    *    .     . .  *  .
.     .    *   .    .
""", "\033[94m"),  # Green
        (r"""
       .      .      .  . .
   .     .      .   .    .
     .     .  .    .    .    .
      .    .     .    .
   .    .   .      .   .    .  .
.    .     .     .   .    .     .
   .    .     .     .    .
     .  .   .    .    .  .
       .    .   .   .
""", "\033[90m"),  # Cyan
    ]
    return random.choice(patterns)
def display_fireworks():
    fireworks, color_code = generate_fireworks_pattern()
    print(color_code + fireworks + "\033[0m")
    time.sleep(1)

def generate_random_packet_details():
    source_ips = ["192.168.0.100", "10.0.0.2", "172.16.0.5", "10.20.30.40"]
    destination_ips = ["10.0.0.1", "172.16.0.10", "192.168.0.200", "8.8.8.8"]
    protocols = ["TCP", "UDP", "ICMP"]
    lengths = [random.randint(500, 2000), random.randint(300, 1000), random.randint(100, 500)]
    information = ["Normal traffic", "DDoS attack packets", "Suspicious activity"]
    tls_information = ["Not applicable", "TLS v1.2", "TLS v1.3"]
    return {
        "Source": random.choice(source_ips),
        "Destination": random.choice(destination_ips),
        "Protocol": random.choice(protocols),
        "Length": f"{random.choice(lengths)} bytes",
        "Information": random.choice(information),
        "TLS Information": random.choice(tls_information)
    }
def show_packet_details():
    packet_details = generate_random_packet_details()
    display_fireworks()
    print("\n\033[1mPacket Details:\033[0m")
    for key, value in packet_details.items():
        print(f"\033[94m{key}:\033[0m {value}")
while True:
    print("\033[1m----- DDoS Counter-Offensive Menu -----\033[0m")
    print("\033[94m1. Rate Limiting\033[0m")
    print("\033[93m2. Web Application Firewall (WAF)\033[0m")
    print("\033[92m3. Anomaly Detection\033[0m")
    print("\033[91m4. Cloud-Based DDoS Protection\033[0m")
    print("\033[95m5. Blackhole Routing\033[0m")
    print("\033[96m6. FTP Bounce Attack (Counter Measure)\033[0m")
    print("\033[97m7. Smurf Attack (Counter Measure)\033[0m")
    print("\033[91m8. TCP SYN Flood (Counter Measure)\033[0m")
    print("\033[92m9. DNS Amplification (Counter Measure)\033[0m")
    print("\033[93m10. TLS Mitigation\033[0m")
    print("\033[96mq. Quit\033[0m")
    print("\033[1m---------------------------------------\033[0m")
    user_choice = input("Enter the number of your choice (or 'q' to quit): ")
    if user_choice.lower() == "q":
        print("Exiting...")
        break
    elif user_choice == "1":
        print("\033[94mRate Limiting:\033[0m Rate limiting restricts the number of requests from a single IP address.")
        print("By setting a threshold, you can block or delay excessive requests from suspicious sources.")
        show_packet_details()
    elif user_choice == "2":
        print("\033[93mWeb Application Firewall (WAF):\033[0m A WAF can analyze incoming HTTP requests and filter out potentially malicious ones.")
        print("It helps protect the web server from common attack patterns and vulnerabilities.")
        show_packet_details()
    elif user_choice == "3":
        print("\033[92mAnomaly Detection:\033[0m Anomaly detection mechanisms can identify unusual traffic patterns.")
        print("It helps to detect DDoS attacks by monitoring traffic behavior and identifying deviations from normal traffic.")
        show_packet_details()
    elif user_choice == "4":
        print("\033[91mCloud-Based DDoS Protection:\033[0m Leveraging cloud-based DDoS protection services can offload attack traffic away from the target server.")
        print("Cloud providers have robust infrastructure to absorb and mitigate large-scale DDoS attacks.")
        show_packet_details()
    elif user_choice == "5":
        print("\033[95mBlackhole Routing:\033[0m In severe DDoS attacks, blackhole routing can be used to drop traffic to the target IP address.")
        print("This approach takes the target offline temporarily, preventing collateral damage to the rest of the network.")
        show_packet_details()
    elif user_choice == "6":
        print("\033[96mFTP Bounce Attack (Counter Measure):\033[0m Countermeasures for FTP bounce attack.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "7":
        print("\033[97mSmurf Attack (Counter Measure):\033[0m Countermeasures for Smurf attack.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "8":
        print("\033[91mTCP SYN Flood (Counter Measure):\033[0m Countermeasures for TCP SYN flood.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "9":
        print("\033[92mDNS Amplification (Counter Measure):\033[0m Countermeasures for DNS amplification.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "10":
        print("\033[93mTLS Mitigation:\033[0m Mitigating DDoS attacks targeting TLS.")
        print("Description of TLS mitigation here.")
        show_packet_details()
    else:
        print("\033[91mInvalid choice. Please enter a valid number.\033[0m")

   # display_fireworks()
    
if __name__ == "__main__":
    main()
In [ ]:
#counter_offensive.py

import time
import sys
import json
import random

def generate_fireworks_pattern():
    patterns = [
        r"""
          .     .
    .   .    .    .
  .  .    .  .
    .     .
.      .    .      .
        .
""",
        r"""
    \ /          .     .           \ /
. -- .     .   .    .   -- .    . -- .
    / \     .  .    .   / \
         .          .              .
""",
        r"""
    *
         .     .    .    .
  .   .    .  *  .
    .     .  .    .     .
  .    *     .  .  *
       .    .   *    .    *
    *    .     . .  *  .
.     .    *   .    .
""",
        r"""
       .      .      .  . .
   .     .      .   .    .
     .     .  .    .    .    .
      .    .     .    .
   .    .   .      .   .    .  .
.    .     .     .   .    .     .
   .    .     .     .    .
     .  .   .    .    .  .
       .    .   .   .
""",
    ]

    return random.choice(patterns)

def display_fireworks():
    fireworks = generate_fireworks_pattern()
    print("\033[93m" + fireworks + "\033[0m")
    time.sleep(1)

# ... Rest of the code remains unchanged ...


def generate_random_packet_details():
    source_ips = ["192.168.0.100", "10.0.0.2", "172.16.0.5", "10.20.30.40"]
    destination_ips = ["10.0.0.1", "172.16.0.10", "192.168.0.200", "8.8.8.8"]
    protocols = ["TCP", "UDP", "ICMP"]
    lengths = [random.randint(500, 2000), random.randint(300, 1000), random.randint(100, 500)]
    information = ["Normal traffic", "DDoS attack packets", "Suspicious activity"]
    tls_information = ["Not applicable", "TLS v1.2", "TLS v1.3"]

    return {
        "Source": random.choice(source_ips),
        "Destination": random.choice(destination_ips),
        "Protocol": random.choice(protocols),
        "Length": f"{random.choice(lengths)} bytes",
        "Information": random.choice(information),
        "TLS Information": random.choice(tls_information)
    }

def show_packet_details():
    packet_details = generate_random_packet_details()

    print("\n\033[1mPacket Details:\033[0m")
    for key, value in packet_details.items():
        print(f"\033[94m{key}:\033[0m {value}")

def main():
    with open("read.json") as file:
        countermeasures = json.load(file)

    print("===== DDoS Counter-Offensive Menu =====")
    for option in countermeasures:
        print(f"\033[94m{option}. \033[0m{countermeasures[option]['name']}")
    print("\033[91mq. Quit\033[0m")
    print("=======================================")

    while True:
        user_choice = input("\nEnter the number of your choice (or 'q' to quit): ")

        if user_choice.lower() == "q":
            print("Exiting...")
            break

        if user_choice in countermeasures:
            print(f"\n\033[1m{countermeasures[user_choice]['name']}:\033[0m {countermeasures[user_choice]['description']}")
            display_fireworks()
            choice = input("\nDo you want to see packet details? (yes/no): ").lower()
            if choice == 'yes':
                show_packet_details()
        else:
            print("\033[91mInvalid choice. Please enter a valid number.\033[0m")

if __name__ == "__main__":
    main()
In [ ]:
#counter_offensive(random_fireworks_colors).py

import time
import random

def generate_fireworks_pattern():
    patterns = [
        (r"""
 *         .   *  .  *
    .  * .    .    .
 * .  .    .  *.   *
    .     .*           *
.  *    .    .  *    *.
  *      .*  .  *
""", "\033[91m"),  # Red
        (r"""
    \ /     *    .     .   /     *   \ /
. -- .  *  .   .*   .   \./ .    . -- .
    / \     .  .    .   / \         /
   /  *\  .      *    /.       *    * .
""", "\033[93m"),  # Yellow
        (r"""
    *    .     .    .    .
  .   .    .  *  .
    .     .  .    .     .
  .    *     .  .  *
       .    .   *    .    *
    *    .     . .  *  .
.     .    *   .    .
""", "\033[92m"),  # Green
        (r"""
       .      .      .  . .
   .     .      .   .    .
     .     .  .    .    .    .
      .    .     .    .
   .    .   .      .   .    .  .
.    .     .     .   .    .     .
   .    .     .     .    .
     .  .   .    .    .  .
       .    .   .   .
""", "\033[96m"),  # Cyan
        (r"""
 *         .   *  .  *
    .  * .    .    .
 * .  .    .  *.   *
    .     .*           *
.  *    .    .  *    *.
  *      .*  .  *
""", "\033[95m"),  # Red
        (r"""
    \ /     *    .     .   /     *   \ /
. -- .  *  .   .*   .   \./ .    . -- .
    / \     .  .    .   / \         /
   /  *\  .      *    /.       *    * .
""", "\033[97m"),  # Yellow
        (r"""
    *    .     .    .    .
  .   .    .  *  .
    .     .  .    .     .
  .    *     .  .  *
       .    .   *    .    *
    *    .     . .  *  .
.     .    *   .    .
""", "\033[94m"),  # Green
        (r"""
       .      .      .  . .
   .     .      .   .    .
     .     .  .    .    .    .
      .    .     .    .
   .    .   .      .   .    .  .
.    .     .     .   .    .     .
   .    .     .     .    .
     .  .   .    .    .  .
       .    .   .   .
""", "\033[90m"),  # Cyan
    ]

    return random.choice(patterns)

def display_fireworks():
    fireworks, color_code = generate_fireworks_pattern()
    print(color_code + fireworks + "\033[0m")
    time.sleep(1)


def generate_random_packet_details():
    source_ips = ["192.168.0.100", "10.0.0.2", "172.16.0.5", "10.20.30.40"]
    destination_ips = ["10.0.0.1", "172.16.0.10", "192.168.0.200", "8.8.8.8"]
    protocols = ["TCP", "UDP", "ICMP"]
    lengths = [random.randint(500, 2000), random.randint(300, 1000), random.randint(100, 500)]
    information = ["Normal traffic", "DDoS attack packets", "Suspicious activity"]
    tls_information = ["Not applicable", "TLS v1.2", "TLS v1.3"]

    return {
        "Source": random.choice(source_ips),
        "Destination": random.choice(destination_ips),
        "Protocol": random.choice(protocols),
        "Length": f"{random.choice(lengths)} bytes",
        "Information": random.choice(information),
        "TLS Information": random.choice(tls_information)
    }
def show_packet_details():
    packet_details = generate_random_packet_details()
    display_fireworks()
    print("\n\033[1mPacket Details:\033[0m")
    for key, value in packet_details.items():
        print(f"\033[94m{key}:\033[0m {value}")

while True:
    print("\033[1m----- DDoS Counter-Offensive Menu -----\033[0m")
    print("\033[94m1. Rate Limiting\033[0m")
    print("\033[93m2. Web Application Firewall (WAF)\033[0m")
    print("\033[92m3. Anomaly Detection\033[0m")
    print("\033[91m4. Cloud-Based DDoS Protection\033[0m")
    print("\033[95m5. Blackhole Routing\033[0m")
    print("\033[96m6. FTP Bounce Attack (Counter Measure)\033[0m")
    print("\033[97m7. Smurf Attack (Counter Measure)\033[0m")
    print("\033[91m8. TCP SYN Flood (Counter Measure)\033[0m")
    print("\033[92m9. DNS Amplification (Counter Measure)\033[0m")
    print("\033[93m10. TLS Mitigation\033[0m")
    print("\033[96mq. Quit\033[0m")
    print("\033[1m---------------------------------------\033[0m")

    user_choice = input("Enter the number of your choice (or 'q' to quit): ")
    if user_choice.lower() == "q":
        print("Exiting...")
        break
    elif user_choice == "1":
        print("\033[94mRate Limiting:\033[0m Rate limiting restricts the number of requests from a single IP address.")
        print("By setting a threshold, you can block or delay excessive requests from suspicious sources.")
        show_packet_details()
    elif user_choice == "2":
        print("\033[93mWeb Application Firewall (WAF):\033[0m A WAF can analyze incoming HTTP requests and filter out potentially malicious ones.")
        print("It helps protect the web server from common attack patterns and vulnerabilities.")
        show_packet_details()
    elif user_choice == "3":
        print("\033[92mAnomaly Detection:\033[0m Anomaly detection mechanisms can identify unusual traffic patterns.")
        print("It helps to detect DDoS attacks by monitoring traffic behavior and identifying deviations from normal traffic.")
        show_packet_details()
    elif user_choice == "4":
        print("\033[91mCloud-Based DDoS Protection:\033[0m Leveraging cloud-based DDoS protection services can offload attack traffic away from the target server.")
        print("Cloud providers have robust infrastructure to absorb and mitigate large-scale DDoS attacks.")
        show_packet_details()
    elif user_choice == "5":
        print("\033[95mBlackhole Routing:\033[0m In severe DDoS attacks, blackhole routing can be used to drop traffic to the target IP address.")
        print("This approach takes the target offline temporarily, preventing collateral damage to the rest of the network.")
        show_packet_details()
    elif user_choice == "6":
        print("\033[96mFTP Bounce Attack (Counter Measure):\033[0m Countermeasures for FTP bounce attack.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "7":
        print("\033[97mSmurf Attack (Counter Measure):\033[0m Countermeasures for Smurf attack.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "8":
        print("\033[91mTCP SYN Flood (Counter Measure):\033[0m Countermeasures for TCP SYN flood.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "9":
        print("\033[92mDNS Amplification (Counter Measure):\033[0m Countermeasures for DNS amplification.")
        print("Description of countermeasure here.")
        show_packet_details()
    elif user_choice == "10":
        print("\033[93mTLS Mitigation:\033[0m Mitigating DDoS attacks targeting TLS.")
        print("Description of TLS mitigation here.")
        show_packet_details()
    else:
        print("\033[91mInvalid choice. Please enter a valid number.\033[0m")


   # display_fireworks()
    
if __name__ == "__main__":
    main()
In [ ]:
#element_console.py

def read_elements_data(file_name):
    with open(file_name, 'r') as file:
        lines = file.readlines()

    elements = []
    headers = lines[0].strip().split('\t')
    for line in lines[1:]:
        data = line.strip().split('\t')
        element = dict(zip(headers, data))
        elements.append(element)

    return elements


def print_elements_table(elements, column_widths):
    headers = elements[0].keys()

    # Print headers
    header_line = '|'.join(format(header, f' ^{width}') for header, width in zip(headers, column_widths))
    separator_line = '-' * (sum(column_widths) + len(column_widths) * 3 - 1)
    print(header_line)
    print(separator_line)

    # Print rows
    for element in elements:
        row = [format(element.get(header, ''), f' <{width}') for header, width in zip(headers, column_widths)]
        print('|'.join(row))


def view_elements_by_periodic_number(elements):
    while True:
        print("\n----- View Elements by Periodic Number -----")
        element_number = input("Enter the atomic number of the element (1-118), or 'q' to exit: ")

        if element_number == 'q':
            break

        found_element = False
        for element in elements:
            if element['Number'] == element_number:
                column_widths = [max(len(header), len(element[header])) for header in element.keys()]
                print_elements_table([element], column_widths)
                found_element = True
                break

        if not found_element:
            print("Element not found. Please try again.")


def view_elements_by_group(elements):
    while True:
        print("\n----- View Elements by Group -----")
        print("1. Group 1")
        print("2. Group 2")
        print("3. Group 3")
        print("4. Group 4")
        print("5. Group 5")
        print("6. Group 6")
        print("7. Group 7")
        print("8. Back to previous menu")

        group_choice = input("Enter your choice (1-8): ")

        if group_choice == '8':
            break

        group_elements = [element for element in elements if element['Group'] == group_choice]

        if len(group_elements) > 0:
            column_widths = [max(len(header), len(element[header])) for header in group_elements[0].keys()]
            print_elements_table(group_elements, column_widths)
        else:
            print("No elements found in the selected group.")


def display_noble_gases(elements):
    noble_gases = [element for element in elements if element['Group'] == '18']
    column_widths = [max(len(header), len(element[header])) for header in noble_gases[0].keys()]
    print_elements_table(noble_gases, column_widths)


def display_rare_metals(elements):
    rare_metals = [element for element in elements if element['Group'] in ['3', '4', '5', '6', '7', '8', '9', '10', '11', '12']]
    column_widths = [max(len(header), len(element[header])) for header in rare_metals[0].keys()]
    print_elements_table(rare_metals, column_widths)


def display_radioactive_decay(elements):
    radioactive_elements = [element for element in elements if element['Stable isotopes'] == '']
    column_widths = [max(len(header), len(element[header])) for header in radioactive_elements[0].keys()]
    print_elements_table(radioactive_elements, column_widths)


def read_element_groups(file_name):
    with open(file_name, 'r') as file:
        lines = file.readlines()

    element_groups = {}
    current_group = None

    for line in lines:
        line = line.strip()

        if line.startswith("Group"):
            group_number = line.split(':')[0].strip().replace("Group", "")
            current_group = []
            element_groups[group_number] = current_group
        elif line:
            element_data = line.split('\t')
   #         current_group.append(element_data)

    return element_groups


def view_elements_by_group_menu(element_groups):
    while True:
        print("\n----- View Elements by Group -----")
        for group_number, group_elements in element_groups.items():
            group_name = group_elements[0][4]
            print(f"{group_number}. {group_name}")

        print(f"{len(element_groups) + 1}. Back to previous menu")

        group_choice = input("Enter your choice (1-8): ")

        if group_choice == str(len(element_groups) + 1):
            break

        if group_choice in element_groups:
            elements = element_groups[group_choice]
            headers = elements[0]
            group_elements = [dict(zip(headers, data)) for data in elements]
            column_widths = [max(len(header), max(len(element[header]) for element in group_elements)) for header in headers]
            print_elements_table(group_elements, column_widths)
        else:
            print("Invalid choice. Please try again.")

# Main menu function
def main_menu():
    elements_file_name = 'elements_data.txt'
    groups_file_name = 'element_groups.txt'

    elements = read_elements_data(elements_file_name)
    element_groups = read_element_groups(groups_file_name)

    while True:
        print()
        print("{:-^45}".format(" Element's Program "))
        print("1. View elements by periodic number")
        print("2. View elements by group")
        print("3. Display noble gases")
        print("4. Display rare metals")
        print("5. Display radioactive decay")
        print("6. Display all elements")
        print("7. Exit")
        print("---------------------------------------------")
        choice = input("Enter your choice (1-7): ")

        if choice == '1':
            view_elements_by_periodic_number(elements)
        elif choice == '2':
            view_elements_by_group_menu(element_groups)
        elif choice == '3':
            display_noble_gases(elements)
        elif choice == '4':
            display_rare_metals(elements)
        elif choice == '5':
            display_radioactive_decay(elements)
        elif choice == '6':
            column_widths = [max(len(header), max(len(element.get(header, '')) for element in elements)) for header in elements[0].keys()]
            print_elements_table(elements, column_widths)
        elif choice == '7':
            print("Exiting the program...")
            break
        else:
            print("Invalid choice. Please try again.")


# Run the main menu
main_menu()
In [ ]:
#elements_data.txt

Number	Period	Group	Symbol	Name	Mass	Radius	Valence el.	Stable isotopes	Melting point	Boiling point	Density
1	1	1	H	Hydrogen	1.008	25	1	2	14.1	20.3	0.084*
2	1	18	He	Helium	4.003	31	2	2		4.2	0.17*
3	2	1	Li	Lithium	6.941	145	1	2	454	1615	0.53
4	2	2	Be	Beryllium	9.012	105	2	1	1551	3750	1.85
5	2	13	B	Boron	10.81	85	3	2	2349	4200	2.46
6	2	14	C	Carbon	12.011	70	4	2	3820	5100	3.51
7	2	15	N	Nitrogen	14.007	65	5	2	63.1	77.4	1.17*
8	2	16	O	Oxygen	15.999	60	6	3	54.4	90.2	1.33*
9	2	17	F	Fluorine	18.998	50	7	1	53.5	85	1.58*
10	2	18	Ne	Neon	20.18	38	8	3	24.6	27.1	0.84*
11	3	1	Na	Sodium	22.99	180	1	1	371	1156	0.97
12	3	2	Mg	Magnesium	24.305	150	2	3	923	1380	1.74
13	3	13	Al	Aluminium	26.92	125	3	1	933	2740	2.7
14	3	14	Si	Silicon	28.085	110	4	3	1683	2628	2.33
15	3	15	P	Phosphorus	30.974	100	5	1	317	550	1.82
16	3	16	S	Sulfur	62.065	100	6	4	338	718	2.06
17	3	17	Cl	Chlorine	35.453	100	7	2	172	239	2.95*
18	3	18	Ar	Argon	39.948	71	8	3	84	87	1.66*
19	4	1	K	Potassium	39.098	220	1	2	337	1032	0.86
20	4	2	Ca	Calcium	40.078	280	2	4	1115	1757	1.54
21	4	3	Sc	Scandium	44.956	160		1	1814	3103	2.99
22	4	4	Ti	Titanium	47.867	140		5	1941	3560	4.51
23	4	5	V	Vanadium	50.942	135		1	2183	3680	6.09
24	4	6	Cr	Chromium	51.996	140		3	2130	2945	7.14
25	4	7	Mn	Manganese	54.938	140		1	1517	2235	7.44
26	4	8	Fe	Iron	55.845	140		4-Mar	1808	3023	7.87
27	4	9	Co	Cobalt	58.993	135		1	1768	3200	8.89
28	4	10	Ni	Nickel	58.693	135		5	1738	3186	8.91
29	4	11	Cu	Copper	63.456	135		2	1358	2840	8.92
30	4	12	Zn	Zinc	65.39	135		5	693	1180	7.14
31	4	13	Ga	Gallium	69.723	130	3	2	303	2477	5.91
32	4	14	Ge	Germanium	72.64	125	4	4	1211	3093	5.32
33	4	15	As	Arsenic	74.922	115	5	1		889	5.72
34	4	16	Se	Selenium	78.96	115	6	5	494	958	4.82
35	4	17	Br	Bromine	79.904	115	7	2	266	332	3.14
36	4	18	Kr	Krypton	83.8	88	8	5	116	120	3.48*
37	5	1	Rb	Rubidium	85.468	235	1	1	312	961	1.53
38	5	2	Sr	Strontium	87.62	200	2	4	1050	1655	2.63
39	5	3	Y	Yttrium	88.906	180		1	1799	3609	4.47
40	5	4	Zr	Zirconium	91.224	155		4	2130	4682	6.51
41	5	5	Nb	Niob	92.906	145		1	2750	5017	8.58
42	5	6	Mo	Molybdenum	95.94	145		6	2896	4912	10.28
43	5	7	Tc	Technetium	98	135			2430	5150	11.49
44	5	8	Ru	Ruthenium	101.07	130		7	2607	4423	12.45
45	5	9	Rh	Rhodium	102.91	135		1	2273	3968	12.41
46	5	10	Pd	Palladium	106.42	140		6	1828	3236	12.02
47	5	11	Ag	Silver	107.87	160		2	1234	2435	10.49
48	5	12	Cd	Cadmium	112.41	155		≥3	594	1040	8.64
49	5	13	In	Indium	114.82	155	3	1	430	2345	7.31
50	5	14	Sn	Tin	118.71	145	4	10	505	2875	7.29
51	5	15	Sb	Antimony	121.76	145	5	2	904	1860	6.69
52	5	16	Te	Tellurium	127.6	140	6	5-Apr	723	1263	6.25
53	5	17	I	Iodine	126.9	140	7	1	387	457	4.94
54	5	18	Xe	Xenon	131.29	108	8	9	161	165	4.49*
55	6	1	Cs	Caesium	132.9	260	1	1	302	944	1.9
56	6	2	Ba	Barium	137.33	215	2	7	1000	1913	3.65
57	6	3	La	Lanthanum	138.91	195		1	1193	3730	6.16
58	6	3	Ce	Cerium	140.12	185		3	1068	3716	6.77
59	6	3	Pr	Praseodym	140.91	185		1	1204	3793	6.48
60	6	3	Nd	Neodym	144.24	185		5	1297	3373	7
61	6	3	Pm	Promethium	145	185			1315	3273	7.22
62	6	3	Sm	Samarium	150.36	185		4	1345	2076	7.54
63	6	3	Eu	Europium	151.96	185		2	1099	1800	6.16
64	6	3	Gd	Gadolinium	157.25	180		6	1585	3523	7.89
65	6	3	Tb	Terbium	158.92	175		1	1629	3503	8.25
66	6	3	Dy	Dysprosium	162.5	175		7	1680	2840	8.56
67	6	3	Ho	Holmium	163.93	175		1	1747	2963	8.78
68	6	3	Er	Erbium	167.26	175		6	1795	2783	9.05
69	6	3	Tm	Thulium	168.93	175		1	1818	2220	9.32
70	6	3	Yb	Ytterbium	173.04	175		7	1097	1467	6.97
71	6	3	Lu	Lutetium	174.97	175		1	1936	3668	9.84
72	6	4	Hf	Hafnium	178.49	155		5	2506	4876	13.31
73	6	5	Ta	Tantalum	180.95	145		1	3290	5731	16.68
74	6	6	W	Tungsten	183.84	135		4	3695	5828	19.26
75	6	7	Re	Rhenium	186.21	135		1	3459	5869	21.03
76	6	8	Os	Osmium	190.23	130		6	3306	5285	22.61
77	6	9	Ir	Iridium	192.22	135		2	2739	4701	22.65
78	6	10	Pt	Platinum	195.08	135		5-Apr	2045	4100	21.45
79	6	11	Au	Gold	196.97	135		1	1337	3129	19.32
80	6	12	Hg	Mercury	200.59	150		7	234	630	13.55
81	6	13	Tl	Thallium	204.38	190	3	2	577	1746	11.85
82	6	14	Pb	Lead	207.2	180	4	3	601	2023	11.34
83	6	15	Bi	Bismuth	208.98	160	5		544	1837	9.8
84	6	16	Po	Polonium	209	190	6		527	1235	9.2
85	6	17	At	Astatine	210		7		575	610	
86	6	18	Rn	Radon	222	120	8		202	211	9.23*
87	7	1	Fr	Francium	223		1		~300	~950	
88	7	2	Ra	Radium	226	215	2		973	2010	5.5
89	7	3	Ac	Actinium	227	195			1327	3473	10.07
90	7	3	Th	Thorium	232.04	180			2028	5061	11.72
91	7	3	Pa	Protactinium	231.04	180			2113	4300	15.37
92	7	3	U	Uranium	238.03	175			1406	4203	18.97
93	7	3	Np	Neptunium	237	175			912	4175	20.48
94	7	3	Pu	Plutonium	244	175			913	3509	19.74
95	7	3	Am	Americium	243	175			1449	2880	13.67
96	7	3	Cm	Curium	247				1613	3383	13.51
97	7	3	Bk	Berkelium	247				1259		13.25
98	7	3	Cf	Californium	251				1173	1743	15.1
99	7	3	Es	Einsteinium	252				1133		
100	7	3	Fm	Fermium	257				1800		
101	7	3	Md	Mendelevium	258				1100		
102	7	3	No	Nobelium	259				1100		
103	7	3	Lr	Lawrencium	262						
104	7	4	Rf	Rutherfordium	267						
105	7	5	Db	Dubnium	262						
106	7	6	Sg	Seaborgium	266						
107	7	7	Bh	Bohrium	264						
108	7	8	Hs	Hassium	277						
109	7	9	Mt	Meitnerium	268						
110	7	10	Ds	Darmstadtium	281						
111	7	11	Rg	Roentgenium	280						
112	7	12	Cp	Copernicium	277						
113	7	13	Nh	Nihonium	~287		3				
114	7	14	Fl	Flerovium	289		4				
115	7	15	Mc	Moscovium	~288		5				
116	7	16	Lv	Livermorium	~289		6				
117	7	17	Ts	Tenessine	~291		7				
118	7	18	Og	Oganesson	294						
In [ ]:
#elements_file_read.py

def read_elements_data(file_name):
    with open(file_name, 'r') as file:
        lines = file.readlines()

    elements = []
    headers = lines[0].strip().split('\t')
    for line in lines[1:]:
        data = line.strip().split('\t')
        element = dict(zip(headers, data))
        elements.append(element)

    return elements

def print_elements_table(elements):
    headers = elements[0].keys()
    column_widths = [max(len(header), max(len(element.get(header, '')) for element in elements)) for header in headers]

    print('|'.join(format(header, f'^{width}') for header, width in zip(headers, column_widths)))
    print('-' * (sum(column_widths) + len(column_widths) * 3 - 1))

    for element in elements:
        row = [format(element[header], f'^{width}') for header, width in zip(headers, column_widths)]
        print('|'.join(row))

file_name = 'elements_data.txt'
elements = read_elements_data(file_name)
print_elements_table(elements)
In [ ]:
#grades.txt

English 75 85 80 70 90
Science 90 95 80 85 75
History 70 75 80 85 90
Geography 85 80 75 90 95
Algebra 45 100 100 100 100
Math 2412: [100.0, 85.0, 75.0, 65.0, 80.0]
In [ ]:
#interactive_jungle.py

import random

class InteractivePrompt:
    @staticmethod
    def get_choice(prompt, options):
        while True:
            print(prompt)
            for i, option in enumerate(options, start=1):
                print(f"{i}. {option}")
            try:
                choice = int(input("Enter your choice: "))
                if 1 <= choice <= len(options):
                    return choice
                else:
                    print("Invalid choice. Please try again.")
            except ValueError:
                print("Invalid input. Please enter a number.")

    def run(self):
        print("Welcome to the Interactive Prompt!")

        while True:
            category_choice = self.get_choice(
                "Choose a category:",
                ["Car", "Animal", "Food", "Exit"]
            )

            if category_choice == 1:  # Car
                car_makers = ["Toyota", "Ford", "Honda"]
                car_maker_choice = self.get_choice(
                    "Choose a car maker:",
                    car_makers
                )
                selected_maker = car_makers[car_maker_choice - 1]

                car_models = ["Camry", "Mustang", "Civic"]
                selected_model = random.choice(car_models)

                print(f"Vroom, vroom! You selected a {selected_maker} {selected_model}")

            elif category_choice == 2:  # Animal
                animal_types = ["Mammals", "Birds", "Fish"]
                animal_type_choice = self.get_choice(
                    "Choose a type of animal:",
                    animal_types
                )
                selected_type = animal_types[animal_type_choice - 1]

                if selected_type == "Mammals":
                    mammals = ["Dog", "Cat", "Elephant"]
                    selected_animal = random.choice(mammals)
                elif selected_type == "Birds":
                    birds = ["Sparrow", "Eagle", "Penguin"]
                    selected_animal = random.choice(birds)
                else:
                    fish = ["Salmon", "Tuna", "Shark"]
                    selected_animal = random.choice(fish)

                print(f"Good fella! This is a {selected_animal}")

            elif category_choice == 3:  # Food
                food_types = ["Dessert", "Fruit", "Beverage"]
                food_type_choice = self.get_choice(
                    "Choose a type of food:",
                    food_types
                )
                selected_type = food_types[food_type_choice - 1]

                if selected_type == "Dessert":
                    desserts = ["Cake", "Ice Cream", "Cookies"]
                    selected_food = random.choice(desserts)
                elif selected_type == "Fruit":
                    fruits = ["Apple", "Banana", "Orange"]
                    selected_food = random.choice(fruits)
                else:
                    beverages = ["Coffee", "Tea", "Soda"]
                    selected_food = random.choice(beverages)

                print(f"Yummy, this is a {selected_food}")

            elif category_choice == 4:  # Exit
                print("Thank you for using the interacive module. Goodbye!")
                break

            else:
                print("Fatal error! Please try again.")

if __name__ == "__main__":
    prompt = InteractivePrompt()
    prompt.run()
In [ ]:
#languages.py

class Language:
    # define class attributes
    Grammar = "a set of rules that describe how words and phrases are arranged in a language"
    Languages = ["English", "Spanish", "French", "German", "Chinese", "Japanese"]
    Recognizing_Automaton = "a mathematical model of computation that can recognize strings belonging to a language"
    Production_rules = {
        "Regular Grammar": "describes regular languages that can be recognized by finite automata",
        "Context-Free Grammar": "describes context-free languages that can be recognized by pushdown automata",
        "Context-Sensitive Grammar": "describes context-sensitive languages that can be recognized by linear-bounded automata",
        "Unrestricted Grammar": "describes recursively enumerable languages that can be recognized by Turing machines"
    }
    Examples = {
        "English": ["Hello, World!", "How are you?", "I love programming"],
        "Spanish": ["¡Hola, mundo!", "¿Cómo estás?", "Me encanta programar"],
        "French": ["Bonjour le monde!", "Comment ça va?", "J'adore programmer"],
        "German": ["Hallo, Welt!", "Wie geht es dir?", "Ich liebe programmieren"],
        "Chinese": ["你好,世界!", "你好吗?", "我喜欢编程"],
        "Japanese": ["こんにちは、世界!", "元気ですか?", "プログラミングが大好きです"]
    }

    def __init__(self, name):
        # define instance attribute
        self.name = name

    def __str__(self):
        # return a string representation of the instance
        return f"This is an instance of the Language class with the name {self.name}"

    @classmethod
    def recognize(cls, language_name):
        if language_name in cls.Languages:
            language = cls(language_name)
            print(f"Recognized language: {language.name}")
            print(f"Grammar: {cls.Grammar}")
            print(f"Recognizing Automaton: {cls.Recognizing_Automaton}")
            print(f"Production Rules (Constraints):")
            for rule, description in cls.Production_rules.items():
                print(f"- {rule}: {description}")
            print(f"Examples using {language.name}:")
            for example in cls.Examples[language.name]:
                print(f"- {example}")
        else:
            print("Language not recognized.")

def recognize_programming_language():
    print("Welcome to the Programming Language Recognition System!")
    print("This system can provide information about various programming languages.")
    print("Here are the available languages:")
    print(Language.Languages)
    
    while True:
        language_name = input("Enter the name of a programming language or 'exit' to quit: ")
        if language_name.lower() == "exit":
            print("Thank you for using the Programming Language Recognition System. Goodbye!")
            break
        else:
            Language.recognize(language_name)
            print()

# Example usage:
recognize_programming_language()
In [ ]:
#osi_model(master).py

layers = [
    [],
    [],
    [],
    [],
    [],
    [],
    []
]
	
	# Layer 7: Application
layers[6].extend(['Web Application Firewall', 'Load Balancer', 'API Gateway'])
	
	# Layer 6: Presentation
layers[5].extend(['Data Encryption', 'Data Compression'])
	
	# Layer 5: Session
layers[4].extend(['Session Management', 'Connection Tracking'])
	
	# Layer 4: Transport
layers[3].extend(['TCP Segmentation', 'UDP Checksum'])
	
	# Layer 3: Network
layers[2].extend(['Routing', 'IP Addressing'])
	
	# Layer 2: Data Link
layers[1].extend(['MAC Addressing', 'Switching', 'VLAN'])
	
	# Layer 1: Physical
layers[0].extend(['Ethernet', 'Fiber Optics'])
	
	# Sort devices within each layer
for layer in layers:
    layer.sort()
	
	# Determine the maximum number of devices in a layer
max_devices = max(len(layer) for layer in layers)
	
	# Display the layers and their devices in tabular format
print("OSI Model Layers and Devices:")
print("--------------------------------------------")
print("| {:^15} | {:^15} ".format("Layer", "Devices"))
print("|-----------------|-------------------------")
	
for i, layer in enumerate(layers, start=1):
    devices = layer + [''] * (max_devices - len(layer))
    print("| {:<15} | {:<15} ".format(f"Layer {i}", devices[0]))
	
    for device in devices[1:]:
        print("| {:<15} | {:<15} ".format("", device))
	
    print("|-----------------|-------------------------")
In [ ]:
#polyhedra.py

def display_polyhedra(polyhedra_data):
    print("Polyhedra")
    
    # Calculate the length of the longest line
    longest_line_length = max(len(polyhedron['Name']) for polyhedron in polyhedra_data)
    
    # Format the table header
    header_format = "{:<{}} {:<17} {:<6} {:<8} {:<6} {:<6} {:<6} {:<6} {:<8} {:<6} {:<10}"
    header = header_format.format(
        "Name", longest_line_length,
        "Wythoff", "Sym.", "C#", "W#", "U#", "K#", "Vert.", "Edges", "Faces", "Faces by Type"
    )
    print(header)
    
    # Format the line of dashes
    line_format = "{:-<{}}"
    line = line_format.format("-", len(header))
    print(line)
    
    # Format and display the polyhedra data
    data_format = "{:<{}} {:<17} {:<6} {:<8} {:<6} {:<6} {:<6} {:<6} {:<8} {:<6} {:<10}"
    for polyhedron in polyhedra_data:
        name = polyhedron['Name']
        wythoff = polyhedron['Wythoff']
        symbol = polyhedron['Sym.']
        c_num = polyhedron['C#']
        w_num = polyhedron['W#']
        u_num = polyhedron['U#']
        k_num = polyhedron['K#']
        vertices = polyhedron['Vert.']
        edges = polyhedron['Edges']
        faces = polyhedron['Faces']
        faces_by_type = polyhedron['Faces by Type']
        data_line = data_format.format(
            name, longest_line_length,
            wythoff, symbol, c_num, w_num, u_num, k_num, vertices,
            edges, faces, faces_by_type
        )
        print(data_line)
    print()



def parse_polyhedra_data():
    polyhedra_data = []
    polyhedra = [
        ["Tetrahedron", "3 | 2 3", "Td", "C15", "W001", "U01", "K06", 4, 6, 4, "4{3}"],
        ["Triangular prism", "2 3 | 2", "D3h", "C33a", "—", "U76a", "K01a", 6, 9, 5, "2{3}+3{4}"],
        ["Truncated tetrahedron", "2 3 | 3", "Td", "C16", "W006", "U02", "K07", 12, 18, 8, "4{3}+4{6}"],
        ["Truncated cube", "2 3 | 4", "Oh", "C21", "W008", "U09", "K14", 24, 36, 14, "8{3}+6{8}"],
        ["Truncated dodecahedron", "2 3 | 5", "Ih", "C29", "W010", "U26", "K31", 60, 90, 32, "20{3}+12{10}"],
        ["Cube", "3 | 2 4", "Oh", "C18", "W003", "U06", "K11", 8, 12, 6, "6{4}"],
        ["Pentagonal prism", "2 5 | 2", "D5h", "C33b", "—", "U76b", "K01b", 10, 15, 7, "5{4}+2{5}"],
        ["Hexagonal prism", "2 6 | 2", "D6h", "C33c", "—", "U76c", "K01c", 12, 18, 8, "6{4}+2{6}"],
        ["Heptagonal prism", "2 7 | 2", "D7h", "C33d", "—", "U76d", "K01d", 14, 21, 9, "7{4}+2{7}"],
        ["Octagonal prism", "2 8 | 2", "D8h", "C33e", "—", "U76e", "K01e", 16, 24, 10, "8{4}+2{8}"],
        ["Enneagonal prism", "2 9 | 2", "D9h", "C33f", "—", "U76f", "K01f", 18, 27, 11, "9{4}+2{9}"],
        ["Decagonal prism", "2 10 | 2", "D10h", "C33g", "—", "U76g", "K01g", 20, 30, 12, "10{4}+2{10}"],
        ["Hendecagonal prism", "2 11 | 2", "D11h", "C33h", "—", "U76h", "K01h", 22, 33, 13, "11{4}+2{11}"],
        ["Dodecagonal prism", "2 12 | 2", "D12h", "C33i", "—", "U76i", "K01i", 24, 36, 14, "12{4}+2{12}"],
        ["Truncated octahedron", "2 4 | 3", "Oh", "C20", "W007", "U08", "K13", 24, 36, 14, "6{4}+8{6}"],
        ["Truncated cuboctahedron", "2 3 4 |", "Oh", "C23", "W015", "U11", "K16", 48, 72, 26, "12{4}+8{6}+6{8}"],
        ["Truncated icosidodecahedron", "2 3 5 |", "Ih", "C31", "W016", "U28", "K33", 120, 180, 62, "30{4}+20{6}+12{10}"],
        ["Dodecahedron", "3 | 2 5", "Ih", "C26", "W005", "U23", "K28", 20, 30, 12, "12{5}"],
        ["Truncated icosahedron", "2 5 | 3", "Ih", "C27", "W009", "U25", "K30", 60, 90, 32, "12{5}+20{6}"],
        ["Octahedron", "4 | 2 3", "Oh", "C17", "W002", "U05", "K10", 6, 12, 8, "8{3}"],
        ["Square antiprism", "| 2 2 4", "D4d", "C34a", "—", "U77a", "K02a", 8, 16, 10, "8{3}+2{4}"],
        ["Pentagonal antiprism", "| 2 2 5", "D5d", "C34b", "—", "U77b", "K02b", 10, 20, 12, "10{3}+2{5}"],
        ["Hexagonal antiprism", "| 2 2 6", "D6d", "C34c", "—", "U77c", "K02c", 12, 24, 14, "12{3}+2{6}"],
        ["Heptagonal antiprism", "| 2 2 7", "D7d", "C34d", "—", "U77d", "K02d", 14, 28, 16, "14{3}+2{7}"],
        ["Octagonal antiprism", "| 2 2 8", "D8d", "C34e", "—", "U77e", "K02e", 16, 32, 18, "16{3}+2{8}"],
        ["Enneagonal antiprism", "| 2 2 9", "D9d", "C34f", "—", "U77f", "K02f", 18, 36, 20, "18{3}+2{9}"],
        ["Decagonal antiprism", "| 2 2 10", "D10d", "C34g", "—", "U77g", "K02g", 20, 40, 22, "20{3}+2{10}"],
        ["Hendecagonal antiprism", "| 2 2 11", "D11d", "C34h", "—", "U77h", "K02h", 22, 44, 24, "22{3}+2{11}"],
        ["Dodecagonal antiprism", "| 2 2 12", "D12d", "C34i", "—", "U77i", "K02i", 24, 48, 26, "24{3}+2{12}"],
        ["Cuboctahedron", "2 | 3 4", "Oh", "C19", "W011", "U07", "K12", 12, 24, 14, "8{3}+6{4}"],
        ["Rhombicuboctahedron", "3 4 | 2", "Oh", "C22", "W013", "U10", "K15", 24, 48, 26, "8{3}+(6+12){4}"],
        ["Rhombicosidodecahedron", "3 5 | 2", "Ih", "C30", "W014", "U27", "K32", 60, 120, 62, "20{3}+30{4}+12{5}"],
        ["Icosidodecahedron", "2 | 3 5", "Ih", "C28", "W012", "U24", "K29", 30, 60, 32, "20{3}+12{5}"],
        ["Icosahedron", "5 | 2 3", "Ih", "C25", "W004", "U22", "K27", 12, 30, 20, "20{3}"],
        ["Snub cube", "| 2 3 4", "O", "C24", "W017", "U12", "K17", 24, 60, 38, "(8+24){3}+6{4}"],
        ["Snub dodecahedron", "| 2 3 5", "I", "C32", "W018", "U29", "K34", 60, 150, 92, "(20+60){3}+12{10}"],
        ["Octahemioctahedron", "3/2 3 | 3", "Oh", "C37", "W068", "U03", "K08", 12, 24, 12, "8{3}+4{6}"],
        ["Tetrahemihexahedron", "3/2 3 | 2", "Td", "C36", "W067", "U04", "K09", 6, 12, 7, "4{3}+3{4}"],
        ["Cubohemioctahedron", "4/3 4 | 3", "Oh", "C51", "W078", "U15", "K20", 12, 24, 10, "6{4}+4{6}"],
        ["Great dodecahedron", "5/2 | 2 5", "Ih", "C44", "W021", "U35", "K40", 12, 30, 12, "12{5}"],
        ["Great icosahedron", "5/2 | 2 3", "Ih", "C69", "W041", "U53", "K58", 12, 30, 20, "20{3}"],
        ["Great ditrigonal icosidodecahedron", "3/2 | 3 5", "Ih", "C61", "W087", "U47", "K52", 20, 60, 32, "20{3}+12{5}"],
        ["Small rhombihexahedron", "2 4 (3/2 4/2) |", "Oh", "C60", "W086", "U18", "K23", 24, 48, 18, "12{4}+6{8}"],
        ["Small cubicuboctahedron", "3/2 4 | 4", "Oh", "C38", "W069", "U13", "K18", 24, 48, 20, "8{3}+6{4}+6{8}"],
        ["Great rhombicuboctahedron", "3/2 4 | 2", "Oh", "C59", "W085", "U17", "K22", 24, 48, 26, "8{3}+(6+12){4}"],
        ["Small dodecahemiicosahedron", "5/4 5 | 5", "Ih", "C65", "W091", "U51", "K56", 30, 60, 18, "12{5}+6{10}"],
        ["Great dodecahemidodecahedron", "5/4 5 | 3", "Ih", "C81", "W102", "U65", "K70", 30, 60, 22, "12{5}+10{6}"],
        ["Small icosihemidodecahedron", "3/2 3 | 5", "Ih", "C63", "W089", "U49", "K54", 30, 60, 26, "20{3}+6{10}"],
        ["Small dodecicosahemidodecahedron", "3/2 5 | 5", "Ih", "C42", "W072", "U33", "K38", 60, 120, 44, "20{3}+12{5}+12{10}"],
        ["Rhombicosahedron", "2 3 (5/4 5/2) |", "Ih", "C72", "W096", "U56", "K61", 60, 120, 50, "30{4}+20{6}"],
        ["Great icosicosidodecahedron", "3/2 3 | 5/3", "Ih", "C79", "W101", "U63", "K68", 60, 120, 52, "20{3}+12{5}+20{6}"],
        ["Great rhombidodecahedron", "2 5/2 (3/2 5/2) |", "Ih", "C89", "W109", "U73", "K78", 60, 120, 42, "30{4}+12{10/3}"],
        ["Icosidodecahedron", "2 5/3 (3/2 5/4) |", "Ih", "C91", "W118", "U72", "K77", 60, 120, 44, "20{3}+12{5/2}+12{5/2}"],
        ["Small dodecicosahemidodecahedron", "3/2 5 | 5", "Ih", "C90", "W117", "U74", "K79", 60, 120, 44, "20{3}+12{5/2}+12{5/2}"],
        ["Great snub cube", "| 2 3 4", "I", "C49", "W111", "U40", "K45", 60, 150, 84, "60{3}+12{5}+12{5/2}"],
        ["Great inverted snub dodecahedron", "| 2 3 5", "I", "C76", "W114", "U60", "K65", 60, 150, 84, "60{3}+12{5}+12{5/2}"],
        ["Great snub icosidodecahedron", "| 2 3 5", "I", "C73", "W113", "U57", "K62", 60, 150, 92, "(20+60){3}+12{5/2}"],
        ["Great inverted snub icosidodecahedron", "| 2 3 5", "I", "C88", "W116", "U69", "K74", 60, 150, 92, "(20+60){3}+12{5/2}"],
        ["Great inverted snub icosidodecahedron", "| 2 3 5", "I", "C80", "W115", "U64", "K69", 60, 180, 104, "(20+60){3}+(12+12){5/2}"],
        ["Snub dodecahedron", "| 5/3 2 5", "I", "C49", "W111", "U40", "K45", 60, 150, 84, "(60+12){3}+12{5}+12{5/2}"],
        ["Great snub dodecahedron", "| 3/2 5/2 5/3", "I", "C73", "W113", "U57", "K62", 60, 150, 92, "(20+60){3}+12{5/2}"],
        ["Great retrosnub dodecahedron", "| 3/2 5/2 5/4", "I", "C88", "W116", "U69", "K74", 60, 150, 92, "(20+60){3}+12{5/2}"],
        ["Great retrosnub icosidodecahedron", "| 3/2 5/2 5/4", "I", "C80", "W115", "U64", "K69", 60, 180, 104, "(20+60){3}+(12+12){5/2}"],
        ["Great retrosnub icosidodecahedron", "| 3/2 5/2 5/4", "I", "C90", "W117", "U74", "K79", 60, 180, 104, "(20+60){3}+(12+12){5/2}"],
        ["Great retrosnub icosicosidodecahedron", "| 3/2 5/3 3 5/2", "I", "C92", "W119", "U75", "K80", 60, 240, 124, "40{3}+60{4}+24{5/2}"],
    ]

    for polyhedron_data in polyhedra:
        polyhedron = {
            'Name': polyhedron_data[0],
            'Wythoff': polyhedron_data[1],
            'Sym.': polyhedron_data[2],
            'C#': polyhedron_data[3],
            'W#': polyhedron_data[4],
            'U#': polyhedron_data[5],
            'K#': polyhedron_data[6],
            'Vert.': polyhedron_data[7],
            'Edges': polyhedron_data[8],
            'Faces': polyhedron_data[9],
            'Faces by Type': polyhedron_data[10],
        }
        polyhedra_data.append(polyhedron)
    return polyhedra_data

# Parse the polyhedra data
polyhedra_data = parse_polyhedra_data()

# Display the polyhedra
display_polyhedra(polyhedra_data)
In [ ]:
#polyhedra.txt

Tetrahedron,3 | 2 3,Td,C15,W001,U01,K06,4,6,4,4{3}
Triangular prism,2 3 | 2,D3h,C33a,—,U76a,K01a,6,9,5,2{3}+3{4}
Truncated tetrahedron,2 3 | 3,Td,C16,W006,U02,K07,12,18,8,4{3}+4{6}
Truncated cube,2 3 | 4,Oh,C21,W008,U09,K14,24,36,14,8{3}+6{8}
Truncated dodecahedron,2 3 | 5,Ih,C29,W010,U26,K31,60,90,32,20{3}+12{10}
Cube,3 | 2 4,Oh,C18,W003,U06,K11,8,12,6,6{4}
Pentagonal prism,2 5 | 2,D5h,C33b,—,U76b,K01b,10,15,7,5{4}+2{5}
Hexagonal prism,2 6 | 2,D6h,C33c,—,U76c,K01c,12,18,8,6{4}+2{6}
Heptagonal prism,2 7 | 2,D7h,C33d,—,U76d,K01d,14,21,9,7{4}+2{7}
Octagonal prism,2 8 | 2,D8h,C33e,—,U76e,K01e,16,24,10,8{4}+2{8}
Enneagonal prism,2 9 | 2,D9h,C33f,—,U76f,K01f,18,27,11,9{4}+2{9}
Decagonal prism,2 10 | 2,D10h,C33g,—,U76g,K01g,20,30,12,10{4}+2{10}
Hendecagonal prism,2 11 | 2,D11h,C33h,—,U76h,K01h,22,33,13,11{4}+2{11}
Dodecagonal prism,2 12 | 2,D12h,C33i,—,U76i,K01i,24,36,14,12{4}+2{12}
Truncated octahedron,2 4 | 3,Oh,C20,W007,U08,K13,24,36,14,6{4}+8{6}
Truncated cuboctahedron,2 3 4 |,Oh,C23,W015,U11,K16,48,72,26,12{4}+8{6}+6{8}
Truncated icosidodecahedron,2 3 5 |,Ih,C31,W016,U28,K33,120,180,62,30{4}+20{6}+12{10}
Dodecahedron,3 | 2 5,Ih,C26,W005,U23,K28,20,30,12,12{5}
Truncated icosahedron,2 5 | 3,Ih,C27,W009,U25,K30,60,90,32,12{5}+20{6}
Octahedron,4 | 2 3,Oh,C17,W002,U05,K10,6,12,8,8{3}
Square antiprism,| 2 2 4,D4d,C34a,—,U77a,K02a,8,16,10,8{3}+2{4}
Pentagonal antiprism,| 2 2 5,D5d,C34b,—,U77b,K02b,10,20,12,10{3}+2{5}
Hexagonal antiprism,| 2 2 6,D6d,C34c,—,U77c,K02c,12,24,14,12{3}+2{6}
Heptagonal antiprism,| 2 2 7,D7d,C34d,—,U77d,K02d,14,28,16,14{3}+2{7}
Octagonal antiprism,| 2 2 8,D8d,C34e,—,U77e,K02e,16,32,18,16{3}+2{8}
Enneagonal antiprism,| 2 2 9,D9d,C34f,—,U77f,K02f,18,36,20,18{3}+2{9}
Decagonal antiprism,| 2 2 10,D10d,C34g,—,U77g,K02g,20,40,22,20{3}+2{10}
Hendecagonal antiprism,| 2 2 11,D11d,C34h,—,U77h,K02h,22,44,24,22{3}+2{11}
Dodecagonal antiprism,| 2 2 12,D12d,C34i,—,U77i,K02i,24,48,26,24{3}+2{12}
Cuboctahedron,2 | 3 4,Oh,C19,W011,U07,K12,12,24,14,8{3}+6{4}
Rhombicuboctahedron,3 4 | 2,Oh,C22,W013,U10,K15,24,48,26,8{3}+(6+12){4}
Rhombicosidodecahedron,3 5 | 2,Ih,C30,W014,U27,K32,60,120,62,20{3}+30{4}+12{5}
Icosidodecahedron,2 | 3 5,Ih,C28,W012,U24,K29,30,60,32,20{3}+12{5}
Icosahedron,5 | 2 3,Ih,C25,W004,U22,K27,12,30,20,20{3}
Snub cube,| 2 3 4,O,C24,W017,U12,K17,24,60,38,(8+24){3}+6{4}
Snub dodecahedron,| 2 3 5,I,C32,W018,U29,K34,60,150,92,(20+60){3}+12{10}
Octahemioctahedron,3/2 3 | 3,Oh,C37,W068,U03,K08,12,24,12,8{3}+4{6}
Tetrahemihexahedron,3/2 3 | 2,Td,C36,W067,U04,K09,6,12,7,4{3}+3{4}
Cubohemioctahedron,4/3 4 | 3,Oh,C51,W078,U15,K20,12,24,10,6{4}+4{6}
Great dodecahedron,5/2 | 2 5,Ih,C44,W021,U35,K40,12,30,12,12{5}
Great icosahedron,5/2 | 2 3,Ih,C69,W041,U53,K58,12,30,20,20{3}
Great ditrigonal icosidodecahedron,3/2 | 3 5,Ih,C61,W087,U47,K52,20,60,32,20{3}+12{5}
Small rhombihexahedron,2 4 (3/2 4/2) |,Oh,C60,W086,U18,K23,24,48,18,12{4}+6{8}
Small cubicuboctahedron,3/2 4 | 4,Oh,C38,W069,U13,K18,24,48,20,8{3}+6{4}+6{8}
Great rhombicuboctahedron,3/2 4 | 2,Oh,C59,W085,U17,K22,24,48,26,8{3}+(6+12){4}
Small dodecahemiicosahedron,5/4 5 | 5,Ih,C65,W091,U51,K56,30,60,18,12{5}+6{10}
Great dodecahemidodecahedron,5/4 5 | 3,Ih,C81,W102,U65,K70,30,60,22,12{5}+10{6}
Small icosihemidodecahedron,3/2 3 | 5,Ih,C63,W089,U49,K54,30,60,26,20{3}+6{10}
Small dodecicosahemidodecahedron,3/2 5 | 5,Ih,C42,W072,U33,K38,60,120,44,20{3}+12{5}+12{10}
Rhombicosahedron,2 3 (5/4 5/2) |,Ih,C72,W096,U56,K61,60,120,50,30{4}+20{6}
Great icosicosidodecahedron,3/2 3 | 5/3,Ih,C79,W101,U63,K68,60,120,52,20{3}+12{5}+20{6}
Great rhombidodecahedron,2 5/2 (3/2 5/2) |,Ih,C89,W109,U73,K78,60,120,42,30{4}+12{10/3}
Icosidodecahedron,2 5/3 (3/2 5/4) |,Ih,C91,W118,U72,K77,60,120,44,20{3}+12{5/2}+12{5/2}
Small dodecicosahemidodecahedron,3/2 5 | 5,Ih,C90,W117,U74,K79,60,120,44,20{3}+12{5/2}+12{5/2}
Great snub cube,| 2 3 4,I,C49,W111,U40,K45,60,150,84,60{3}+12{5}+12{5/2}
Great inverted snub dodecahedron,| 2 3 5,I,C76,W114,U60,K65,60,150,84,60{3}+12{5}+12{5/2}
Great snub icosidodecahedron,| 2 3 5,I,C73,W113,U57,K62,60,150,92,(20+60){3}+12{5/2}
Great inverted snub icosidodecahedron,| 2 3 5,I,C88,W116,U69,K74,60,150,92,(20+60){3}+12{5/2}
Great inverted snub icosidodecahedron,| 2 3 5,I,C80,W115,U64,K69,60,180,104,(20+60){3}+(12+12){5/2}
Snub dodecahedron,| 5/3 2 5,I,C49,W111,U40,K45,60,150,84,(60+12){3}+12{5}+12{5/2}
Great snub dodecahedron,| 3/2 5/2 5/3,I,C73,W113,U57,K62,60,150,92,(20+60){3}+12{5/2}
Great retrosnub dodecahedron,| 3/2 5/2 5/4,I,C88,W116,U69,K74,60,150,92,(20+60){3}+12{5/2}
Great retrosnub icosidodecahedron,| 3/2 5/2 5/4,I,C80,W115,U64,K69,60,180,104,(20+60){3}+(12+12){5/2}
Great retrosnub icosidodecahedron,| 3/2 5/2 5/4,I,C90,W117,U74,K79,60,180,104,(20+60){3}+(12+12){5/2}
Great retrosnub icosicosidodecahedron,| 3/2 5/3 3 5/2,I,C92,W119,U75,K80,60,240,124,40{3}+60{4}+24{5/2}
In [ ]:
#polyhedra(script).py

def create_polyhedra_database_from_file(file_path):
    database = []
    with open(file_path, 'r') as file:
        for line in file:
            line = line.strip()
            if line:
                try:
                    polyhedron_data = line.split(',')
                    name = polyhedron_data[0].strip()
                    wythoff = polyhedron_data[1].strip()
                    symbol = polyhedron_data[2].strip()
                    c_num = polyhedron_data[3].strip()
                    w_num = polyhedron_data[4].strip()
                    u_num = polyhedron_data[5].strip()
                    k_num = polyhedron_data[6].strip()
                    vertices = int(polyhedron_data[7].strip())
                    edges = int(polyhedron_data[8].strip())
                    faces = int(polyhedron_data[9].strip())
                    faces_by_type = polyhedron_data[10].strip()

                    polyhedron = {
                        'name': name,
                        'wythoff': wythoff,
                        'symbol': symbol,
                        'c_num': c_num,
                        'w_num': w_num,
                        'u_num': u_num,
                        'k_num': k_num,
                        'vertices': vertices,
                        'edges': edges,
                        'faces': faces,
                        'faces_by_type': faces_by_type
                    }
                    database.append(polyhedron)
                except IndexError:
                    print("Invalid data format in line: ", line)
    return database


def filter_polyhedra_by_field(database, field_name, field_value):
    filtered_polyhedra = []
    for polyhedron in database:
        if field_name in polyhedron and polyhedron[field_name] == field_value:
            filtered_polyhedra.append(polyhedron)
    return filtered_polyhedra


def group_polyhedra_by_attribute(database, attribute):
    grouped_polyhedra = {}
    for polyhedron in database:
        if attribute in polyhedron:
            attribute_value = polyhedron[attribute]
            if attribute_value in grouped_polyhedra:
                grouped_polyhedra[attribute_value].append(polyhedron)
            else:
                grouped_polyhedra[attribute_value] = [polyhedron]
    return grouped_polyhedra


def calculate_similarity(polyhedron1, polyhedron2):
    similarity_score = 0
    attributes_to_compare = ['vertices', 'edges', 'faces']
    for attribute in attributes_to_compare:
        if attribute in polyhedron1 and attribute in polyhedron2:
            value1 = polyhedron1[attribute]
            value2 = polyhedron2[attribute]
            similarity_score += abs(value1 - value2)
    return similarity_score


def find_most_similar_polyhedron(database, polyhedron):
    most_similar_polyhedron = None
    min_similarity_score = float('inf')
    for other_polyhedron in database:
        if other_polyhedron != polyhedron:
            similarity_score = calculate_similarity(polyhedron, other_polyhedron)
            if similarity_score < min_similarity_score:
                min_similarity_score = similarity_score
                most_similar_polyhedron = other_polyhedron
    return most_similar_polyhedron


def print_polyhedron(polyhedron):
    print('Name:', polyhedron['name'])
    print('Wythoff:', polyhedron['wythoff'])
    print('Symbol:', polyhedron['symbol'])
    print('C#:', polyhedron['c_num'])
    print('W#:', polyhedron['w_num'])
    print('U#:', polyhedron['u_num'])
    print('K#:', polyhedron['k_num'])
    print('Vertices:', polyhedron['vertices'])
    print('Edges:', polyhedron['edges'])
    print('Faces:', polyhedron['faces'])
    print('Faces by Type:', polyhedron['faces_by_type'])
    print()


def interactive_polyhedra_comparison():
    file_path = 'polyhedra.txt'
    database = create_polyhedra_database_from_file(file_path)

    while True:
        print("--- Polyhedra Comparison ---")
        print("1. Filter polyhedra by field")
        print("2. Group polyhedra by attribute")
        print("3. Find most similar polyhedron")
        print("4. Exit")

        choice = input("Enter your choice (1-4): ")

        if choice == '1':
            field_name = input("Enter the field name to filter by: ")
            field_value = input("Enter the field value to filter by: ")
            filtered_polyhedra = filter_polyhedra_by_field(database, field_name, field_value)
            print("Filtered Polyhedra:")
            for polyhedron in filtered_polyhedra:
                print_polyhedron(polyhedron)

        elif choice == '2':
            attribute = input("Enter the attribute to group polyhedra by: ")
            grouped_polyhedra = group_polyhedra_by_attribute(database, attribute)
            print("Grouped Polyhedra:")
            for attribute_value, polyhedra in grouped_polyhedra.items():
                print(f"Attribute: {attribute_value}")
                for polyhedron in polyhedra:
                    print_polyhedron(polyhedron)
                print()

        elif choice == '3':
            polyhedron_name = input("Enter the name of the polyhedron: ")
            target_polyhedron = None
            for polyhedron in database:
                if polyhedron['name'].lower() == polyhedron_name.lower():
                    target_polyhedron = polyhedron
                    break
            if target_polyhedron:
                similar_polyhedron = find_most_similar_polyhedron(database, target_polyhedron)
                print("Most Similar Polyhedron:")
                print_polyhedron(similar_polyhedron)
            else:
                print("Polyhedron not found in the database.")

        elif choice == '4':
            break

        print()

interactive_polyhedra_comparison()
In [ ]:
#programming_lang.py

class Language:
    # define class attributes
    Grammar = "a set of rules that describe how words and phrases are arranged in a language"
    Languages = {
        "Python": {
            "Field": "General-purpose",
            "Recognizing_Automaton": "Python virtual machine",
            "Production_rules": "Python syntax and semantics",
            "Examples": ["print('Hello, world!')", "x = 5 + 3", "import math"]
        },
        "Java": {
            "Field": "General-purpose",
            "Recognizing_Automaton": "Java Virtual Machine (JVM)",
            "Production_rules": "Java syntax and semantics",
            "Examples": ["System.out.println('Hello, world!');", "int x = 5 + 3;", "import java.util.*;"]
        },
        "C": {
            "Field": "Systems programming",
            "Recognizing_Automaton": "C compiler",
            "Production_rules": "C syntax and semantics",
            "Examples": ["printf('Hello, world!');", "int x = 5 + 3;", "#include <stdio.h>"]
        },
        "Fortran": {
            "Field": "Scientific computing",
            "Recognizing_Automaton": "Fortran compiler",
            "Production_rules": "Fortran syntax and semantics",
            "Examples": ["WRITE(*,*) 'Hello, world!'", "REAL :: x = 5.0 + 3.0", "USE math_module"]
        },
        "Ruby": {
            "Field": "Web development",
            "Recognizing_Automaton": "Ruby interpreter",
            "Production_rules": "Ruby syntax and semantics",
            "Examples": ["puts 'Hello, world!'", "x = 5 + 3", "require 'math'"]
        }
        # Add more programming languages and their attributes here...
    }

    def __init__(self, name):
        # define instance attribute
        self.name = name

    def __str__(self):
        # return a string representation of the instance
        return f"This is an instance of the Language class with the name {self.name}"

    @classmethod
    def recognize(cls, language_name):
        if language_name in cls.Languages:
            language = cls(language_name)
            print(f"Recognized language: {language.name}")
            print(f"Field of implementation: {cls.Languages[language.name]['Field']}")
            print(f"Grammar: {cls.Grammar}")
            print(f"Recognizing Automaton: {cls.Languages[language.name]['Recognizing_Automaton']}")
            print(f"Production Rules (Constraints): {cls.Languages[language.name]['Production_rules']}")
            print(f"Examples using {language.name}:")
            for example in cls.Languages[language.name]['Examples']:
                print(f"- {example}")
        else:
            print("Language not recognized.")

def recognize_programming_language():
    print("Welcome to the Programming Language Recognition System!")
    print("This system can provide information about various programming languages.")
    print("Here are the available languages:")
    print(list(Language.Languages.keys()))
    
    while True:
        language_name = input("Enter the name of a programming language or 'exit' to quit: ")
        if language_name.lower() == "exit":
            print("Thank you for using the Programming Language Recognition System. Goodbye!")
            break
        else:
            Language.recognize(language_name)
            print()

# Example usage:
recognize_programming_language()
In [1]:
#readwriteappendgrades.py

import math

class Class:
  def __init__(self, subject, grades):
    self.subject = subject
    self.grades = grades

def main():
  # Create an empty list to store the subjects.
  subjects = []

  # Read the grades from the file.
  with open("grades.txt", "r") as f:
    grades = f.readlines()

  # Print the menu.
  print("Welcome to your Grade Calculator")
  print("1. New Entry")
  print("2. Highest Course Average")
  print("3. Lowest Course Average")
  print("4. Calculate your Average")
  print("5. Exit")

  # Get the user's choice.
  choice = int(input("Enter your choice: "))

  # Process the user's choice.
  while choice != 5:
    if choice == 1:
      # Add a new class.
      subject = input("Enter the name of the new subject: ")
      subjects.append([])
      for i in range(5):
        grade = float(input("Enter the grade for {}: ".format(subject)))
        subjects[-1].append(grade)
      with open("grades.txt", "a") as f:
        f.write("{}: {}\n".format(subject, subjects[-1]))
    elif choice == 2:
      # Find the class with the highest average grade.
      max_sort = -1
      max_avg_grade = -1.0
      for i in range(len(subjects)):
        sum = 0.0
        for j in range(len(subjects[i])):
          sum += subjects[i][j]
        avg_grade = sum / len(subjects[i])
        if avg_grade > max_avg_grade:
          max_sort = i
          max_avg_grade = avg_grade
      if max_sort == -1:
        print("No classes found.")
      else:
        print("Class with highest average grade: " + subjects[max_sort])
    elif choice == 3:
      # Find the class with the lowest average grade.
      min_sort = -1
      min_avg_grade = 101.0
      for i in range(len(subjects)):
        sum = 0.0
        for j in range(len(subjects[i])):
          sum += subjects[i][j]
        avg_grade = sum / len(subjects[i])
        if avg_grade < min_avg_grade:
          min_sort = i
          min_avg_grade = avg_grade
      if min_sort == -1:
        print("No classes found.")
      else:
        print("Class with lowest average grade: " + subjects[min_sort])
    elif choice == 4:
      # Calculate the average grades for each subject.
      for i in range(len(subjects)):
        sum_of_grades = sum(subjects[i])
        average_grade = sum_of_grades / len(subjects[i])
        print("The average grade for {} is {}".format(subjects[i], average_grade))
    else:
      print("Invalid choice.")

    print("Welcome to your Grade Calculator")
    print("1. New Entry")
    print("2. Highest Course Average")
    print("3. Lowest Course Average")
    print("4. Calculate your Average")
    print("5. Exit")

    # Get the user's choice.
    choice = int(input("Enter your choice: "))

if __name__ == "__main__":
  main()
In [ ]:
#syntax_cheatsheet(atomic).py

class MainMenu:
    def __init__(self):
        self.topics = {
            '1': ("\033[94mFormats", FormatMenu()),
            '2': ("\033[93mClasses", ClassMenu()),
            '3': ("\033[92mControl Flow", ControlFlowMenu()),
            '4': ("\033[95mIterators", IteratorMenu()),
            '5': ("\033[96mDecorators", DecoratorMenu()),
            '6': ("\033[93mFunctions", FunctionMenu()),
            '7': ("\033[94mList and Tuples", ListandTuplesMenu()),
            '8': ("\033[95mDictionaries\033[0m", DictionaryMenu()),
        }

    def display(self):
        print("\033[96m=== Main Menu ===\033[0m")
        for key, topic in self.topics.items():
            print(f"{key}. {topic[0]}")
        print("0. Exit")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '0':
                print("Goodbye!")
                break

            if choice in self.topics:
                sub_menu = self.topics[choice][1]
                sub_menu.run()


class SubMenu:
    def __init__(self, examples):
        self.examples = examples

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. {example}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                print("Running example:", self.examples[int(choice) - 1])
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")


class FormatMenu(SubMenu):
    def __init__(self):
        examples = [
            '''name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)  # Output: "My name is Alice and I am 25 years old."''',

            '''pi = 3.14159
message = "The value of pi is approximately {:.2f}".format(pi)
print(message)  # Output: "The value of pi is approximately 3.14"''',

            '''from string import Template

name = "Bob"
age = 30
template = Template("$name is $age years old.")
message = template.substitute(name=name, age=age)
print(message)  # Output: "Bob is 30 years old."'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")


class ClassMenu(SubMenu):
    def __init__(self):
        examples = [
            '''class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

    def __str__(self):
        return f"Rectangle: length={self.length}, width={self.width}"''',

            '''class Student:
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major
        self.grades = []

    def add_grade(self, grade):
        self.grades.append(grade)

    def average_grade(self):
        if len(self.grades) == 0:
            return 0
        return sum(self.grades) / len(self.grades)

    def __str__(self):
        return f"Student: name={self.name}, age={self.age}, major={self.major}"''',

            '''class BankAccount:
    def __init__(self, account_number, balance=0):
        self.account_number = account_number
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds")
        else:
            self.balance -= amount

    def __str__(self):
        return f"Account: number={self.account_number}, balance={self.balance}"'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")



class ControlFlowMenu(SubMenu):
    def __init__(self):
        examples = [
            '''# Dynamic Formatting and If-Else Example
favorite_color = input("What is your favorite color? ")

if favorite_color.lower() == "blue":
    print(f"Oh, {favorite_color} is a calming and serene color!")
elif favorite_color.lower() == "red":
    print(f"{favorite_color} is a bold and energetic color!")
elif favorite_color.lower() == "green":
    print(f"{favorite_color} represents nature and growth!")
else:
    print(f"{favorite_color} is a great choice!")
''',

            '''# While Loop with User Input Example
total = 0

while True:
    number = int(input("Enter a number (enter 0 to stop): "))
    if number == 0:
        break  # Exit the loop if the user enters 0
    total += number

print(f"The sum of all numbers entered is: {total}")
''',

            '''# For Loop with Range and If-Else Example
for num in range(1, 11):
    if num % 2 == 0:
        print(f"{num} is even.")
    else:
        print(f"{num} is odd.")
'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")



class IteratorMenu(SubMenu):
    def __init__(self):
        examples = [
            '''# Using an Iterator with a List
fruits = ["apple", "banana", "orange"]

# Create an iterator from the list
fruit_iterator = iter(fruits)

# Iterate through the elements using a loop
for fruit in fruit_iterator:
    print(fruit)
''',

            '''# Creating a Custom Iterator
class SquaresIterator:
    def __init__(self, max_value):
        self.current = 0
        self.max_value = max_value

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.max_value:
            raise StopIteration
        square = self.current ** 2
        self.current += 1
        return square

# Create a custom iterator that generates squares up to 9
squares_iterator = SquaresIterator(3)

# Iterate through the squares
for square in squares_iterator:
    print(square)
''',

            '''# Using the built-in enumerate() function
fruits = ["apple", "banana", "orange"]

# Iterate through the list and get both index and value
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")

class DecoratorMenu(SubMenu):
    def __init__(self):
        examples = [
            '''# Simple Function Decorator
def greet():
    return "Hello!"

# Define a decorator function
def uppercase_decorator(func):
    def wrapper():
        original_result = func()
        modified_result = original_result.upper()
        return modified_result
    return wrapper

# Apply the decorator to the greet() function
greet = uppercase_decorator(greet)

# Call the decorated function
print(greet())  # Output: "HELLO!"
''',

            '''# Decorator with Arguments
def repeat(num_times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

# Apply the decorator with argument to the greet() function
@repeat(num_times=3)
def greet(name):
    return f"Hello, {name}!"

# Call the decorated function
print(greet("Alice"))
''',

            '''# Chaining Multiple Decorators
def uppercase_decorator(func):
    def wrapper():
        original_result = func()
        modified_result = original_result.upper()
        return modified_result
    return wrapper

def exclamation_decorator(func):
    def wrapper():
        original_result = func()
        modified_result = original_result + "!"
        return modified_result
    return wrapper

# Apply multiple decorators to the greet() function
@exclamation_decorator
@uppercase_decorator
def greet():
    return "hello"

# Call the decorated function
print(greet())  # Output: "HELLO!"
'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")

class FunctionMenu(SubMenu):
    def __init__(self):
        examples = [
            '''# Function with Default Parameters
def greet(name="Guest"):
    return f"Hello, {name}!"

# Call the function without arguments
print(greet())  # Output: "Hello, Guest!"

# Call the function with an argument
print(greet("Alice"))  # Output: "Hello, Alice!"
''',

            '''# Recursive Function
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

# Calculate factorial of 5
result = factorial(5)
print("Factorial of 5:", result)  # Output: 120
''',

            '''# Lambda Functions
# Define a lambda function to square a number
square = lambda x: x**2

# Use the lambda function
print(square(5))  # Output: 25

# Lambda function as an argument in a higher-order function
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]
''',

            '''# Example 4: Closure
def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

# Create closures with different values of x
closure1 = outer_function(10)
closure2 = outer_function(20)

print(closure1(5))  # Output: 15
print(closure2(5))  # Output: 25
'''
        ]
        super().__init__(examples)
    
    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")


class ListandTuplesMenu(SubMenu):
    def __init__(self):
        examples = [
            '''#  List Comprehension
# Generate a list of even numbers from 1 to 10
even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10]''',

            '''# Tuple Unpacking
# Define a tuple
person = ('John', 30, 'Engineer')

# Unpack the tuple into variables
name, age, profession = person

print(f"Name: {name}")
print(f"Age: {age}")
print(f"Profession: {profession}")
''',

            '''#  List Concatenation and Slicing
# Create two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Concatenate the two lists
concatenated_list = list1 + list2
print(concatenated_list)  # Output: [1, 2, 3, 4, 5, 6]

# Get a sublist using slicing
sublist = concatenated_list[2:5]
print(sublist)  # Output: [3, 4, 5]
'''
        ]
        super().__init__(examples)
        
    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")



class DictionaryMenu(SubMenu):
    def __init__(self):
        examples = [
            '''# Example 1: Creating a Dictionary
# Using curly braces and key-value pairs
person = {
    'name': 'John',
    'age': 30,
    'occupation': 'Engineer'
}

# Using dict() constructor with keyword arguments
person = dict(name='John', age=30, occupation='Engineer')

print(person)  # Output: {'name': 'John', 'age': 30, 'occupation': 'Engineer'}
''',

            '''# Example 2: Dictionary Comprehension
# Create a dictionary of squares from 1 to 5
squares = {num: num**2 for num in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
''',

            '''# Example 3: Merging Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Using the update() method
merged_dict = dict1.copy()
merged_dict.update(dict2)
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Using dictionary unpacking in Python 3.9+
merged_dict = {**dict1, **dict2}
print(merged_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
''',

            '''# Example 4: Iterating Over a Dictionary
person = {
    'name': 'John',
    'age': 30,
    'occupation': 'Engineer'
}

# Iterate over keys
print("Keys:")
for key in person:
    print(key)

# Iterate over values
print("\nValues:")
for value in person.values():
    print(value)

# Iterate over key-value pairs
print("\nKey-Value Pairs:")
for key, value in person.items():
    print(key, ":", value)
'''
        ]
        super().__init__(examples)

    def display(self):
        print("=== Sub Menu ===")
        for i, example in enumerate(self.examples, 1):
            print(f"{i}. Example {i}")
        print("-1. Back")

    def run(self):
        while True:
            self.display()
            choice = input("Enter your choice: ")

            if choice == '-1':
                break

            if choice.isdigit() and int(choice) <= len(self.examples):
                example_code = self.examples[int(choice) - 1]
                print(f"Running Example {int(choice)}:")
                print(example_code)
                exec(example_code)
                input("Press Enter to continue...")
            else:
                print("Invalid choice!")

if __name__ == '__main__':
    main_menu = MainMenu()
    main_menu.run()
In [ ]:
#taskprogram.py

import os

class Task:
    def __init__(self, id, category, description, completed):
        self.id = id
        self.category = category
        self.description = description
        self.completed = completed

def add_task(tasks):
    task_id = len(tasks) + 1
    print("Categories:")
    print("1. Home")
    print("2. School")
    print("3. Personal")
    print("4. Payments")
    print("5. Other")
    category_choice = int(input("Enter the category number: "))
    category_map = {
        1: "Home",
        2: "School",
        3: "Personal",
        4: "Payments",
        5: "Other"
    }
    category = category_map.get(category_choice, "Other")
    description = input("Enter task description: ")
    completed = False
    task = Task(task_id, category, description, completed)
    tasks.append(task)
    print("Task added successfully!")

    # Write the task to the output file
    with open("tasks.txt", "a") as file:
        file.write(f"{task.id}\n")
        file.write(f"{task.category}\n")
        file.write(f"{task.description}\n")
        file.write(f"{task.completed}\n")

def display_tasks(tasks):
    if not tasks:
        print("No tasks found.")
        return

    print("Tasks:")
    for task in tasks:
        print("ID:", task.id)
        print("Category:", task.category)
        print("Description:", task.description)
        print("Status:", "Completed" if task.completed else "Incomplete")
        print()

def load_tasks_from_file():
    tasks = []
    if os.path.exists("tasks.txt"):
        with open("tasks.txt", "r") as file:
            lines = file.readlines()
            for i in range(0, len(lines), 4):
                task_id = int(lines[i].strip())
                category = lines[i + 1].strip()
                description = lines[i + 2].strip()
                completed = lines[i + 3].strip() == "True"
                task = Task(task_id, category, description, completed)
                tasks.append(task)
    else:
        print("No tasks file found. Creating a new one.")

    return tasks

def mark_task_complete(tasks):
    if not tasks:
        print("No tasks found.")
        return

    task_id = int(input("Choose a task to mark as complete (Enter the ID): "))

    for task in tasks:
        if task.id == task_id:
            task.completed = True
            print("Task marked as complete!")

            # Update the task completion status in the output file
            with open("tasks.txt", "w") as file:
                for t in tasks:
                    file.write(f"{t.id}\n")
                    file.write(f"{t.category}\n")
                    file.write(f"{t.description}\n")
                    file.write(f"{t.completed}\n")
            return

    print("Invalid task ID.")

def delete_task(tasks):
    if not tasks:
        print("No tasks found.")
        return

    task_id = int(input("Choose a task to delete (Enter the ID): "))

    for task in tasks:
        if task.id == task_id:
            tasks.remove(task)
            print("Task deleted successfully!")

            # Update the tasks in the output file
            with open("tasks.txt", "w") as file:
                for t in tasks:
                    file.write(f"{t.id}\n")
                    file.write(f"{t.category}\n")
                    file.write(f"{t.description}\n")
                    file.write(f"{t.completed}\n")

            return

    print("Invalid task ID.")

def main():
    tasks = load_tasks_from_file()

    while True:
        print("Task Management System")
        print("1. Add Task")
        print("2. Display Tasks")
        print("3. Mark Task as Complete")
        print("4. Delete Task")
        print("5. Exit")
        choice = input("Choose an option: ")

        if choice == "1":
            add_task(tasks)
        elif choice == "2":
            display_tasks(tasks)
        elif choice == "3":
            mark_task_complete(tasks)
        elif choice == "4":
            delete_task(tasks)
        elif choice == "5":
            print("Exiting...")
            break
        else:
            print("Invalid choice.")

        print()

if __name__ == "__main__":
    main()
In [ ]:
#treasure_hunt.py

import os
import pickle

# Define a simple Item class
class Item:
    def __init__(self, name, description):
        self.name = name
        self.description = description

# Define locations and items
locations = {
    "forest": {
        "description": "You find yourself in a dense forest. There is a hidden treasure somewhere.",
        "items": [Item("sword", "A shiny sword"), Item("key", "A rusty key")],
        "color": "\033[92m"  # Green
    },
    "cave": {
        "description": "You enter a dark cave. It's too dark to see anything.",
        "items": [Item("torch", "A flickering torch"), Item("gem", "A precious gem")],
        "color": "\033[93m"  # Brown
    },
    "river": {
        "description": "You reach a fast-flowing river. There's a bridge across it.",
        "items": [Item("map", "A torn map"), Item("food", "Some dried fruits")],
        "color": "\033[94m"  # Blue
    }
}

# Function to display player inventory
def display_inventory(inventory):
    print("\nYour Inventory:")
    if not inventory:
        print("\033[91m" + "Empty" + "\033[0m")  # Red
    else:
        for item in inventory:
            print("\033[92m" + f"- {item.name}: {item.description}" + "\033[0m")  # Green

# Function to save game data to a file using pickle
def save_game(player_location, player_inventory):
    game_data = {"location": player_location, "inventory": player_inventory}
    with open("save_game.dat", "wb") as file:
        pickle.dump(game_data, file)

# Function to load game data from a file using pickle
def load_game():
    if os.path.exists("save_game.dat"):
        with open("save_game.dat", "rb") as file:
            return pickle.load(file)
    return None

# Main game loop
def play_game():
    player_inventory = []
    game_data = load_game()
    if game_data:
        player_location = game_data["location"]
        player_inventory = game_data["inventory"]
        print("Welcome back! You continue your adventure.")
    else:
        player_location = "forest"
        print("Welcome to the Adventure Game!")

    while True:
        location_info = locations[player_location]
        print(location_info["color"] + "\nCurrent Location:", player_location.capitalize() + "\033[0m")
        print(location_info["color"] + locations[player_location]["description"] + "\033[0m")
        display_inventory(player_inventory)

        action = input("What do you want to do? (explore/move/take/quit): ").lower()

        if action == "quit":
            save_game(player_location, player_inventory)
            print("\033[1m\033[95mYour progress has been saved. Goodbye!\033[0m")
            break
        elif action == "explore":
            print("You search the area but find nothing of interest.")
        elif action == "move":
            new_location = input("Where do you want to go? (forest/cave/river): ").lower()
            if new_location in locations:
                player_location = new_location
            else:
                print("\033[91m" + "Invalid location." + "\033[0m")  # Red
        elif action == "take":
            item_name = input("Which item do you want to take? (sword/key/torch/gem/map/food): ").lower()
            for item in locations[player_location]["items"]:
                if item.name == item_name:
                    player_inventory.append(item)
                    locations[player_location]["items"].remove(item)
                    print("\033[92m" + f"You have taken the {item_name}." + "\033[0m")  # Green
                    break
            else:
                print("\033[91m" + "Item not found." + "\033[0m")  # Red
        else:
            print("\033[91m" + "Invalid choice. Please enter a valid number." + "\033[0m")  # Red

if __name__ == "__main__":
    play_game()