r/pythonhelp • • Feb 19 '23

Having trouble installing Xformers for AI Diffusion

2 Upvotes

I was planning to install Xformers for Automatic 1111.

But whenever I put pip installer on program.

pip install xformers==0.0.16rc425

I get error

C:\Users\Chris>pip install xformers==0.0.16rc425

Fatal error in launcher: Unable to create process using '"C:\Users\Chris\AppData\Local\Programs\Python\Python39\python.exe" "C:\Users\Chris\AppData\Local\Programs\Python\Python39\Scripts\pip.exe" install xformers==0.0.16rc425': The system cannot find the file specified.


r/pythonhelp • • Feb 13 '23

which encoding system/machanism is used in python binary read?

2 Upvotes

I need to read file in binary format-->

 with open("tex.pdf", mode='br') as file:  
fileContent = file.read()
for i in fileContent:
    print(i,end=" ")

so this provide decimal integers which i think it in ascii format but ascii values only have 0-127

and this output display integers greater that 127 (like 225 108 180 193)

Can someone tell me what encoding/machanism used?


r/pythonhelp • • Feb 02 '23

having trouble with this code

2 Upvotes

planets = {
"mercury": 5429,
"venus": 5243,
"earth": 5514,
"mars": 3934,
"jupiter": 1326,
"saturn": 687,
"uranus": 1270,
"neptune": 1638
}
planet_name = input('Enter the name of a planet:')
if planet_name in planets:
print("this planet has a density of:" planets[planet_name])
else:
print("unrecognised planet")


r/pythonhelp • • Jan 30 '23

Loop feature to ask the user to enter the file name until they press "n".

2 Upvotes

Hello I need help with a python project. I have been asked to create a feature that would allow the user to enter a file name and prompt an error message if the file cannot be opened. The process should continue to as ask for a valid file name until the file can be opened or the user types "n". Yet I am not sure where to implement the loop.

So far I came up with this:

def open_file(self):
try:
fname = input("Enter a filename for network data: ")
with open(fname, 'r') as f:
num_members = int(f.readline().strip())
for line in f:
member, friend = line.strip().split()
if member in network:
network[member].append(friend)
else:
network[member] = [friend]

except IOError:
print("File does not exist.")
return False
return True

Yet I am not sure where to implement the loop so that when the file does not exist the user must be prompted to enter the file again until they press "n".

Any help would be much appreciated. :)


r/pythonhelp • • Jan 06 '23

SOLVED Access Database: Script that works when manually run is failing in MS Task Scheduler

2 Upvotes

SOLVED - See my comment below (2023-01-20 UPDATE).

Hey all,

Hoping someone has insight into what is going on with the issue I'm facing.

Problem

I have a Python script that exports a report from an Access Database to a PDF file. The script itself works fine when run manually, however when that same exact script is added to Task Scheduler (either via Python file or batch file), the script fails due to the following error:

(-2147352567, 'Exception occurred.', (0, None, "Contact Management Database can't save the output data to the file you've selected.", None, -1, -2146825986), None)

I don't understand why I can run the script manually and have it work as expected, but when running via Task Scheduler, it gives me that error.

Script

import win32com.client
from pathlib import Path
from UtilityBelt import write

access_db_path = Path(r'<Access Database Path>')

report_name = r'<Name of Report in Access>'

report_output = Path(r'<Export folder>\test.pdf')

if report_output.exists():
    # Deletes existing report if applicable
    report_output.unlink()

try:
    a = win32com.client.gencache.EnsureDispatch("Access.Application")

    # Open the database
    db = a.OpenCurrentDatabase(access_db_path)

    # Exports the selected report to a PDF
    a.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)', str(report_output))

    a.Application.Quit()

except Exception as e:
    write(logfile, str(e))

Relevant Task Scheduler Settings

General

Run whether user is logged in or not

Run with highest privileges

Actions

Program/script

<path to folder>\access_testing.bat

Start in (optional)

<path to folder>

Batch File

@echo off
"<path to python folder>\python.exe" "<path to folder>\access_testing.py"
pause

I've tried creating a brand new test access database, logging out then back in, restarting the computer, running in Task Scheduler via Python and Batch, playing with the action parameters, exporting to a local drive as opposed to a network drive, exporting a different file type, running with a different user, ... No luck with anything I've tried.

Any help would be very much appreciated.

Thanks all


r/pythonhelp • • Dec 20 '22

Stealth Port Scanner with Scapy and Python

2 Upvotes

I am doing a college assignment right now and am writing code in python to build a "Stealth Port Scanner with Scapy and Python". This is quite difficult for me so I am hoping for help. I did 11/41 subsections, but I think I messed up somewhere. What should I do differently? Below I send the code and a link of tasks: https://ibb.co/1dYk970

target = input("Adres IP: ")
Registered_Ports = range(1023)

open_ports = []

def scanport(port):
port = RandShort()
conf.verb = 0
SYNACKpkt = sr1(IP(dst=target) / TCP(sport=srcport, dport=port, flags="S", timeout=0.5))
flags = SYNACKpkt.getlayer(TCP).flags
if flags == SYNACKpkt:
return True
else:
return False
SynPkt1 = IP() / TCP()
SynPkt1.haslayer(TCP)
1
SynPkt2 = IP() / UDP()
SynPkt2.haslayer(TCP)
0


r/pythonhelp • • Dec 09 '22

Problem with understanding lists/arrays and creating a list from another list...

2 Upvotes

Hi this semester I enrolled in a computer science class and I am confused on this code. I was assigned to create a code that can create a 3x3 multidimensional list that takes the input of elements from the user. I then need to store all the "A" grades in a new list. I attempted to do so and keep getting an error stating "TypeError: '<=' not supported between instances of 'list' and 'int'. Just need help understanding what I am doing wrong. Thanks in advance. Here's my code for reference

R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
matrix = []
print("Enter the entries rowwise:")
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
print (matrix)
A_grades=[]
B_Grades=[]
C_Grades=[]

def grades_a(matrix):
for x in matrix:
if x <= 100 and x >= 90:
A_grades.append()
print(A_grades)

grades_a(matrix)


r/pythonhelp • • Dec 01 '22

how to pass multiple flags in argparse?

2 Upvotes

I have these lines of code and im trying to pass something like ScriptName.py --naruto --goku
but its giving error of unexpected arguments. when I pass only one, for example only --naruto, then its working fine. any help on how to pass multiple flags in python?

parser.add_argument('--naruto', action='store_true')

parser.add_argument('--transformers', action='store_true')

parser.add_argument('--goku', action='store_true')


r/pythonhelp • • Oct 16 '22

Store an output randomly printed from a list as a variable

2 Upvotes

So i'm trying the make a program that randomly prints out a series of random letters.

but my letter_combo in the user input shows only the last set from the original randomized version

 import random
list = ['AB','CD','GF','HD',]
for x in range(3):
    letter_combo = random.choice(list)
    print(letter_combo,end='') 
print('\t')
user_answr = input("Rewrite for " + str(letter_combo)+ ": ")
if user_answr == letter_combo:
        print("Good")
elif user_answr !=letter_combo:
    print("Wrong combination")

here's the output

ABCDGF
Rewrite for GF: 

every thing else seems fine. I just want to keep the whole initial line (ABCDGF) and have the user verify that it's correct, is there anyway to store it maybe?


r/pythonhelp • • Oct 12 '22

Unable to install MariaDB in Python docker container

2 Upvotes

Objective: I need to be able to access a MariaDB database on a remote server from my very simple app (local or in docker, whatever works easiest) so that I can run a couple of select queries on the data.

I've opted to use Docker because it's cleaner and less prone to interference from my local OS, but regardless, I've tried it on both and I get the same errors on both MacOS locally and Linux on Docker.

This is my Dockerfile (the app works fine until I try to add MariaDB):

FROM python:3.8

WORKDIR /usr/src/app

RUN apt-get update
RUN apt-get install libmariadb3 libmariadb-dev

COPY . .

RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 5000

CMD ["python", "./app.py"]

This is my requirements.txt (I don't need Flask but I just want to make sure I can see that pip is able to install something correctly, and it does):

Flask==2.0.2
mariadb==1.1.4

When I run a docker build, I get this:

RUN pip install --no-cache-dir -r requirements.txt:                                                                 
#11 1.253 Collecting Flask==2.0.2                                                                                            
#11 1.397   Downloading Flask-2.0.2-py3-none-any.whl (95 kB)                                                                 
#11 1.441      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 95.2/95.2 kB 4.7 MB/s eta 0:00:00                                    
#11 1.527 Collecting mariadb==1.1.4                                                                                          
#11 1.558   Downloading mariadb-1.1.4.zip (97 kB)
#11 1.568      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 97.4/97.4 kB 32.3 MB/s eta 0:00:00
#11 1.585   Preparing metadata (setup.py): started
#11 1.920   Preparing metadata (setup.py): finished with status 'error'
#11 1.930   error: subprocess-exited-with-error
#11 1.930   
#11 1.930   × python setup.py egg_info did not run successfully.
#11 1.930   │ exit code: 1
#11 1.930   ╰─> [8 lines of output]
#11 1.930       Traceback (most recent call last):
#11 1.930         File "<string>", line 2, in <module>
#11 1.930         File "<pip-setuptools-caller>", line 34, in <module>
#11 1.930         File "/tmp/pip-install-p7s8jj6d/mariadb_90e5111808594b418ebf9c5df54e9d58/setup.py", line 27, in <module>
#11 1.930           cfg = get_config(options)
#11 1.930         File "/tmp/pip-install-p7s8jj6d/mariadb_90e5111808594b418ebf9c5df54e9d58/mariadb_posix.py", line 64, in get_config
#11 1.930           print('MariaDB Connector/Python requires MariaDB Connector/C '
#11 1.930       TypeError: not enough arguments for format string
#11 1.930       [end of output]
#11 1.930   
#11 1.930   note: This error originates from a subprocess, and is likely not a problem with pip.
#11 1.933 error: metadata-generation-failed
#11 1.933 
#11 1.933 × Encountered error while generating package metadata.
#11 1.933 ╰─> See above for output.
#11 1.933 
#11 1.933 note: This is an issue with the package mentioned above, not pip.
#11 1.933 hint: See above for details.
------
executor failed running [/bin/sh -c pip install --no-cache-dir -r requirements.txt]: exit code: 1

Obviously something isn't right with my MariaDB Connector/C but I don't understand what.

I also tried the instructions listed on mariadb.com like this:

RUN apt install wget && \
wget https://downloads.mariadb.com/MariaDB/mariadb_repo_setup && \
echo "733cf126b03f73050e242102592658913d10829a5bf056ab77e7f864b3f8de1f  mariadb_repo_setup" sha256sum -c - && \
chmod +x mariadb_repo_setup && \
./mariadb_repo_setup --mariadb-server-version="mariadb-10.6"

but it doesn't work either, it goes to try to install and then trows the same error:

RUN pip install --no-cache-dir -r requirements.txt:                                                                 
#11 0.947 Collecting Flask==2.0.2                                                                                            
#11 1.068   Downloading Flask-2.0.2-py3-none-any.whl (95 kB)                                                                 
#11 1.115      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 95.2/95.2 kB 2.6 MB/s eta 0:00:00                                    
#11 1.199 Collecting mariadb==1.1.4                                                                                          
#11 1.255   Downloading mariadb-1.1.4.zip (97 kB)
#11 1.280      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 97.4/97.4 kB 5.0 MB/s eta 0:00:00
#11 1.295   Preparing metadata (setup.py): started
#11 1.598   Preparing metadata (setup.py): finished with status 'error'
#11 1.606   error: subprocess-exited-with-error
#11 1.606   
#11 1.606   × python setup.py egg_info did not run successfully.
#11 1.606   │ exit code: 1
#11 1.606   ╰─> [8 lines of output]
#11 1.606       Traceback (most recent call last):
#11 1.606         File "<string>", line 2, in <module>
#11 1.606         File "<pip-setuptools-caller>", line 34, in <module>
#11 1.606         File "/tmp/pip-install-w0d9j1a5/mariadb_874c8d3d5379442d9066ba64e29d96d1/setup.py", line 27, in <module>
#11 1.606           cfg = get_config(options)
#11 1.606         File "/tmp/pip-install-w0d9j1a5/mariadb_874c8d3d5379442d9066ba64e29d96d1/mariadb_posix.py", line 64, in get_config
#11 1.606           print('MariaDB Connector/Python requires MariaDB Connector/C '
#11 1.606       TypeError: not enough arguments for format string
#11 1.606       [end of output]
#11 1.606   
#11 1.606   note: This error originates from a subprocess, and is likely not a problem with pip.
#11 1.612 error: metadata-generation-failed
#11 1.612 
#11 1.612 × Encountered error while generating package metadata.
#11 1.612 ╰─> See above for output.
#11 1.612 
#11 1.612 note: This is an issue with the package mentioned above, not pip.
#11 1.612 hint: See above for details.
------
executor failed running [/bin/sh -c pip install --no-cache-dir -r requirements.txt]: exit code: 1

Any help would be very much appreciated.


r/pythonhelp • • Sep 16 '22

Am I understanding this process correctly?

2 Upvotes

Hello. I am going through a machine learning class online (just a series of videos, no instructors with feedback) and am trying to ensure I understand the process of building and using a model correctly.

The class has a project at the end in which I am to build a classifier. The goal of the project is to build a model that has a Recall score of at least 50%.

My approach is as follows:

* Clean / prep dataset
    * fix datatypes
	* remove unwanted columns
	* remove NA's


* For each type classifier I want to consider:
	* Build a pipeline:
	     * Scale Data 
	     * Use Feature Selection
	     * Classify

	     (e.g.):  

	     ```
		Pipeline([
			('Scale Data', StandardScaler()),
			('Select Features', SelectKBest(chi2, k=MY_COLS)),
			('Classify Data', LogisticRegression())
		])
	     ```  


(at this point, if I wanted to compare a NaiveBayes with a LogisticRegression, I have two pipelines, one with a NaiveBayes classifier and one with a LogisticRegression classifier)

* Tune hyperparameters of each model to find optimal version of each model:
    * I'm using GridSearch with scoring set to 'Recall'.  Since I did not split my dataset into Training/Test beforehand, I am using:

        StratifiedKFold for cross-validation


* Compare scores of each model's optimal parameters to decide which model is best


* Save optimal model for reuse later (e.g. in Pickle)

My questions are:

 1. Does this process seem correct?

 2. If doing this process manually without pipelines:  
     do I normalize labels as well as features (if for regression)?

 3. Once my model is fitted and saved, to use it on a new unlabelled dataset is it as simple as:  

     ```
      ## load trained model from pickle as model
      ## load unlabelled data as unlabelled_X
      predictions = model.predict(unlabelled_X)
     ```

 4.  If this is how I use the model, how can I be sure that it goes through the entire pipeline I created with the optimal model (e.g. scaling and feature selection prior to predicting)?  


 5.  Once time passes and the previously unlabelled data can be 'labeled', can I improve the model by training it with this new data using:
     model.fit(newly_labelled_X, newly_labelled_Y)

Any and all guidance and answers to my questions are greatly appreciated. Thank you in advance for your time and help.


r/pythonhelp • • Aug 22 '22

Topology sort open source

2 Upvotes

I need help with my project I am searching for an open source for an application that uses topology sort algorithm I tried searching in github but all I found was examples and not real applications Any suggestions?


r/pythonhelp • • Aug 17 '22

INACTIVE Is it possible to enable or disable the command prompt of a freezed programm ?

2 Upvotes

I'd like to be able to hide or to show the command prompt when needed. Indeed sometimes I need it for debugging, knowing what's going on. But when the software is on production I'd like to hide it. Is it even possible without making a new .exe via PyInstaller ?


r/pythonhelp • • Aug 16 '22

Need resources on how to do this

2 Upvotes

I want to fill in different parameters in a website and copy result data in excel. I want to carry 100s of such different calculations and copy data in excel and compare them. How do I approach this?

here are the steps:

fill in params

copy results

fill in new params

repeat


r/pythonhelp • • Aug 14 '22

Grab item from class without knowing what the item is?

2 Upvotes

I'm trying to make a system that requires picking an object from a class where the object depends on the players input. I tried something like this:

class items:
    class IronSword:
        name = "Iron sword"
        value = 20
        description = "whatever lololol"

c = IronSword
itemtheplayerpicksorwhatever = items.c.value

But this gives me an attribute error because c is not an item in the class. How could I do this?


r/pythonhelp • • Jul 24 '22

Save GMAIL Attachments (images) on the Linux Server

2 Upvotes

Hello,

i want to receive Emails (GMAIL) on my Server.

The Mails have Image-Attachments in it. The Attachments should be saved in my folder /var/www/mail/.

Now the clue:

I send image to the following email account using the gmail filter:

[email protected]

[email protected]

[email protected]

(its always the same account [email protected] but its "filtered" with the +food +flowers2 etc.)

The Script should save the files then in filtered-folders:

/var/www/mail/user1/image1.jpg

/var/www/mail/flowers2/image1.jpg

/var/www/mail/food/image1.jpg


r/pythonhelp • • Jul 03 '22

HOMEWORK Why won't this loop?

2 Upvotes

This is the beginning of a larger script, I need it to end early if the letter q is input.

theSum = 0.0
while True:
    name = input("Enter your name or press q to quit: ")
    if name =="":
        print("Thank you")
        break
    elif name == << q >>:
    	print("bye")
    	sys.exit()

r/pythonhelp • • May 31 '22

Why does it print 'none'?

2 Upvotes

Why does it print 'none' when I start my code?

import random options1 = 1 options2 = [ ["Move"], ["Pillage", "Move", "or Shop"], ["Loot", "Move", "or shop"] ] money = 0 move = 0 loot = [ "Drugs", "Jewels", "Money" ]

def moving(): random.shuffle(options2) if options2[0] == ["Loot", "Move", "or shop"]: ifmav = input(print("What would you like to do? \nWrite "LOOT" to loot nearby chests,\n"MOVE" to move,\nand "SHOP" to check our shop"))

if options1 == 1: options = input(print("What would you like to do?" " Write "MOVE" to move. ")) if options == "MOVE": move += 1 print("You chose to move!") moving()

def find_loot(): random.shuffle(loot) print(loot[0])


r/pythonhelp • • May 30 '22

SOLVED Ho to join two data frames no common fields?

2 Upvotes

I am getting AttributeError: 'NoneType' object has no attribute '_jdf' this is happening on the join of the two dataframes. I have tried merge and crossjoin but get errors as well, I need to use pyspark as the data sets are too large for Pandas and I get OOM, how would I join the two df's with no key is it possible to join on index as both dataframes will only have 1 row?

import os

from pyspark.sql.functions import col, approx_count_distinct, min, max, mean, stddev, stddev_samp, stddev_pop, kurtosis, skewness


def collect_col_stats(pqToRead):
    df = spark.read.parquet(pqToRead)
    fPath = os.path.dirname(pqToRead).split("/")
    table=(fPath[-1])
    runid= (fPath[-2:-1])
    col_max = len(df.columns)
    i=0

    schema = StructType([
        StructField('table', StringType()),
        StructField('run_id', StringType()),
        StructField('field', StringType()),
        StructField('pos', IntegerType())])

    while i < col_max:

        r = Row(table,runid[0],df.columns[i],i)
        rows=[r]
        dfDetail = spark.createDataFrame(rows,schema)
        dfData = ((df.select(approx_count_distinct(df.columns[i]), avg(df.columns[i]), kurtosis(df.columns[i]), \
        max(df.columns[i]),min(df.columns[i]), mean(df.columns[i]), skewness(df.columns[i]), \
        stddev(df.columns[i]), stddev_samp(df.columns[i]),stddev_pop(df.columns[i]), \
        sum(df.columns[i]), variance(df.columns[i]),var_samp(df.columns[i]),var_pop(df.columns[i])).show(truncate=False))

        )
        dfDetail.join(dfData)
        i+=1

dfDetail:

|table|file_id|field|pos|+-----------------------------+------------------+

|units|2022052|UNIT_ID|0| +-----------------------------+------------------+

dfData:

|approx_count_distinct(UNIT_ID)|avg(UNIT_ID) |kurtosis(UNIT_ID) |max(UNIT_ID)|min(UNIT_ID)|avg(UNIT_ID) |skewness(UNIT_ID) |stddev_samp(UNIT_ID) |stddev_samp(UNIT_ID) |stddev_pop(UNIT_ID) |sum(UNIT_ID) |var_samp(UNIT_ID) |var_samp(UNIT_ID) |var_pop(UNIT_ID) | +-----------------------------+------------------+

|409112784 |2.19160123798337E8|-1.228283702617958|99999999 |1 |2.19160123798337E8|-0.09214974984810387|1.2296924654679328E8|1.2296924654679328E8|1.229692464610742E8|1.57199283616453312E17|1.512143559628603E16|1.512143559628603E16|1.512143557520441E16| +-----------------------------+------------------+

What I want is this:

|table|file_id|field|pos|approx_count_distinct(UNIT_ID)|avg(UNIT_ID) |kurtosis(UNIT_ID) |...

|units|2022052|UNIT_ID|0|409112784 |2.19160123798337E8|-1.228283702617958|...


r/pythonhelp • • May 25 '22

random.sample throws a warning with the counts parameter

2 Upvotes

Hi,

I am using random.sample with the counts parameter in my code and PyCharm throws a warning : Expected type 'Iterable[str] | None' (matched generic type 'Iterable[_T] | None'), got 'list[int]' instead

The code itself works fine, but I am losing my mind trying to get rid of the warning. Why does it do that? Here is an example of the code:

from random import sample

a, b, c = sample(["A", "B"], counts=[1, 2], k=3)

print(a, b, c)

Results = B B A , A B B , B A B


r/pythonhelp • • May 20 '22

HOMEWORK Where am I making a mistake?

2 Upvotes
print("Please input your number")
num = int(input())
i = 2
final_amount = 0
while i ** 2 <= num:
    if num % i == 0:
        final_amount += i
        i += 1
    else:
        i += 1
if int(final_amount) == int(num):
    print(f"{num} is a perfect number!")
else:
    print(f"{num} is not a perfect number!")
print(final_amount)

A number is a perfect number if the sum of its divisors is equal to it. for example 6, 8128, 28, 496.

I'm just doing some random projects btw...


r/pythonhelp • • May 15 '22

HOMEWORK Installing a Github Python Project WITHOUT Internet connection (via PIP? )

2 Upvotes

Hi, I am a med student and currently working on a project that requires the installation of a Github Python Project. This is the link: https://github.com/MatthewBCooke/Pathfinder

I managed to install it to my personal machine with no problems (following installation instructions and installing via "pip install jsl-pathfinder").

Now I need to install the program on a machine that is NOT connected to the internet (due to safety concerns) and im struggling to do so as the PIP command only gives "connection errors" as it cant establish a connection to PIPY.

I am an absolute noob concerning python and therefore my question is how I can install the above mentioned Github .py on my machine without using PIP comand / without Internet connection.

Thanks in advance you guys for the help!

PS: If anybody cares the study is about the effects of THC for treatment of Alzheimers disease ;)


r/pythonhelp • • May 15 '22

HOMEWORK String not existing and added loop when not mean to be there

2 Upvotes

This code is meant to count the amount of Vowels and Consonants is a string and when I run it I get an error that string does not exist (I am not allowed to change the names of the functions) also when I did the get string part it looped twice for some reason and I do not know why, here is code:

def Main():
    Get_String_from_User()
    Count_Vowels(string)
    Count_Consonants(string)
    print(f'The string you entered includes {Count_Vowels} vowels and {Count_Consonants} consonants.')
def Get_String_from_User():
    string=input("Enter a string: ")
    return string
def Count_Vowels(string):
    vowels=0
    Vowels=set("aeiouAEIOU")
    for Letters in string:
        if Letters in Vowels and Letters.isalpha:
            vowels+=1
    return vowels
def Count_Consonants(string):
    consonants=0
    Vowels=set("aeiouAEIOU")
    for Letters in string:
        if Letters not in Vowels and Letters.isalpha:
            consonants+=1
Main()

r/pythonhelp • • May 14 '22

HOMEWORK Sentence into fitted matrix

2 Upvotes

Hey, I have a problem in a task I’ve been tried to handle with. The task goes like this: the user enters a sentences from maximum 9 words. And I need to convert the sentence into a matrix that the number of rows is as the number of words and the number of columns is 26 (as the alphabet a,b,c…).I guess you see where it’s going… I need to convert each letter that it will be in the index as the index of it in the alphabet. Example: “my name is alex” my - will be stored in row 0 And ‘m’ will be stored in column 12, etc… I’ve tried to handle with it in this way: first of all I’ve converted the sentences into a list of it self that each word will be stored as an object in the list (without spaces), second I’ve handled that all the letters will be set to Lower case. Btw if there is a word with the same latter a lot of times it will just add the index of it. But the main problem remains to convert the words into the given matrix, no matter what I’ve done tried to use 2d loops but it just doesn’t gives me the right answer. Help please 😭😭😭😭😭