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.
Related
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 1 year ago.
Improve this question
I tried these, but its only for one column.
using notepad++ and python. Any solution that can do for multiple columns of text?
# Input:
tim
oso
d n
a d
y a
y
# Output:
today
is
monday
You can do this fairly easily with a loop, something like:
s = "tim\noso\nd n\na d\ny a\n y"
bits = s.split('\n')
lines = ['' for i in range(0, len(bits[0]))]
for bit in bits:
for i in range(0, len(bit)):
if bit[i] != ' ':
lines[i] += bit[i]
'\n'.join(lines)
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 3 years ago.
Improve this question
Essentially I want to put characters inside a list so I can make the for loop work.
Example characters (supposedly listed individually vertically. not like this showing as one line)
N/A
N/A
None
Test
Dev
I want to put these characters into a list like below
a = [N/A, N/A, None, Test, Dev]
Reason is when I use for loop into these characters (let's say there are all inside "test_report". For loop is not working because it is reading the "test_report" as like this:
N
/
A
N
/
A
N
o
n
e
count = 0
for i in test_report:
if i == "Test":
count += 1
return count
Try this...
with open('test_report.txt', 'r') as f:
test_arr = f.read().split()
print(test_arr)
Considered your test_report.txt like this...
N/A
N/A
None
Test
Dev
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
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 4 years ago.
Improve this question
My dataset looks like following. I am trying to read numbers in "per" column without reading "%" symbol.Being a beginner in python,I was wondering if we can do such in python. Also, if you could provide the explanation that will be great!
State Year per
A 1990 6.10%
A 1989 4.50%
B 1990 3.4%
B 1989 1.25%
Thanks in advance,
In case it is a csv file, this should help (or there might be another way to get a dataframe):
import pandas as pd
data = pd.read_csv("somefile.csv")
data["per"] = data["per"].str.replace("%", "").to_numeric()
Your file type doesn't matter for this and no modules required. It works by taking each row and going to the last word. Then it splits the percentage and removes the percent symbol.
def readFile(filename):
percents = []
with open (filename,"r") as f:
for row in f:#for each line, we remove the first one late
splitRow = row.split()[-1]# spliting the elements by word, we want the last one only
percent = splitRow
percent = percent.split("%")[0]#removing the percent
percents.append(percent)#if you want it as an number instead of a string do percents.append(float(percent))
percents = percents[1:] # removes the header "per"
return percents
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