Hello I'm trying an hackerrank problem : String Validators
I actually solved the question but i'm trying a different approach on it.
Such as:
list=['isalnum()','isalpha()','isdigit()','islower()','isupper()']
for l in list:
count =0
for i in range(len(s)+1):
a=i.l
if a==1:
count+=1
if count !=0:
print(False)
elif count >0:
print(True)
Is there any way that I can convert components inside the list as a function and use it?
In python you can actually make a list of function:
if you have your array looking like this:
list=[isalnum,isalpha, isdigit, islower, isupper]
if you type
list[0]()
the function isalnum will be executed, obviously if they take parameters you can also pass parameters
in case you want the members of your list to be like you wrote:
list=['isalnum()','isalpha()','isdigit()','islower()','isupper()']
you can use the function eval() even if i don't suggest it:
eval(list[0])
will evaluate the string as a line of code and execute the function isalnum()
Related
so I wnt to compare a string in a iist and variable but the output is awlays false
ive used is and == then I thought because elemen in my list is not string then I try to chnage it in to a str using str() func but it doesnt work
obj='ana'
# haha[22][0] is 'ana'
obj1=str(haha[22][0])
if obj is obj1:
print('true')
else:
print('false')
print(obj1)
first I tried to change == into is but it doesnt work then I though I need to change elemen in my list into str() it doenst work too
I would like to compare it thank you so much for the answer
This is almost certainly something to do with what's stored in your list. Also in general == is for comparing value and 'is' is for comparing identity so you should use == in this situation.
What is output by the last print?
'ana' == 'ana' will always return true so without specifying where the element is set there isn't enough information to work out what your issue is.
If it prints 'ana' it may be worth printing the hash function of each object to compare.
I'd like to have written this as a comment but I don't have enough rep to comment :/
I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.
def myfunc(*args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?
By writing *args in your function declaration, it means that you're iterating over a number of strings and not just one string. For example:
myfunc('hello', 'goodbye')
Your function will iterate over a hello and goodbye, with hello having an index of 0 which is even number and thus converting its characters to uppercase, whereas goodbye has an index of 1 which is odd and thus covnerting its characters to lowercase:
HELLOgoodbye
If you wish to call your function for only one string, you have to remove the * from *args or inserting the string's characters one by one:
myfunc('h','e','l','l','o')
So, the declaration and implementation of your function should look like this:
def myfunc(args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
Calling myfunc('hello') will return the correct result.
The problem is, you're using var-args. That's wrapping the string passed with a list, then you're iterating over that list (which only contains one string). This means your code does work to some extent; its just alternating the case of each whole word instead of each character.
Just get rid of the var-args:
def myfunc(word):
return ''.join([word[i].upper() if i%2==0 else word[i].lower() for i in range(len(word))])
print(myfunc("hello world"))
# HeLlo WoRlD
I'll just note, there's a few ways this could have been debugged. If you had checked the contents of args, you would have seen that it only contained a single element when one argument was passed, and two when two arguments were passed. If you had passed two arguments in, you would have also noticed that it alternated the case of each word as a whole. That would have likely given you enough hints to figure it out.
The above answers are correct but they ask you to modify the current syntax. In general you should try to understand how *args works.
In python, *args in a function definition is used to receive variable number of arguments. Such cases arise when we don't know in advance how many arguments will be passed.
For example :
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Now coming back to your code, you can make it run by selecting the first argument from the args list. See below :
def myfunc(*args):
return ''.join([args[0][i].upper() if i%2==0 else args[0][i].lower() for i in range(len(args[0]))])
print(myfunc("input"))
Help the community by selecting the best answer for this question.
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.
So i'm trying to write a code for a router terminal simulator. And I'm using raw_input to read from the keyboard.
The problem is that I want to do a specific action when the user writes a sequence that matches this pattern: "<1-100> permit", so in order to accomplish this I wrote an if of this type:
if input == "%d permit" %number:
print 'Do this'
I want the number to be a value in the range of 1-100. I created a list with the range(1,100) function but I don't know how to check this condition inside my if.
I solved the problem however with the use of split function and some other conditions, but I can't really get over this idea and I want to find a solution. Any help would be greatly appreciated.
if input == "%d permit" %number and number in range(1,101):
print 'Do this'
Use re.match(pattern, value):
import re
[...]
if re.match(r"(\d\d?|100) permit", input):
do_something()
And the variable input will override the built-in function input(), so change the name to something else.
EDIT: As you don't want to use RegExp, you can split the string, pass it to int and then see if it's in the range.
if 1 <= int(input.split(" ")[0]) <= 100:
do_something()
I am using recursion to reverse a string. I am able to reverse a string successfully using following code.
def rev(string):
if len(string)==0:
return string
if len(string)==1:
return string
else:
s=string
string = s[-1]+rev(s[:-1])
return string
But when i am replacing return with print it is printing only the first two characters of answer and then throwing an error saying
"TypeError: cannot concatenate 'str' and 'NoneType' objects"
Example. when give 'StackOverflow' to function and returned a value it returns 'wolfrevOkcatS' corrrectly
but when I am trying to print the answer in the function itself, it is only printing "tS" giving the error above.
I suspect that you did something like this:
def rev(string):
if len(string)==0:
print string
if len(string)==1:
print string
else:
s=string
string = s[-1]+rev(s[:-1])
print string
Let's get right to the problem. Supposed the string you are trying to reverse is abc. In the first call, you will hit the else clause and try to evaluate:
'c' + rev('ab')
The problem is now that your function has no return statements, rev('ab') returns None. And python raises an error when you try to concatenate a string with None.
With the return statements. rev('ab') returns 'ba' and the plus sign can be used to concatenate 'c' with 'ba'.
As an aside, if you are ever trying to solve this problem in production code, you should be using the built in tools.
reversed_str = myStr[::-1]
reversed_str_iterator = reversed(myStr)
If you're replacing return with print, your function will not return anything. In Python, that is the same as returning None. This breaks your recursive step where you concatenate the last letter of the string with the return value of the recursive call. Instead, you should just let the recursive call do its own printing (just call it), after print the last letter in a separate statement:
else:
print(s[-1], end="") # or print s[-1], (with the comma!) if you're on Python 2
rev(s[:-1])
Note that you probably want your base cases to print a newline in this situation, since otherwise you won't get one at all.
If you don't return from a function, then the function implicitly returns None. By replacing return with print, you break the recursive functionality; it recurses, but the values computed in the recursive calls are not returned and used. If you want to print intermediate results for your own edification, do so, but do so just before each return statement, not in place of the return statements.
To reverse a string/list in Python use list[::-1]
Demo
>>> my_str = 'StackOverflow'
>>> my_str[::-1]
'wolfrevOkcatS'