[英]Pass the “method()” portion of Object.method() as a parameter
First, let me say that this is a hackerrank question which, though I could do it hackily, is allowing me to indulge my deeper python curiosities. 首先,让我说这是一个hackerrank问题,尽管我可以很巧妙地做到这一点,但它却让我沉迷于更深层次的python好奇心。
I would welcome comments on my general approach, but my specific question relates to the title of this post. 我欢迎就我的一般做法发表评论,但我的具体问题与该职位的标题有关。
Question: 题:
Task
任务
You are given a string S. Your task is to find if string S contains, alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
给您一个字符串S。您的任务是查找字符串S是否包含字母数字字符,字母字符,数字,小写和大写字符。
Input Format
输入格式
Single line containing, string S.
单行包含字符串S。
Constraints
约束条件
0
0
Output Format
输出格式
In First line, print True if S has any alphanumeric character, otherwise print False.
在第一行中,如果S具有任何字母数字字符,则输出True,否则输出False。
In Second line, print True if S has any alphabetical character, otherwise print False.
在第二行中,如果S具有任何字母字符,则输出True;否则,输出False。
In Third line, print True if S has any digits, otherwise print False.
在第三行中,如果S有任何数字,则输出True,否则输出False。
In Fourth line, print True if S has any lowercase character, otherwise print False.
在第四行中,如果S具有任何小写字符,则输出True;否则,输出False。
In Fifth line, print True if S has any uppercase character, otherwise print False.
在第五行中,如果S具有任何大写字符,则输出True;否则,输出False。
Attempted Code: 尝试输入的代码:
S = input()
def testing(S, fun):
for x in S:
if x.fun:
print(x.fun)
break
else:
print(False)
testing(S, .isalnum())
testing(S, .isalpha())
testing(S, .isdigit())
testing(S, .islower())
testing(S, .isupper())
I'm not sure how to get my string methods into my testing
function in a way that lets me run them against each letter of the string(s). 我不确定如何将字符串方法放入
testing
函数中,从而无法针对字符串的每个字母运行它们。
I could obviously pass a kwarg and do a select-case, but that's not what I'm looking for. 我显然可以通过kwarg并做一个选择案例,但这不是我想要的。 I'm sure there's a way to do this with lambdas (perhaps instead of passing
.method()
I would pass lambda x: x.method()
), but (1) I'm not too sure about lambdas, and (2) I have this theory that I'd really like to write code that a beginner can always read, and lambdas aren't beginner. 我敢肯定有一种方法可以用lambdas做到这一点(也许不传递
.method()
我可以传递lambda x: x.method()
),但是(1)我不太确定lambdas,以及(2 )我有这样的理论,我真的很想编写一个初学者始终可以阅读的代码,而lambda并不是初学者。
You can assign an instance method to a variable as if it were a normal function, by using the class name that declares the method. 您可以使用声明方法的类名称,将实例方法分配给变量,就好像它是普通函数一样。 For instance:
例如:
fun = str.isalnum
print (fun('123'))
So your code would end up looking something like this: 因此,您的代码最终看起来像这样:
def testing(S, fun):
for x in S:
if fun(x):
print(fun(x))
break
else:
print(False)
testing(S, str.isalnum)
or more succinctly: 或更简洁地:
def testing(S, fun):
print(any(fun(x) for x in S))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.