Please help me clean up my function [closed] - python

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Here is my function's objective:
Define a procedure, find_last, that takes as input two strings, a
search string and a target string,and returns the last position in the
search string where the target string appears, or -1 if there are no
occurrences.
Here is a link to the question.
And here's my function so far:
def find_last(target, search):
find = target.find(search, 0)
if find != -1:
targets = target.find(search, find)
while targets != -1:
find = find + 1
targets = target.find(search, find)
return find - 1
else:
return -1
The code returns the answer I'm looking for with return find - 1, but I know there is a better way to go about doing this.
Any help would be greatly appreciated!

You basically implemented target.rfind(search).

Why dont you use rfind ?
>>> d = "ball foo ball"
>>> f = "ball"
>>> d.rfind(f)
12
So your method becomes a 1 liner :)
def find_last(target, search):
return target.rfind(search)
You can return target.rfind(search) and in the calling method check for -1 and handle appropriately.
Can't resist to quote this awesome piece from XKCD

Related

Compare one item of a dictionary to another item in a dictionary one by one [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Currently I'm working on an assignment where I have to compare an answer key(dictionary) to answers from students(dictionary). I have to count how many of the students answers match the answer key and return that value. I realize my current code is comparing one whole dictionary to the other and if they're all equal then it will return a value but if not it returns 0. I'm just not sure how to fix it so it returns the number of ones that match.
This is my current code. Here is the previous function forgot to add it.
def index_responses(responses):
results = {}
count = 1
for answer in responses:
"""
makes a dictionary containing the responses of the student
and mapping it to a key of Q" " depending on wht number question it is.
"""
results["Q" + str(count)] = answer[0]
count += 1
return results
Assuming the keys (here, prompt) of both dictionaries are the same, or at least for every key in the answers dictionary, there is a matching response prompt, then you can count them like so
count = 0
for prompt, response in responses.items():
if response == answers.get(prompt, None):
count += 1
return count

Python names in a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I'm kinda new to python and was given a problem as follows:
Given the list names , find the largest element in the list and swap it with the last element. For example, the list ["Carlton", "Quincy" "Adam", "Bernard"] would become ["Carlton", "Bernard", "Adam", "Quincy"] . Assume names is not empty
I thought about doing list Comprehension but I don't know how I would write that out in code
EDIT: Largest in this case would be the length of the string (sorry for not clarifying!!!))
names = [foo, fooooo, bar, baaar]
a, b = i.index(max(name, key=len)), -1
i[b], i[a] = i[a], i[b]
Courtesy of this.
If by largest, you mean longest, then you could iterate over the list to find the longest name, and then swap them.
maxLen = 0
maxI = 0
for i in range(0, len(names)):
if len(names[i]) > maxLen:
maxLen = len(names[i])
maxI = i
temp = names[-1]
names[-1] = names[maxI]
names[maxI] = temp
This is an overly convoluted way of doing it, but it's so drawn out to make it more obvious as to what's going on. With that said, you really should be more specific about what "largest" means.

How to count frequencys in python? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I had a file called 'words.txt' which contains things such as. #+=%£%= and i need to go through and count each symbol without allowing any duplicates and then print my answer. for example it should look like this when printed:
# : 1
+ : 1
= : 2
% : 2
£ : 1
I know I need to use a for loop in this and that I need to use a set so It doesnt't allow any duplicates but how would I do it? Thanl you
A set isn't so useful here as it doesn't have a place to store the counts
from collections import Counter
with open("words.txt") as fin:
c = Counter(fin.read())
for item in c.items():
print("{} : {}".format(*item))
Use python dictionary:
symbols = {}
for c in string:
if c not in symbols:
symbols[c] = 0
symbols[c] += 1
Look up dictionary.
Don't want to post more as it would only spoil the exercise.

Detect string repetition in python without regular expression [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I would like a function to detect string reputation, specifically
repetition("abcabcabc")
abc
repetition("aaaaaaa")
a
repetition("ababab")
ab
repetition("abcd")
abcd
I am thinking of doing it in a recursive way but I am confused
Thanks for any help in advance!
I am trying something like
def repetition(r):
if len(r) == 2:
if r[0] == r[1]:
return r[0]
half = len(r) / 2
repetition(r[:half])
if r[:half] == r[half:]:
return r[:half]
There probably is a better way to do this, but my first thought would be this:
def repetition(string):
substring = ''
for character in string:
substring += character
if len(string) % len(substring) == 0:
if (len(string) / len(substring)) * substring == string:
return substring
Using regular expressions:
import re
def repetitions(s):
r = re.compile(r"(.+?)\1+")
for match in r.finditer(s):
if len(match.group()) != len(s):
return s
return match.group(1)
Test:
repetitions("oblabla")
#output: "oblabla"
repetitions("blabla")
#output: "bla"

Python String Reverse Program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to write a program that will simply reverse a string. I get an error that something is not subscriptable or something. Could you guys help me pinpoint why this isn't working?
listreverse(list1):
rlist = []
i = len(list1) - 1
while i >= 0:
rlist.append(list[i])
i = i - 1
return rlist
rlist.append(list[i])
Should be
rlist.append(list1[i])
Right now you're trying to get the index i of the list function.
As #gnibbler points out, you should try to pick variable names that are descriptive and distinct enough that you aren't likely to make a typo like this or confuse one variable for another.
your code can be simplified to:
def string_reverse(string1):
return string1[::-1]
print string_reverse('hello')
it returns:
olleh
Note that your code, when takes a string, returns a list, not a string.
Here if you send a string you get the reversed string and if you send a list you get the reversed list
print string_reverse([1,2,3,4])
returns
[4, 3, 2, 1]
Change
rlist.append(list[i])
To
rlist.append(list1[i])
That will solve your problem..
There are lots of (other) ways to do that in Python:
>>> s = 'Hello World!'
# 1
>>> ''.join(reversed(s))
'!dlroW olleH'
# 2
>>> s[::-1]
'!dlroW olleH'
# 3
>>> r = ''
>>> for i in s:
r = i+r
>>> r
'!dlroW olleH'
# 4
>>> ''.join(list(s)[::-1])
'!dlroW olleH'
you can use this
str='qwerty'
print str[::-1] # it will reverse

Categories