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
I have a function generating random character [a-Z0-9] with whitespaces and appending each character to list:
words = []
while words.count(' ') < 10:
if len(words) == 0:
# append character
else:
if words[-1].isdigit(): # checking if last character is digit
# append only digit or whitespacce
else:
# append character
As you can see if last (previous) character was digit, I try to append digit or whitespace only, otherwhise append any character. The problem is, when I run the code I get error below:
'NoneType' object has no attribute 'isdigit' for line if words[-1].isdigit():. What I do wrong and why there is None instead of str?
Just make words string:
(It's biased towards chars, because whitespace is not digit, and hence it can turn to chars from digits, but not other way around- which is what you wanted, if I got you right)
import random
sample_digit=" 0123456789"
sample_char=" abcdefghi"
sample_any=sample_digit+sample_char
words = ""
while words.count(' ') <10:
if len(words) == 0:
words+=sample_any[random.randint(0, len(sample_any)-1)]
else:
if words[-1].isdigit():
words+=sample_digit[random.randint(0, len(sample_digit)-1)]
else:
words+=sample_char[random.randint(0, len(sample_char)-1)]
print(words)
A simple way of testing whether a character is a digit:
if words[-1] in '0123456789':
...
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 10 months ago.
Improve this question
I'm trying to write a simple program where it removes the previous letter when there exists a "/" after the character. Also, if there are two "//" after two characters, it should remove the last two characters. The number of / only exists if there a similar number of characters before so // in this scenario: aa//.
for example
x = 'abc/c/dd//a'
print x.rstrip('/')
it should return
aba
another example
x = '/aab//'
print x.rstrip('/')
should return
a
I have seen solutions trying the method above, but it doesn't seem to work for me. Is there an optimal solution for this?
A simple function can do this :
def stripStr(x, special_char="/"):
buff = ""
for char in x:
if char == special_char:
buff = buff[:-1]
else:
buff += char
return buff
assert stripStr('abc/c/dd//a') == 'aba'
assert stripStr('abc////cde/dd///a') == 'ca'
The idea is to reconstruct the string (in the buff variable) character after character. You simply need to keep appending each char except when you find a / then you have to remove the last char of the string.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
We tried to solve the following problem with friends but we couldn't come to a conclusion. How can we approach this question?
The full question is:
Even Words Problem: An even word is a word that contains an even number of copies of every letter. For example, the word "tattletale"
is an even word, since there are four copies of 't' and two copies of
'a,' 'e,' and 'l.' Similarly, "appeases" and arraigning" are even
words. However, "banana" is not an even word, because there is just
one 'b' and three copies of 'a.'
Write a function def isEvenWord(word) that accepts as input a string
representing a single word and returns whether or not that word is an
even word.
Your solution should be recursive and must not use any loops (e.g.
while, for). As a hint, this problem has a beautiful recursive
decomposition:
• The empty string is an even word, since it has 0 copies of every
letter.
• Otherwise, a word is an even word if there are at least two copies
of the first letter and the word formed by removing two copies of the
first letter is itself an even word.
For example, we can see that the word "appeases" is an even word using
the following logic:
"appeases" is an even word, because "ppeses" is an even word, because
"eses" is an even word, because "ss" is an even word, because "" is an
even word.
Screenshot of the problem description
I assume the tricky part is not using loop since this the solution must be recursive.
In this problem, you want to find whether the count of each letter can be divided by two.
Here are the steps you can follow:
1) Define your base condition
In this problem, the base condition is when there are no more letters in the word to check; in other words, your word is an empty string ''.
If the base condition is reached, it means that you have checked the count of all the letters in the word and the count was always even. So you can stop there. You've checked all the letters in the word and their count and they are even --> you return True and you are done.
2) Define what you do if the base condition is not reached:
In this problem, you need to check that the count of each letter in the word is even. You can store the letter in a variable and check its count in the word.
You must check the last letter each time, create a new word that doesn't contain the letter already checked, and run the isEvenWord(word) function again on the new word.
If when you check the count of the letter, it is not even, then you are done, you know that the word is not even since at least one letter in the word is not even so you return False.
If the count of the letter you are checking is even then you continue the check the next letter by calling your function again on the new word made of the remaining letters that you haven't checked yet.
Here is the code version of the explanation above:
def isEvenWord(word):
if word == '': # base condition
return True
else:
last_letter = word[-1]
if word.count(last_letter) % 2 != 0:
return False
else:
next_word = word[0:-1] #create the next word you want to test (ie the word except the last letter)
next_word = word.replace(last_letter, '') # in the new word, replace the variable last_letter (the letter you just counted) by an empty string '' which is like removing it
return isEvenWord(next_word)
Very nice little puzzle, thanks for sharing.
I hope this helps.
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 6 years ago.
Improve this question
The task is:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last
Below is a solution that constructs the string with first, body and last portions
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
String literals can be sliced and added:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S. str is a builtin in python, so using it as a variable name is a bad idea.
First, never call a variable str. Why? Because that is the name of the class for Python strings. If you use the same name then you loose it. I use txt.
Your test with the length is sensible, but the lower limit can be increased (a single character would be silly).
But using str.replace() is not feasible. Why? Well it could work in your test case, but only because each character is unique. str.replace() replaces every occurrence of the specified string. So if the first or last character was repeated elsewhere then that would be changed as well.
You can use slicing, where the first (leftmost) character is 0 (zero). You can also index from the right using negative numbers, so -1 is the last (rightmost) character. The range of characters goes from the start to the character after the last. So [1:-1] goes from the second character to the last but one.
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
I use return in the function, since that would be the normal way of processing text, and that is asked for in your question.
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 8 years ago.
Improve this question
I have a wordlist containing numbers, English Words, and Bengali words in a column and in other column I have their frequencies. These columns have no headers. I need the words with frequencies between 5- 300. This is the code I am using. It is not working.
wordlist = open('C:\\Python27\\bengali_wordlist_full.txt', 'r').read().decode('string-escape').decode("utf-8")
for word in wordlist:
if word[1] >= 3
print(word[0])
elif word[1] <= 300
print(word[0])
This is giving me a syntax error.
File "<stdin>", line 2
if word[1] >= 3
^
SyntaxError: invalid syntax
Can anyone please help?
You should add : after your if statements to fix this SyntaxError:
wordlist = open('C:\\Python27\\bengali_wordlist_full.txt', 'r').read().decode('string-escape').decode("utf-8")
for word in wordlist:
if word[1] >= 3:
print word[0]
elif word[1] <= 300:
print word[0]
Read this:
https://docs.python.org/2/tutorial/controlflow.html
Also here it is one useful tip: when python gives you SyntaxError for some line, always look at the previous line, then at the following one.
There are few problems with your code, I add full explanation in an hour and so. See how it should look like and consult docs in the meantime:
First, it is safer to use with open() clause for opening files (see https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects)
filepath = 'C:/Python27/bengali_wordlist_full.txt'
with open(filepath) as f:
content = f.read().decode('string-escape').decode("utf-8")
# do you really need all of this decdcoding?
Now content holds text from file: this is one, long string, with '\n' characters to mark endlines. We can split it to list of lines:
lines = content.splitlines()
and parse one line at the time:
for line in lines:
try:
# split line into items, assign first to 'word', second to 'freq'
word, freq = line.split('\t') # assuming you have tab as separator
freq = float(freq) # we need to convert second item to numeric value from string
if 5 <= freq <= 300: # you can 'chain' comparisons like this
print word
except ValueError:
# this happens if split() gives more than two items or float() fails
print "Could not parse this line:", line
continue
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
I need to make a program in python which looks through a given file. Let's say acronyms.txt, and then returns a percentage value of how many lines contain at least 1 three letter acronym.
For example:
NSW is a very large state.
It's bigger than TAS.
but WA is the biggest!
After reading this it should return 66.7% as 66.7% of the lines contain a three letter acronym. It is also rounded to the first decimal place as you can see. I am not very familiar with regex but I think it would be simplest with regex.
EDIT:
I have finished the code but i need it to recognize acronyms with dots between them, EG N.S.W should be recognized as an acronym. How do i do this?
Any help would be appreciated!
You can do:
import re
cnt = 0
with open('acronyms.txt') as myfile:
lines = myfile.readlines()
length = len(lines)
for line in lines:
if re.search(r'\b[A-Z]{3}\b', line) is not None:
cnt += 1
print("{:.1f}%".format(cnt/length*100))
r'[A-Z]{3}' matches three (and only three) capital letters in a row. If a search is found, then we add a count.
Then we simply do the count divided by the length of lines, and print the result as you have shown.
You can do something like:
total_lines = 0
matched_lines = 0
for line in open("filename"):
total_lines += 1
matched_lines += bool(re.search(r"\b[A-Z]{3}\b", line))
print "%f%%" % (float(matched_lines) / total_lines * 100)
Note '\b' in search pattern -- it matches empty string in beginning or end of word. It helps you to prevent unwanted matches with acronyms longer than 3 ('asdf ASDF asdf') or with acronyms inside word ('asdfASDasdf').