A Needle in the Haystack(大海捞针)
Can you find the needle in the haystack?
Write a function findNeedle() that takes an array full of junk but containing one "needle"
After your function finds the needle it should return a message (as a string) that says:
"found the needle at position " plus the index it found the needle, so
Example(Input --> Output)
["hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"] --> "found the needle at position 5"
Note: In COBOL, it should return
"found the needle at position 6"
COBOL是一个高级计算机编程语言,主要用于商业应用。它是一个缩写,全称是Common Business-Oriented Language,意思是通用商业导向语言。
COBOL是1959年由美国政府和私营部门共同发起的数据系统语言会议(Conference on Data Systems Languages)开发的,是最早广泛使用的语言之一,也是多年来商业界最受欢迎的语言。
COBOL是一种命令式、过程式、并且自2002年起也支持面向对象的语言。
COBOL主要用于公司和政府的商业、金融和管理系统。COBOL仍然在许多应用程序中广泛使用。
Solution:
def find_needle(haystack):
# loop through the haystack list
for i in range(len(haystack)):
# check if the current element is "needle"
if haystack[i] == "needle":
# return a message with the index
return f"found the needle at position {i}"
# if no needle is found, return None
return None
f-string是从Python 3.6开始引入的一种新的字符串格式化方法,它可以在字符串中使用花括号{}来插入变量或表达式的值。f-string前面要加一个字母f,表示格式化字符串。
return f"found the needle at position {i}"
例如,如果i的值是5,那么返回的字符串就是"found the needle at position 5"。

浙公网安备 33010602011771号