在一句话中找出所有单独的数字并相加 回答:
def sum_numbers(text: str) -> int: # your code here sum = 0 for x in text.split(): if x.isdigit(): sum += int(x) return sum其他人的回答:
def sum_numbers(text: str) -> int: return sum(int(word) for word in text.split() if word.isdigit())将所给数组中的偶数索引相加再与最后的数字相乘,若为空数组,则返回0 回答:
def checkio(array: list) -> int: try: return sum(array[0:len(array):2]) * array[-1] except: return 0将所给字符中的right替换为left 回答:
def left_join(phrases: tuple) -> str: sentence = [x.replace('right', 'left')+',' for x in phrases] sum = '' for x in reversed(sentence): sum = x + sum return sum.rstrip(',')其他人的回答:
def left_join(phrases: tuple) -> str: return ','.join(phrases).replace('right', 'left')判断所给字符是否存在连续的三个英文单词
回答:
def checkio(words: str) -> bool: i = 0 for x in words.split(' '): if x.isalpha(): i += 1 else: i = 0 if i == 3: return True return False找到一句话的第一个单词 回答:
def first_word(text: str) -> str: text = text.strip('... ') for index,alpha in enumerate(text): if alpha.isalpha() == False and alpha != "'" : return text[:index] return text计算两个日期之间所差的天数 回答:
import time import datetime def days_diff(a, b): a, b = [str(x) for x in a], [str(x) for x in b] a[0] = a[0].rjust(4,'0') b[0] = b[0].rjust(4,'0') a, b = '-'.join(a), '-'.join(b) a1 = time.strptime(a, "%Y-%m-%d") b1 = time.strptime(b, "%Y-%m-%d") date1 = datetime.datetime(a1[0], a1[1], a1[2]) date2 = datetime.datetime(b1[0], b1[1], b1[2]) return abs((date2 - date1).days)其他人的回答:
from datetime import datetime def days_diff(date1, date2): return abs((datetime(*date1)-datetime(*date2)).days)找到字符串中的数字的个数 回答:
def count_digits(text: str) -> int: i = 0 try: for x in text: if x.isdigit(): i += 1 return i except: return 0其他人的回答:
def count_digits(text: str) -> int: return len(list(filter(lambda c: c.isdigit(), text)))回答:
def backward_string_by_word(text: str) -> str: text = text.split(' ') text = ' '.join([x[::-1] for x in text]) return text找到前几个价格最高的商品,需要找的个数已经给出。 回答:
def bigger_price(limit: int, data: list) -> list: index = list(x.get('price') for x in data) data = list(zip(index , data)) data.sort(key = lambda x:x[0] , reverse=True) return list(list(zip(*data[0:limit]))[1])其他人的回答:
def bigger_price(limit: int, data: list) -> list: return sorted(data, reverse=True, key=lambda item: item["price"])[0:limit]找到所给两个字符之间的字符串(升级版) 回答:
def between_markers(text: str, begin: str, end: str) -> str: try: return text[text.index(begin)+len(begin):text.index(end)] except: if text.find(begin) == -1 and text.find(end) == -1 : return text.split(' ')[0].strip(begin)+' '+text.split(' ')[-1].rstrip(end) if text.find(begin) == -1: return text.split(' ')[0].strip(end) if text.find(end) == -1: return text.split(' ')[-1].strip(begin)其他人的答案
def between_markers(text: str, begin: str, end: str) -> str: try: if text.index(end) < text.index(begin): return "" except ValueError: pass return text.split(begin)[-1].split(end)[0]删除列表中唯一的数 回答:
def checkio(data: list) -> list: data1 = data.copy() for x in data: if data.count(x) == 1: data1.remove(x) return data1寻找所给单词在指定文段中出现的次数 回答:
def popular_words(text: str, words: list) -> dict: text = text.lower().replace('\n', ' ').split(' ') return {x:text.count(x) for x in words}找到所给字符在字符串中第二次出现的位置 回答:
def second_index(text: str, symbol: str) -> [int, None]: return text.find(symbol,text.find(symbol)+1) if text.find(symbol,text.find(symbol)+1) != -1 else None以元素出现的频率排序 回答:
from collections import Counter def frequency_sort(items): items = [4,6,2,2,2,6,4,4,4] freq = Counter(items) freq = freq.most_common() result = [] for x in freq: for i in range(x[1]): result.append(x[0]) return result其他人的回答:
def frequency_sort(items): return sorted(items, key = lambda x: (-items.count(x), items.index(x)))在棋盘上判断自己有多少个安全的棋子 回答:
def safe_pawns(pawns: set) -> int: square = safe_square(pawns) count = 0 for x in pawns: if x in square: count += 1 return count def safe_square(pawns): square = [unit_capture(x) for x in pawns] return [x for items in square for x in items] def unit_capture(pawn): pawn1 = ord(pawn[0]) capture1 = [chr(pawn1-1),chr(pawn1+1)] pawn2 = ord(pawn[1]) capture2 = chr(pawn2+1) return [x+capture2 for x in capture1]回答:
from dateutil.parser import parse def sun_angle(time): morning = '06:00' now = parse(time) morning = parse(morning) deg_per_sec = 90/21600 if (now-morning).days < 0 or (now-morning).seconds > 43200: return "I don't see the sun!" else: return int((now - morning).seconds * deg_per_sec)可惜checkio不支持dateutil 其他人的回答:
def sun_angle(time): t = int(time[:2]) * 15 + int(time[3:]) / 4 - 90 return t if 0 <= t <= 180 else "I don't see the sun!"所给列表平均分,若列表数量为单数则分开的列表的第一组数据多。若为空集则返回两个空集 回答:
def split_list(items: list) -> list: return [items[:round(len(items)/2 + 0.1)],items[round(len(items)/2 + 0.1):]]确定是否所给列表中的元素全部一致 回答:
def all_the_same(elements: List[Any]) -> bool: try: return elements.count(elements[0]) == len(elements) except: return True回答:
import calendar def date_time(time: str) -> str: day = time.split('.')[0].lstrip('0') month = calendar.month_name[int(time.split('.')[1].lstrip('0'))] year = time.split('.')[2].split(' ')[0]+' '+'year' hour = time.split(' ')[1].split(':')[0] if hour == '00': hour = '0' else: hour = hour.lstrip('0') hour = hour + ' ' + 'hours' if hour != '1' else hour + ' ' + 'hour' minute = time.split(' ')[1].split(':')[1] if minute == '00': minute = '0' else: minute = minute.lstrip('0') minute = minute + ' ' + 'minutes' if minute != '1' else minute + ' ' + 'minute' return ' '.join([day,month,year,hour,minute])其他人的回答:
from datetime import datetime def checkio(time): dt = datetime.strptime(time, '%d.%m.%Y %H:%M') hour = 'hour' if dt.hour == 1 else 'hours' minute = 'minute' if dt.minute == 1 else 'minutes' return dt.strftime(f'%-d %B %Y year %-H {hour} %-M {minute}')-d -H的输出貌似有问题
摩斯解码 回答:
MORSE = {'.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e', '..-.': 'f', '--.': 'g', '....': 'h', '..': 'i', '.---': 'j', '-.-': 'k', '.-..': 'l', '--': 'm', '-.': 'n', '---': 'o', '.--.': 'p', '--.-': 'q', '.-.': 'r', '...': 's', '-': 't', '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x', '-.--': 'y', '--..': 'z', '-----': '0', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9' } def morse_decoder(code): word = code.split(' ') decode = '' for x in word: for y in x.split(' '): decode += MORSE[y] decode += ' ' return decode.rstrip(' ').capitalize()