# Checkio python 练习之Elementary

1.Say hi--------------------------------------------- ----------------------------------------

Input: Two arguments. String and positive integer.

Output: String.

Example:

say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old"
say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old"

def say_hi(name, age):
"""
Hi!
"""
return "Hi. My name is " + name + " and I'm " + str(age) + " years old"

2.Correct Sentence--------------------------------------------- ----------------------------------------

Pay attention to the fact that not all of the fixes is necessary. If a sentence already ends with a dot then adding another one will be a mistake.

Input: A string.

Output: A string.

Example:

correct_sentence("greetings, friends") == "Greetings, friends."
correct_sentence("Greetings, friends") == "Greetings, friends."
correct_sentence("Greetings, friends.") == "Greetings, friends."

def correct_sentence(text: str) -> str:
"""
returns a corrected sentence which starts with a capital letter
and ends with a dot.
"""
if text[-1]=='.':
return text[0].title()+text[1:]
else:return text[0].title()+text[1:]+'.'

3.First word--------------------------------------------- ----------------------------------------

When solving a task pay attention to the following points:

• There can be dots and commas in a string.
• A string can start with a letter or, for example, a dot or space.
• A word can contain an apostrophe and it's a part of a word.
• The whole text can be represented with one word and that's it.

Input: A string.

Output: A string.

Example:

first_word("Hello world") == "Hello"
first_word("greetings, friends") == "greetings"

import re
def first_word(text: str) -> str:
"""
returns the first word in a given text.
"""

pat1 = "[a-zA-Z']+"
result = re.search(pat1,text)
result = str(result.group())
return result


4.Second index--------------------------------------------- ----------------------------------------

Input: Two strings.

Output: Int or None

Example:

second_index("sims", "s") == 3
second_index("find the river", "e") == 12
second_index("hi", " ") is None

def second_index(text: str, symbol: str):
"""
returns the second index of a symbol in a given text
"""
if text.count(symbol)<2:return None
else:return text.find(symbol,text.find(symbol)+1)

5.Between Markers--------------------------------------------- ----------------------------------------

Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers.

Output: A string.

Example:

between_markers('What is >apple<', '>', '<') == 'apple'
between_markers('No[/b] hi', '[b]', '[/b]') == 'No'

def between_markers(text: str, begin: str, end: str) -> str:
if begin in text:
start = text.index(begin) + len(begin)
else:
start = 0
if end in text:
finish = text.index(end)
else:
finish = len(text)
return (text[start:finish])

6.Best stock------------------------------------------- ----------------------------------------

You are given the current stock prices. You have to find out which stocks cost more.

Input: The dictionary where the market identifier code is a key and the value is a stock price.

Output: A string and the market identifier code.

Example:

best_stock({
    'CAC': 10.0,
    'ATX': 390.2,
    'WIG': 1.2
}) == 'ATX'
best_stock({
    'CAC': 91.1,
    'ATX': 1.01,
    'TASI': 120.9
}) == 'TASI'

def best_stock(data):
d=sorted(data,key=data.get) ‘data.get的用法’
return d[-1]

7.Papular Words------------------------------------------- ----------------------------------------

At the input of your function are given 2 arguments: the text and the array of words the popularity of which you need to determine.

When solving this task pay attention to the following points:

• The words should be sought in all registers. This means that if you need to find a word "one" then words like "one", "One", "oNe", "ONE" etc. will do.
• The search words are always indicated in the lowercase.
• If the word wasn’t found even once, it has to be returned in the dictionary with 0 (zero) value.

Input: The text and the search words array.

Output: The dictionary where the search words are the keys and values are the number of times when those words are occurring in a given text.

Example:

popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
    'i': 4,
    'was': 3,
    'three': 0,
    'near': 0
}

def popular_words(text, words):
text=text.lower()
dit={}
count=0
for s in words:
if s in text:
count=text.count(s)
dit[s]=count
else:
dit[s]=0
return dit

8.Bigger Price------------------------------------------ ----------------------------------------

Your mission here is to find the TOP most expensive goods. The amount we are looking for will be given as a first argument and the whole data as the second one

Input: int and list of dicts. Each dicts has two keys "name" and "price"

Output: the same as the second Input argument.

Example:

bigger_price(2, [
    {"name": "bread", "price": 100},
    {"name": "wine", "price": 138},
    {"name": "meat", "price": 15},
    {"name": "water", "price": 1}
]) == [
    {"name": "wine", "price": 138},
    {"name": "bread", "price": 100}
]


bigger_price(1, [
    {"name": "pen", "price": 5},
    {"name": "whiteboard", "price": 170}
]) == [{"name": "whiteboard", "price": 170}]

def bigger_price(limit, data):
result=[]
data=sorted(data, key=lambda x: x['price'], reverse=True)

for i in range(limit):
result.append(data[i])
return result

9.Fizz Buzz------------------------------------------ ----------------------------------------

You should write a function that will receive a positive integer and return:
"Fizz Buzz" if the number is divisible by 3 and by 5;
"Fizz" if the number is divisible by 3;
"Buzz" if the number is divisible by 5;
The number as a string for other cases.

Input: A number as an integer.

Output: The answer as a string.

Example:

checkio(15) == "Fizz Buzz"
checkio(6) == "Fizz"
checkio(5) == "Buzz"
checkio(7) == "7"

def checkio(number):
str1=''
if (number%3==0 and number%5==0):
str1="Fizz Buzz"
elif (number%3!=0 and number%5==0):
str1='Buzz'
elif (number%3==0 and number%5!=0):
str1='Fizz'
elif (number%3!=0 and number%5!=0):
str1=str(number)

return str1

10.The Most Number------------------------------------------ ----------------------------------------

Input: An arbitrary number of arguments as numbers (int, float).

Output: The difference between maximum and minimum as a number (int, float).

Example:

checkio(1, 2, 3) == 2
checkio(5, -5) == 10
checkio(10.2, -2.2, 0, 1.1, 0.5) == 12.4
checkio() == 0

def checkio(*args):
if args:return max(args)-min(args)
else:return 0

11.Even the last ------------------------------------------ ----------------------------------------

You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0.

For an empty array, the result will always be 0 (zero).

Input: A list of integers.

Output: The number as an integer.

Example:

checkio([0, 1, 2, 3, 4, 5]) == 30
checkio([1, 3, 5]) == 30
checkio([6]) == 36
checkio([]) == 0

def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array)==0:return 0
else:
last=array[-1]
data=array[::2]
c=0
for i in data:
c+=i
return c*last

12.Secret Message ------------------------------------------ ----------------------------------------

You are given a chunk of text. Gather all capital letters in one word in the order that they appear in the text.

For example: text = "How are you? Eh, ok. Low or Lower? Ohhh.", if we collect all of the capital letters, we get the message "HELLO".

Input: A text as a string (unicode).

Output: The secret message as a string or an empty string.

Example:

find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO"
find_message("hello world!") == ""

def find_message(text):
"""Find a secret message"""
data=[]
for i in range(len(text)):
if text[i].isupper():
data.append(text[i])

return "".join(data)

13.Three Words------------------------------------------ ----------------------------------------

You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession.

Input: A string with words.

Output: The answer as a boolean.

Example:

checkio("Hello World hello") == True
checkio("He is 123 man") == False
checkio("1 2 3 4") == False
checkio("bla bla bla bla") == True
checkio("Hi") == False

def checkio(words):
i=0
for word in words.split():
if word.isalpha():
i+=1
if i==3:return True
else:i=0
return False

14.Index Power------------------------------------------ ----------------------------------------

Let's look at a few examples:
- array = [1, 2, 3, 4] and N = 2, then the result is 32 == 9;
- array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1.

Input: Two arguments. An array as a list of integers and a number as a integer.

Output: The result as an integer.

Example:

index_power([1, 2, 3, 4], 2) == 9
index_power([1, 3, 10, 100], 3) == 1000000
index_power([0, 1], 0) == 1
index_power([1, 2], 3) == -1

def index_power(array, n):
count=len(array)
data=0
if (n<=(count-1)):
data=array[n]**n
else:data=-1
return data

15.Right to Left------------------------------------------ ----------------------------------------

You are given a sequence of strings. You should join these strings into chunk of text where the initial strings are separated by commas. As a joke on the right handed robots, you should replace all cases of the words "right" with the word "left", even if it's a part of another word. All strings are given in lowercase.

Input: A sequence of strings as a tuple of strings (unicode).

Output: The text as a string.

Example:

left_join(("left", "right", "left", "stop")) == "left,left,left,stop"
left_join(("bright aright", "ok")) == "bleft aleft,ok"
left_join(("brightness wright",)) == "bleftness wleft"
left_join(("enough", "jokes")) == "enough,jokes"


def left_join(phrases):
str = ','
str=str.join(phrases)
str=str.replace('right', 'left')
return str


16.Digits Multiplication------------------------------------------ ----------------------------------------

You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.

For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).

Input: A positive integer.

Output: The product of the digits as an integer.

Example:

checkio(123405) == 120
checkio(999) == 729
checkio(1000) == 1
checkio(1111) == 1

def checkio(number):
n = number
cal = 1
while n >= 1:
if n % 10 == 0:
n = int(n / 10)
continue

else:
cal *= n % 10
n = int(n / 10)
return cal

17.Number Base------------------------------------------ ----------------------------------------

Watch out for cases when the number cannot be converted. For example: "1A" cannot be converted with radix 9. For these cases your function should return -1.

Input: Two arguments. A number as string and a radix as an integer.

Output: The converted number as an integer.

Example:

checkio("AF", 16) == 175
checkio("101", 2) == 5
checkio("101", 5) == 26
checkio("Z", 36) == 35
checkio("AB", 10) == -1

def checkio(str_number, radix):
try:
except:
return -1

18.Absolute sorting------------------------------------------ ----------------------------------------

The array (a tuple) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple.

Precondition: The numbers in the array are unique by their absolute values.

Input: An array of numbers , a tuple..

Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.

Addition: The results of your function will be shown as a list in the tests explanation panel.

Example:

checkio((-20, -5, 10, 15)) == [-5, 10, 15, -20] # or (-5, 10, 15, -20)
checkio((1, 2, 3, 0)) == [0, 1, 2, 3]
checkio((-1, -2, -3, 0)) == [0, -1, -2, -3]

def checkio(numbers_array):
numbers_array=sorted(numbers_array,key=lambda x:abs(x))
return numbers_array

19.The Most Frequent------------------------------------------ ----------------------------------------

You have a sequence of strings, and you’d like to determine the most frequently occurring string in the sequence.

Input: a list of strings.

Output: a string.

Example:

most_frequent([
    'a', 'b', 'c',
    'a', 'b',
    'a'
]) == 'a'
most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'

from collections import Counter  '百度下Counter的用法'
def most_frequent(data):
word_counts = Counter(data)
top = word_counts.most_common(1)
return top[0][0]

20.Easy Unpack------------------------------------------ ----------------------------------------

Your mission here is to create a function that gets an tuple and returns a tuple with 3 elements - first, third and second to the last for the given array

Input: A tuple, at least 3 elements long.

Output: A tuple.

Example:

easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
easy_unpack((6, 3, 7)) == (6, 7, 3)

def easy_unpack(elements):
"""
returns a tuple with 3 elements - first, third and second to the last
"""
return (elements[0], elements[2], elements[-2])

21.Date and time convertor------------------------------------------ ----------------------------------------

Computer date and time format consists only of numbers, for example: 21.05.2018 16:30
Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes
Your task is simple - convert the input date and time from computer format into a "human" format.

Input: Date and time as a string

Output: The same date and time, but in a more readable format

Example:

date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes"
date_time("19.09.2999 01:59") == "19 September 2999 year 1 hour 59 minutes"
date_time("21.10.1999 18:01") == "21 October 1999 year 18 hours 1 minute"
NB: words "hour" and "minute" are used only when time is 01:mm (1 hour) or hh:01 (1 minute).
In other cases it should be used "hours" and "minutes".

def date_time(time):
data=time.split()
d1=data[0].split('.')
d2=data[1].split(':')
dic={'01':'January','02':'February','03':'March','04':'April','05':'May','06':'June','07':'July',}
hour=d2[0]+' hours '
minu=d2[1]+' minutes'
if d2[0]=='01':
hour='1 hour '
if d2[1]=='01':
minu='1 minute'
str1=dic[d1[1]]
result=d1[0]+' '+str1+' '+d1[2]+' year '+hour+minu
return result

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120