Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Function Help
#1
Hello all. I am new to Python and struggling with an assignment. Here is one of the problems below. I would appreciate any help as I am lost on how to approach it or what code to write. Thank you.

Problem 8: Write a function called includes which accepts a collection, a value,
and an optional starting index. The function should return True if the value exists
in the collection when we search starting from the starting index. Otherwise, it
should return False.
The collection can be a string, a list, or a dictionary.
If the collection is a string, the third parameter is a starting index for where to
search from.
If the collection is a dictionary, the function searches for the value among values
in the dictionary; since objects have no sort order, the third parameter is ignored


Test cases:
includes([1, 2, 3], 1) # True
includes([1, 2, 3], 1, 2) # False
includes({ 'a': 1, 'b': 2 }, 1) # True
includes({ 'a': 1, 'b': 2 }, 'a') # False
includes('abcd', 'b') # True
includes('abcd', 'e') # False
Reply
#2
There are a few parts to this problem:

Define a function that takes a parameter and returns something
def sum_of_list(list_input):
    sum = 0
    for value in list_input:
        sum += value
    return value
Determine if a collection is a dictionary
if type(collection_input) == dict:
    print("It's a dictionary")
Sequentially search a list or string
found = False
for index in range(0, len(collection_input)):
    if collection_input[index] == query:
        found = True
        break
There's a good bit more to it, but those should get you started.
Reply
#3
Someone wrote an answer to your question that you may have already seen, but I've deleted it because the point of this forum isn't to do others homework. If you still need help, you should provide an attempt and ask as specific a question as possible, and we'd be happy to help.

EDIT: I've undeleted the post in question after reviewing it and realizing I was wrong. It's actually a good example of a good answer - it has all the parts, helping the OP, but leaves them the work of putting it together. My apologies to Clunk_Head. Also, I've added +1 repo, though I realize that doesn't make up for the stress of being told your good deed was bad.
Reply
#4
"I would appreciate any help as I am lost on how to approach it"

Well, do you know what all the words mean? List, function, index, dictionary, index... It's a language. Maybe focus on vocabulary and practice like you would if learning any other language.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020