how can i solve this? Python def function [closed] - python

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
def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
sen = sen.translate(None, "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
**print LongestWord("Argument goes here")**
what's wrong with this line? How can I change it? I can't understand it! It make me really uneasy, cause in Coderbyte.com says that it is true and it work!

I'm not exactly sure what line you're referring too? Perhaps the last line.
If so you need a parenthesis with the print statement in python 3.x
print(LongestWord("Argument goes here"))
additionally, string translate works differently in python 3
def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
intab ="~!##$%^&*()-_+={}[]:;'<>?/,.|`"
trantab= str.maketrans(dict.fromkeys(intab))
sen = sen.translate(trantab)
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
print(LongestWord("Argument. 'Go' #goes here"))
The above worked for me on python 3.6.2

It is working properly but instead of return try
print max(arr, key=len)
as if you called the function directly without print keyword preceding it won't show the max or you can return both arr, max in single line and print the function output so it would look like this:
def LongestWord(sen):
sen = sen.translate(None, "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
arr = sen.split(" ")
print(arr)
print max(arr, key=len)
LongestWord("Argument goes here ! #")
NOTE : it worked in Python 2.7
IF YOU WOULD LIKE TO USE PYTHON 3.7
use the following
to_remove = sen.maketrans("", "", "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
sen = sen.translate(to_remove)

Related

Why this code in Python doesn't recognize the number from a string? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I have a string that I need to extract the numbers into the string. The "number" has a comma in it. If I delete the comma the function works but in case that I leave it, the functions doesn't works. I need the function to work with the comma. I dont know why, the comma its a problem here.
I will be thankful if someone let me know why the comma it's a problem.
Thank you in advance!
def get_numbers(text):
num = [int(i) for i in text.split() if i.isdigit()]
print(num)
get_numbers("16,645")
You need to remove the split() method so your code will look like this:
def get_numbers(text):
num = [int(i) for i in text if i.isdigit()]
print(num)
get_numbers("")
text.split() will return ['16,645'], which you don't want. Use it when you want to separate the string by whitespace (e.g., space, tab, newline).
In this case the text string is an iterator over which you iterate. At the beginning of each cycle in the list comprehension a value from text will be assigned to i.
Instead of trying to split text, you can just iterate through text
Code1:
def get_numbers(text):
num = [int(i) for i in text if i.isdigit()]
print(num)
get_numbers("16,645")
Or if you really want to split the string at the comma.
Code2
def get_numbers(text):
text = ''.join(text.split(','))
num = [int(i) for i in text]
print(num)
get_numbers("16,645")
split method is returning ['16,645']; a list with one string, which is not a digit obviously.
You should use it without split:
def get_numbers(text):
num = [int(i) for i in text if i.isdigit()]
print(num)
get_numbers("16,645")

Error in program-censor(codecademy)Practice makes perfect [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 5 years ago.
Improve this question
I wanted to include spaces too while splitting the text, for that i looked up on google used import re
import re
def censor(text,word) :
text1=re.split(r"(\s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
The error I am getting is
image displaying error and code
If I include an another for loop to replace every 'e' with a whitespace , it doesn't work.
In your code, text1 (very bad naming BTW) is a list of words, and text a single string. Your first for loop is iterating on text1 indices (words in the list), but in the else clause you subscript the whole text string. Obviously you want to get the word from the words list (text1), not the character at position i in the text string. IOW: replace your else clause with:
sum=sum+text1[i]
and the test should pass.
If you used a correct naming and proper code layout you would certainly have spotted the problem more easily:
def censor(text, word) :
words = re.split(r"(\s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
Also you are making things much more complicated than they have to be. You can pre-compute the "replacement" string for "bad" words once for all before the loop (and you don't need a loop to do so), and you don't need a range and indexed acces, ou can iterate directly on the words list instead:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(\s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
There would be other possible improvements but at least this is mostly readable and much more pythonic.

Why doesn't my front_back programme in Python work? [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 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.

Replacing the last three characters in a string if they match a condition [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 7 years ago.
Improve this question
I am trying to take a user inputed string and, if it ends with 'ion', replace the last three characters of the string and add an 'e'.
def ion2e(s):
if s[-3:]=='ion':
print (s[-3:]+'e')
else:
print (s)
Use str.endswith:
>>> def ion2e(s):
... return s[:-3] + 'e' if s.endswith('ion') else s
...
>>> ion2e('xxxion')
'xxxe'
>>> ion2e('xx')
'xx'
s[-3:] says
give me s starting 3 digits backwards from the end, and going to the end
But what you want is s up to 3 digits backwards from the end. Which would be:
s[:-3]
So your whole code should be:
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
Move the colon in your print. You need the string up to the -3rd element, not the end of the string.
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
t = "constitution"
ion2e(t)
Also, are you familiar with single-statement if expressions? Your function might be reduced to this, if you want to return the value instead of printing it.
def ion2e(s):
return s[:-3]+'e' if s[-3:]=='ion' else s
You may also want to use re
import re
print (re.sub("ion$", "e", 'station'))

Procedure in Python

Question
Write a procedure that takes a string of words separated by spaces (assume no punctuation or capitalization), together with a ”target” word, and shows the position of the target word in the string of words. For example, if the string is:
'we dont need no education we dont need no thought control no we dont'
and the target is the word ”dont” then your procedure should return the list 1, 6, 13 because ”dont” appears at the 1st, 6th, and 13th position in the string. (We start counting positions of words in the string from 0.) Your procedure should return False if the target word doesn’t appear in the string.
My solution-
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print procedure(string, "dont")
assert procedure(string, "dont")
Why is this not running in python?! The problem is on print procedure(string, "dont") it mentions invalid syntax. I am running it in the IDLE.
The following is your code with the indentation fixed, compare this with what you posted and you should see why it now works.
It is unclear to me why your original code has a problem because the indentation controls how python views the blocks of code and will fail to run if the indentation is incorrect. I suspect that your problem is that you had these lines in your code:
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
The above will fail and return False because solution length will be 0 on the first iteration if your word is not found on the first iteration, you should check the len of solution outside the scope of the for loop.
In [42]:
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print(procedure(string, "dont"))
assert(procedure(string, "dont"))
[1, 6, 13]
You can user a list comprehension for this:
def list_word_indexes(word, text):
return [index for index, text_word in enumerate(text.split())
if text_word == word]
The problem is on print procedure(string, "dont") it mentions invalid syntax
This means you are using python 3, where print is a function and not a statement. You should add brackets around the argument(s) to print or make sure to use python 2.
eg.
print(procedure(string, "dont"))

Categories

Resources