#๐Ÿ”’ Codewars :3

41 messages ยท Page 1 of 1 (latest)

worthy summit
#
def find_needle(haystack):
    for i in range(len(haystack)):
        if haystack[i] == "needle":
            return f"found the needle at position {i}"```
would this be the ideal solution? i feel like it could be a lot better.
median basaltBOT
#

@worthy summit

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

terse trail
#

You'd need to show the full question.
I'd expect such a function to just return i.

worthy summit
terse trail
#

Oh, then it looks ok

icy escarp
#

that would be correct, this is actually a very good illustration of where hashing becomes relevant though

worthy summit
#

what is hashing?

icy escarp
#

hashing is what dictionaries use instead of indices

inland kayak
worthy summit
#

!d enumerate

median basaltBOT
#

enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__) method of the iterator returned by `enumerate()` returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*...
terse trail
#

Hashing is how dicts work.
You store values associated with keys.
To make lookup fast you distrubute the keys in a list, with the position of the key determined by a "hash" function. That way you can go to the specific list position directly from the key instead of searching linearly as your code does.

#

There are details, but that is the core.

icy escarp
#

if you were trying to find a literal needle in a haystack, hashed lookup would be the equivalent of telling you exactly where it's located

icy escarp
#

there is also the index() function, which will return the same figure as your function

#

!d index

median basaltBOT
#

A numeric value that represents the position of an element in a sequence.

In Python, indexing starts at zero. For example, things[0] names the first element of things; things[1] names the second one.

In some contexts, Python allows negative indexes for counting from the end of a sequence, and indexing using slices...

terse trail
worthy summit
#

im trying to use enumerate

icy escarp
#

forewarning though, normally when beginners are attempting to retrieve the index it's a misguided use of lists. The index is something you'd normally want to have readily available.

worthy summit
#

how do i return the enumerate object into something human readable?

icy escarp
#

list() works I think, or zip map dict()

worthy summit
#

oh nvm, i found out list works

worthy summit
#

oh, enumerate is cool too

#

!e```py
def find_needle(haystack):
hay = dict(enumerate(haystack))
for key, value in hay.items():
if value == "needle":
return f"found the needle at {key}"

print(find_needle(["short", "fire", "needle"]))

median basaltBOT
worthy summit
#

the for loop was better

#
def find_needle(haystack):
    return f'found the needle at position {haystack.index("needle")}'```

OH SO THATS HOW IT WORKS
inland kayak
worthy summit
inland kayak
#

!enumerate

median basaltBOT
#
The `enumerate` function

Ever find yourself in need of the current iteration number of your for loop? You should use enumerate! Using enumerate, you can turn code that looks like this:

index = 0
for item in my_list:
    print(f"{index}: {item}")
    index += 1

into beautiful, pythonic code:

for index, item in enumerate(my_list):
    print(f"{index}: {item}")

For more information, check out the official docs, or PEP 279.

worthy summit
#

oh

median basaltBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.