Hello everyone I've been practicing with python for a bit now and found a project named Ubbi. Pretty much the whole goal is, is to add a string 'ub' before every vowel. So my question am i even close to cracking this or should i head another route??
def ubbidubbi_word(eword):
ubword = ""
for i in eword:
if i == 'aeoiuy': ubword += 'ub'+eword(i)
else: ubword += eword(i)
return ubword
You're close! However...:
(A) eword(i) would call eword as a function with argument i, which makes no sense; just use i itself, the character you're currently looking at (maybe you're thinking of Javascript here...? but even there the syntax will be different);
(B) i, a single character, will never equal the string 'aeoiuy', as you're checking; rather you should check if i is in that string (and thus a vowel).
Related
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 12 months ago.
Improve this question
I need to generate a string of the numbers from 1 to 50 with a for-loop.
my suggestion:
solution = range(1,50)
for i in solution
print(i++, end ="")
it shows me invalid syntax and I don't really get behind the reason. The output should be a string with the number from 1 to 50 added like this (12345....).
How do I do that?
variable++ is not Python syntax at all. You might know it from C, C++, Java, JavaScript, or any of the dozens of languages that use it.
You're missing a colon after the for loop line.
The Python interpreter should have pointed out at least the latter to you. The former is easily found by Googling.
The following should give the output you need, but know that there are easier ways to do this in Python.
solution = range(1,50)
string_variable = "" # the i from below will be of type integer, not string.
for i in solution:
string_variable += str(i) # += performs appending (or addition depending on the data type), but you'll need to convert i to a string
print(string_variable)
Explanation (method 1)
Breaking down the problem
Let's think about what you want.
You want to consider numbers from 1 to 50.
You then want to think about them one at a time.
While doing step 2, you want to maintain a "joined" record somewhere, and "join" each number at the end of the record as you consider it.
Finally, you want to output that "joined" record.
Converting ideas to code
Let's go through each step one at a time, this time in code.
Consider numbers from 1 to 50.
You got this! You saved a range() generator to a variable with 1 and 50 as its endpoints.
solution = range(1, 50)
Think about them one at a time.
You got this too! By using a for loop to iterate over your generator, you are doing this.
for i in solution:
Join the numbers
This step gotcha :(
To understand this, you need to know about something called data types.
The range() generator gives you integer values. Think of this as a proper value: a number that you can manipulate (add, subtract, multiply etc).
However, when you want to join stuff together (called concatenating), you need to use strings.
To you and me, a number on a piece of paper is same as the number on a calculator. To a computer, it's not. If it's a string, it's treated equivalently to an alphabet: you cannot do math with it, you can only do stuff like displaying it.
To concatenate, you must convert to a string. That's why I start with a blank string variable.
string_variable = ""
We do this with the following syntax:
str(i)
The str stands for string.
The joining part happens with the += operator:
string_variable += str(i)
Output the string
I think you know how to do this. Just print it out:
print(string_variable)
Putting it all together:
solution = range(1,50)
string_variable = ""
for i in solution:
string_variable += str(i)
print(string_variable)
Explanation (method 2)
I think your logic was right.
solution = range(1,50)
for i in solution
print(i++, end ="")
We're removing the ++ because it isn't valid Python syntax. This is the increment operator from languages like C++. In practice, if you were using something like a while loop, you would use this to increase the value of i by 1 in each pass of the loop. However, for loops sort of have this idea built into them, so we don't need it.
Addition of : and indentation by 4 spaces are done because that's way we communicate to Python that the line print(i, end ="") is to be executed inside the loop for i in solution.
Corrected code:
solution = range(1,50)
for i in solution:
print(i, end ="")
So the problem is I need to take a string and if it's ord value (ord(ch)) is a multiple of x in the function then that character needs to be added to the new string. I was just wondering if I've done this correctly?
def test(string, x):
r = []
for ch in string:
if ord(ch) % x == 0:
r.append(ch)
return ''.join(r)
Have I done this correctly? If not, any pointers? This was a question in my test I've failed and I don't know if I did it right or not.
Perhaps they were looking for a list comprehension:
return "".join( ch for ch in string if ord(ch)%x == 0 )
That looks correct. You might want to post the exact instructions for the problem, as it's possible you slightly misread the question. It's very hard to write (and read) unambiguous instructions for coding challenges. Nearly everybody who learned programming has made such a mistake at least once in their life.
I was gonna post a list comprehension version, but Alain T. beat me to it while I formulated this response.
I'm having trouble in an online course for python, specifically a palindrome problem These are the instructions, but the function must be case-insensitive and not see spaces. I think the issue is in my return blocks or my flow. I think I need to use the lower function, but I'm honestly not sure.
def student_func(x):
for string in x:
x.lower()
y = x.replace(" ", "")
if y[::-1]==y:
return True
else:
return False
You actually have two separate problems in your code—and you're right that one of them is with lower and the other is with the return flow.
First, x.lower() doesn't modify x in-place. In fact, strings are immutable; nothing modifies them in-place. If you look up the interactive help or the online docs, it says:
Return a copy of the string with all the cased characters [4] converted to lowercase.
So, you need to do the same thing with lower that you do with replace: assign the result to a variable, and use that:
y = x.lower()
z = y.replace(" ", "")
Or you can reuse the same variable:
x = x.lower()
… or chain the two calls together:
y = x.lower().replace(" ", "")
As a side note, unless you're using Python 2, you should consider whether you want casefold instead of lower. For English it makes no difference, but for other languages it can.
Meanwhile, you're doing for string in x:, but then ignoring string.
If x is just a single word, you don't want to loop over it at all.
If x is a list of words, then the for string in x: is correct, but then you have to use string inside the loop, not x. Plus, you can't just return True or return False—that will exit the function as soon as you test the first word, meaning the rest of them never get tested. I'm not sure whether you want to return True if there are any pallidromes, or if they're all palindromes, or if you want to return a list of booleans instead of a single one, or what, but you can't just return the first one.
It would probably be a lot clearer if you used better names, like words instead of x and word instead of string.
Anyway, I can't tell you the right way to fix this since I don't know what you're trying to do, but hopefully this explains enough that you can fix it yourself.
Giving away the solution defeats the purpose of the exercise
your approach is more or less correct.
convert string to a standard case
remove whitespace
check if reverse of the string is equal to the original string
The error lies in how you are using the python API.
check what each of the functions do, and what they return.
a good idea is to run help(function) to see what the function's documentation has to say about it.
try help(x.lower) (note: not help(x.lower())) and see what the return value is.
This question already has answers here:
Using 'try' vs. 'if' in Python
(9 answers)
Closed 6 years ago.
I have a function in which I would like to detect the first occurrence of any letter (given a group of letters) within a string and return the index of the letter(see below).
Time is critical so I am thinking of using a try/except method (see LetterDetect below).
Knowing that the try statement will fail most of the time, is this a bad practice? Secondly Would this be more efficient (time-wise) than checking every dictionary entry for the occurrence of each letter (as in LetterDetect2)?
Take the following function which looks:
def LetterDetect(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
try:
Dct[ord(s[i])] +=1
return i
except:
pass
Versus:
def LetterDetect2(s, letters):
Dct = {}
for l in letters:
Dct[ord(l)] = 0
for i in range(0, length(s)):
if ord(s[i]) in Dct:
return i
LetterDetect("test", "abcdt")
LetterDetect2("test", "abcdt")
I appreciate any help, I am new to coding and Python. Thanks!
Using a dictionary seems like an odd way to solve this problem. Is there some specific reason you're using that?
The string method .find() https://docs.python.org/2/library/stdtypes.html#str.find seems like a much better solution:
def LetterDetect(s, letters)
for l in letters:
position = s.find(l)
if position != -1:
return position
return None
In addition to the basic problems with your design that John Gordon pointed out, I would like to respond directly to the question:
Using try/catch to achieve ordinary flow control is an abuse of its purpose. I can predict several ways this might bite you (the debugger might stop you on the exception, a future programmer might "correct" your code) but the basic rule is, use language features as they were designed.
As a practical matter, a try/catch will tend to be slow. The language runtime has to get involved and do all sorts of fancy things, none of which you actually need.
Exceptions should be, well, exceptional.
I've created a python program where the user enters a word, then the program turns the word into a list. The user then enters a letter and then the program tell you how many times the letter appears. Now I need to add more program to check it the word that was entered at the beginning is a palindrome. If it is there will be a good message and if not a false message. Not really sure how to start. Any help?
You can reverse the string and check whether it's equal to the input string:
def palindrome(s):
return s == s[::-1]
There is a known "trick" for that in python, reversing the word using [::-1]. Not the most efficient though:
>>> "racecar" == "racecar"[::-1]
True
>>> "racecars" == "racecars"[::-1]
False
Okay so I've looked over all of your answers. Would this code be suitable or even a proper peice of code which isn't utter s**t?
def getPalindrome()
if word == word[::-1] :
print(True)
else :
print(False)
palindrome = getPalindrome()
You could use a simple conditional statement. This should be much easier to understand for the beginner. For example:
text = "Rapport"
def palindrome(text)
if text[::-1] == text:
return True
else:
return False
I believe this should be pretty easy to understand. text[::-1] is the fastest approach. A much slower approach is using ''.join(reversed(list)), where the list is the list you split your text into. You can verify which approach you want to take by timing your code using timeit.
Although, timing the slicing of your code is considered a bad benchmark so time the whole code. Hope I explained well enough. Good luck!
Edit: your code is good but you need to remember that a function takes in an argument as a value, which is what you manipulate in the function itself.
Your final code should look something like this:
text = StrVar()
def getPalindrome(word):
if word == word[::-1]:
return True
else :
return False
palindrome = getPalindrome(text)
Notice that the function's argument is different from the text itself, which I assigned a string variable to also show that you don't need to give it a value right away. Make your code elegant.