Jump to content

[PYTHON][HELP NEEDED!]Words in a string / list & using enumerate

Go to solution Solved by Nineshadow,
1 minute ago, CandleJakk said:

Yes, that's what I was looking for, sorry for not specifying.

This is what you're looking for?

def findAll(str,sub):
    str=str.split()
    v = [i+1 for i, x in enumerate(str) if x==sub]
    return v

 

Hi all, doing a project currently, it's only a function, where the user inputs a word, then inputs a string, and the function identifies all occurrences and the position of that word in a string (although it's actually converted to a list halfway through). The code I have currently is only identifying the first occurrence of the word, and none further. It also doesn't identify the word if the word is the first word in the string, returning a blank "[ ]". It will also say the word's actual position - 1 as the first word is counted as zero. I have attempted to curb this problem in two ways, the first of which doing a "aString.insert(0, ' ')", the second of which doing "for i in __: if i == int: i += 1". Neither of these work. Also, when doing the .insert, I tried putting a character in the space instead of, well, a space (as this part doesn't get printed anyway), but that didn't work.

So yes, any help is appreciated! Here is the code:

def wordlocator(word):
    yourWord = word
    print("You have chosen the following word: " +yourWord)
    aString = input("What string would you like to search for the given word?")
    aString = aString.lower()
    aString = aString.split()
    b = [(i, j) for i, j in enumerate(aString)]
    c = [(i, x) for i, x in b if x == yourWord]
    return c

edit: got it working now, thanks for your help all! :)

Link to post
Share on other sites

  1. What is the pseudo-code/English for the algorithm you're using? Do you understand the algorithm?
  2. Why do you have variables named things like "b" and "c"?
  3. Why are you storing word in yourWord if you are not modifying yourWord later in the function?
  4. Why are you not accepting the string as an input to the function and instead violating single responsibility by printing a message and accepting input?
  5. Why are you using i and j in one loop and i and x in the other?
Link to post
Share on other sites

2 minutes ago, SSL said:
  1. snip

hi, thanks for responding! I will try to answer all these questions

1) this isn't pseudo code, it's meant to be used. as for the algorithm, i've been learning code on codecademy but didn't understand how to use enumerate properly so started out on this

2) i named them that so i didn't have to type long things all the time

3) honestly i don't know

4) ?!?!

5) i was getting confused between them so i used x in the next

Link to post
Share on other sites

1 minute ago, CandleJakk said:

hi, thanks for responding! I will try to answer all these questions

1) this isn't pseudo code, it's meant to be used. as for the algorithm, i've been learning code on codecademy but didn't understand how to use enumerate properly so started out on this

2) i named them that so i didn't have to type long things all the time

3) honestly i don't know

4) ?!?!

5) i was getting confused between them so i used x in the next

 

Please re-read and answer my first question. I can't help you unless I know either that you understand the algorithm, or else what you don't understand about it so I can help with it.

Link to post
Share on other sites

Just now, SSL said:

 

Please re-read and answer my first question. I can't help you unless I know either that you understand the algorithm, or else what you don't understand about it so I can help with it.

i'm gonna go with i don't understand the algorithm! please explain it for me, i'm new to coding (only been doing it maybe 3 or 4 months?)!

Link to post
Share on other sites

Uh...

def findAll(str,sub):
    v = []
    i = str.find(s)
    while(i>0):
        v.append(i)
        i=str.find(sub,i+1)
    return v
str = input()
sub = input()
t = findAll(str,sub)
for i in t:
    print(i)

?

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

1 minute ago, CandleJakk said:

i'm gonna go with i don't understand the algorithm! please explain it for me, i'm new to coding (only been doing it maybe 3 or 4 months?)!

 

Well I don't have code academy in front of me, so I'll have to guess.

 

It looks like the goal here is that enumerate takes a sequence and assigns a cardinality (ordered value) to each item. That's your first loop, which could be simplified by wrapping enumerate in "list()".

 

The second loop then needs to iterate over the results of the first loop and count how many times it encounters the word, and what the cardinality of the word is when it encounters it. You need one variable that gets incremented by one each time you encounter the word, and a second variable that is an array, to which you assign the cardinality of the word when it is found.

 

3 minutes ago, Nineshadow said:

Uh...


str = ''
def findAll(s):
    v = []
    x = str.find(s)
    while(x>0):
        v.append(x)
        x=str.find(s,x+1)
    return v
str = input()
t = findAll(input())
for i in t:
    print(i)

?

 

I suspect that this doesn't answer the question in the way the OP needs.

Link to post
Share on other sites

You can compact

b = [(i, j) for i, j in enumerate(aString)]
c = [(i, x) for i, x in b if x == yourWord]

into:

b = [(i, j) for i, j in enumerate(aString) if j == yourWord]

 

Desktop: Intel i9-10850K (R9 3900X died 😢 )| MSI Z490 Tomahawk | RTX 2080 (borrowed from work) - MSI GTX 1080 | 64GB 3600MHz CL16 memory | Corsair H100i (NF-F12 fans) | Samsung 970 EVO 512GB | Intel 665p 2TB | Samsung 830 256GB| 3TB HDD | Corsair 450D | Corsair RM550x | MG279Q

Laptop: Surface Pro 7 (i5, 16GB RAM, 256GB SSD)

Console: PlayStation 4 Pro

Link to post
Share on other sites

Just now, SSL said:

 

I suspect that this doesn't answer the question in the way the OP needs.

Yes, thank you for providing a solution (I think? haven't checked) but I don't really understand the code. Also, I am currently reading what you said SSL, and thanks for the detailed reply!

 

Link to post
Share on other sites

2 minutes ago, CandleJakk said:

Yes, thank you for providing a solution (I think? haven't checked) but I don't really understand the code. Also, I am currently reading what you said SSL, and thanks for the detailed reply!

 

 

Have you looked at the python documentation for the things you are trying to do (like enumerate)? That would be helpful, if not.

Link to post
Share on other sites

3 minutes ago, mathijs727 said:

You can compact


b = [(i, j) for i, j in enumerate(aString)]
c = [(i, x) for i, x in b if x == yourWord]

into:


b = [(i, j) for i, j in enumerate(aString) if j == yourWord]

 

Oh, thanks fr the advice!

Link to post
Share on other sites

1 minute ago, SSL said:

 

Have you looked at the python documentation for the things you are trying to do (like enumerate)? That would be helpful, if not.

I looked on the python wiki, but their way of explaining it didn't really help, at least not for me. 

Link to post
Share on other sites

1 minute ago, CandleJakk said:

Yes, thank you for providing a solution (I think? haven't checked) but I don't really understand the code. Also, I am currently reading what you said SSL, and thanks for the detailed reply!

 

Python has a built-in function find(). Taken from the documentation :
 

Quote
string.find(s, sub[, start[, end]]):

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

You can easily use it to find the first occurrence of a substring in a string. To find all occurrences, you must simply tell it to search for the substring after the index of the previous occurrence. Do this in a loop until you can't find the substring anymore (ie find() returns -1).

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

1 minute ago, Nineshadow said:

Python has a built-in function find(). Taken from the documentation :
 

You can easily use it to find the first occurrence of a substring in a string. To find all occurrences, you must simply tell it to search for the substring after the index of the previous occurrence. Do this in a loop until you can't find the substring anymore (ie find() returns -1).

I may have been doing it wrong, but when I used .find() before, then it would find the first occurrence of the first character of the word the user input, not the first occurrence of the word itself.

Link to post
Share on other sites

3 minutes ago, CandleJakk said:

I may have been doing it wrong, but when I used .find() before, then it would find the first occurrence of the first character of the word the user input, not the first occurrence of the word itself.

Oh, you want the first occurrence in terms of words?

Like, for finding 'word' in 'Hello there world', it would be 3?

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

1 minute ago, SSL said:

 

I thought you wanted the count of word in the string, and all positions?

Ok, to clarify; lets say the user inputs this...

wordlocator("hey")
what string do you want? "hi hey hello hey hello"
(2, hey), (4, hey)

Thanks for your help both

Link to post
Share on other sites

1 minute ago, CandleJakk said:

Yes, that's what I was looking for, sorry for not specifying.

This is what you're looking for?

def findAll(str,sub):
    str=str.split()
    v = [i+1 for i, x in enumerate(str) if x==sub]
    return v

 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×