RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-362254

андрей марченков's questions

Martin Hope
андрей марченков
Asked: 2025-04-14 23:27:53 +0000 UTC

附加限制 - 仅 1 行!我不明白需要什么 - 一行代码还是一行函数输出,或者其他什么!

  • 1

任务:https://www.codewars.com/kata/535742c7e727388cdc000297/train/python

您需要生成一副 52 张牌的牌 - 四种花色,每花色 13 张牌。
牌的等级是:A、二、三、四、五、六、七、八、九、十、J、Q、K

结论应该是这样的

地图的每一行都将采用以下格式

"ace of hearts"  
"ace of spades"  
"ace of diamonds"  
"ace of clubs"

他们不必按顺序进行。

附加限制 - 仅一行

一行代码不通过

import random
dict_card_format = {1: "hearts", 2: "spades", 3: "diamonds", 4: "clubs"}
dict_rank = {1: "ace", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven",
             8: "eight", 9: "nine", 10: "ten", 11: "jack", 12: "queen", 13: "king"
             }

nums = list(range(1, 5))
random.shuffle(nums)
nums1 = list(range(1, 14))                                                                         
random.shuffle(nums1)

def deck_of_cards():
     return [f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])}" for j in nums1 for i in nums]

由 CodesWars 服务器发布

Test Results:
  Code lines
    Tests
       1 line only!: 13 should equal 1  - этот Тест не проходит
Completed in 0.09ms
Completed in 0.14ms
Sample tests                            - этот Тест проходит
    Tests

如果单行代码不起作用,那么如何在一行中输出函数输出?

我尝试用不同的方式写它

def deck_of_cards(): 
    n_card_format = 4
    n_rank = 13        
    nums = list(range(1, 5))                                                    
    random.shuffle(nums)
    card_format = nums[:4]                                                                            
    nums1 = list(range(1, 14))                                                                          
    random.shuffle(nums1)
    rank_list = nums1[:13] 

    # s = ""
    lst = []
    for i in card_format:
        for j in rank_list:
            if i in dict_card_format and j in dict_rank:
                lst.append(f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])}")
                # lst.append(''.join(dict_rank[j]) + " " + "of" + " " + ''.join(dict_card_format[i]))
                # s += (''.join(dict_rank[j]) + " " + "of" + " " + ''.join(dict_card_format[i]) + " ")
                # s += "\n"f"{''.join(dict_rank[j])} of {''.join(dict_card_format[i])} "
    return lst 

帮我找到正确的解决方案

python
  • 2 个回答
  • 73 Views
Martin Hope
андрей марченков
Asked: 2024-02-16 07:05:37 +0000 UTC

计算文本中的单词数(使用更正的代码并添加已提出的问题“计算文本中的单词数”)

  • 5

我修改后的解决方案是这样的:我们用文字将其分解 - 我们删除所有不必要的内容。在循环中,我们检查该单词是否被禁止并增加计数器 - 我们还添加了禁止单词,将其翻译为大写()和一个空格并将其放入集合中

我收到这样的提示:方向是由Enikeyshchik指示的,但是单词可以以大写字母开头,例如“and”和“And”是不同的单词。

import codewars_test as test

import re

except_word = {"a", "the", "on", "at", "of", "upon", "in", "as",
               "A", "The", "On", "At", "Of", "Upon", "In", "As", ""
               }


def word_count(s):
    all_word = re.sub(r'([^A-Za-z]+)', r' ', s).split(' ')
    cnt = 0
    for word in all_word:
        if word in except_word:
            continue
        else:
            cnt += 1
    return cnt


if __name__ == '__main__':
    test.assert_equals(word_count("hello there"), 2)
    test.assert_equals(word_count("hello there and a hi"), 4)
    test.assert_equals(word_count("I'd like to say goodbye"), 6)
    test.assert_equals(word_count("Slow-moving user6463 has been here"), 6)
    test.assert_equals(word_count("%^&abc!@# wer45tre"), 3)
    test.assert_equals(word_count("abc123abc123abc"), 3)
    test.assert_equals(word_count("Really2374239847 long ^&#$&(*@# sequence"), 3)

    long_text = r"""
            I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.
            """

    test.assert_equals(word_count(long_text), 112)

现在我的函数可以生成基本测试的正确答案

来自服务器的随机测试未通过,与所有其他随机测试一样,结果总是多 1 个单词

st = """R;!GV9sZrD 5x=jncajkU Z#0qd' rR"8oeAy:; IO$"EhYI), NG("Cy28 +ix>i kq&rV/ ',Sl[PL~ Ae/[< \-T<:/ D-$W9p5,Qh yF)DFS XFR@x{8[. L+(]M-cW J+i~E =g5B"1rGoM @c*ByGCt _2amHl =Y8f*E) P_F}01o t}1q!+A@| B3"S;; dP..'U >FqS>4D(S %rf/# =jB$+F<M G$:|K"rJn m92Fkv I^xuZ )s@~R65W x(;~$DWj,J auRs^b S*H-Y]FV T~PS*F8} OA<<qt n]`wK:ED }^B)]! kD[&y uwb_1nY&(F 7_K"c\T 7G0](BA3 ?UpyrP"Y5) @rTKasu`J uk,HFb^{ }IE|N L>$lwGtd dfQ;[.O}zY S`y/$ <\pzJ2\( S+g0IZ /9QKZ29BC jy3b%0KZb~ Eb"192nt Q8^[| <EZ'oN K8~uLh>Z?N KF*8,s3u C<4lxn%> sFARC r_s?Q~,)9y W)q=oQK]cK ?n^k}qwECZ I#@9CF "T1w@ &j(QfUio :O"m~{ <\&rxFVI !k9(Eq} Ezhc_="""
Правильный ответ с сайта 159 у меня 160

st = """"&p!2g Nz"E{ 0=cfc;*^{U bPf<:n/ 1>?j!#+|Ww kQsGs}] }48%s W?Kk4RdIK+ WCtv~_ t_.q4-! #%~=K /[r/,t#Se 1:fyl: KZx,o9 2*W[hp>X0" L0u0oFBY @"wHc bgRTj ,~OXJWt.Z jY*k2S:L x/jF>_#QRX Va(A/3 {4f32ZC|s 'f1MsZRK s+y@i lU<keS4! c!sA&i| rS'+-oNOj ']OzY?e# NDU!Sd) k5z#!n<4 p]kD,X5 c}aY|1"J ^KF}4sl ailA6Uw>$8 W{aA5ON~} 2}<C"p T&+h?\Y {Y9E$;4/.k GDYYXcK` ][h!l>*o!` &0?ST%v @+9T'-0F5U {Wh&ye:7 9CF0"n3 Nw/,L=+qK :jTZ;b,. wb=i_d5F i:(WF1 e;>9`#ToF ~z~-/ <uN], jc0[p$f3I r9M;Vm|%p 0)0<PS< CUtg2Gl@$ nnL]'O?N>C O9`YU 730|Y K!Sx,JL""""

服务器的答案是 134 - 我有 135 - 对于所有随机测试都是如此

请解释一下,这是什么原因?就好像我忘记删除某些东西(我不明白是什么)。

python-3.x
  • 1 个回答
  • 24 Views
Martin Hope
андрей марченков
Asked: 2024-02-15 23:56:33 +0000 UTC

计算文本中的单词数

  • 5

这个网站上有一个任务:统计单词数。单词被认为是英文字母字符的连续序列(从 A 到 z)。
以下是示例:

Hello there, little user5453 374 ())$. I’d been using my sphere as a stool. Slow-moving target 839342 was hit by OMGd-63 or K4mp. 
contains "words" 
['Hello', 'there', 'little', 'user', 'I', 'd', 'been', 'using', 'my','sphere', 'as', 'a', 'stool', 'Slow', 'moving', 'target', 'was', 'hit', 'by', 'OMGd', 'or', 'K', 'mp']

有些词应该被排除。这些话是:

"a", "the", "on", "at", "of", "upon", "in" and "as", case-insensitive.

我的解决方案是这样的:
我们用文字来分解它——我们删除所有不必要的东西。在循环中,我们检查该单词是否被禁止或为空字符串并增加计数器

import codewars_test as test
import re

except_word = ["a", "the", "on", "at", "of", "upon", "in", "as"]


def word_count(s):
    all_word = re.sub(r'([^A-Za-z]+)', r' ', s).split(' ')
    print(all_word)
    cnt = 0
    for word in all_word:
        if word in except_word or word == '':
            continue
        else:
            cnt += 1
    return cnt

if __name__ == '__main__':
    test.assert_equals(word_count("hello there"), 2)
    test.assert_equals(word_count("hello there and a hi"), 4)
    test.assert_equals(word_count("I'd like to say goodbye"), 6)
    test.assert_equals(word_count("Slow-moving user6463 has been here"), 6)
    test.assert_equals(word_count("%^&abc!@# wer45tre"), 3)
    test.assert_equals(word_count("abc123abc123abc"), 3)
    test.assert_equals(word_count("Really2374239847 long ^&#$&(*@# sequence"), 3)

    long_text = r"""
            I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.
            """

    test.assert_equals(word_count(long_text), 112)

基本测试:

        test.assert_equals(word_count("hello there"), 2)
        test.assert_equals(word_count("hello there and a hi"), 4)
        test.assert_equals(word_count("I'd like to say goodbye"), 6)
        test.assert_equals(word_count("Slow-moving user6463 has been here"), 6)
        test.assert_equals(word_count("%^&abc!@# wer45tre"), 3)
        test.assert_equals(word_count("abc123abc123abc"), 3)
        test.assert_equals(word_count("Really2374239847 long ^&#$&(*@# sequence"), 3)

该函数通过了所有基本测试,但不会在长文本上产生正确的答案,
这是一个基本示例:

Example Input 2

I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.

Example Output 2

112

我的函数返回 113 也许我对任务的理解不正确(翻译自 Google)?在服务器上的随机测试中,我的解决方案总是产生 1 到 3 个额外的单词。

请解释一下,这是什么原因?就好像我忘记删除某些东西(我不明白是什么)。

python
  • 1 个回答
  • 51 Views
Martin Hope
андрей марченков
Asked: 2024-02-06 18:01:03 +0000 UTC

如何在不使用替换的情况下从python字符串中删除不必要的字符 - 使用正则表达式

  • 5

任务如下:创建一个函数,给出一个字符串,仅存储字母 A-Z(大小写)、0-9 数字和空格字符。如果记录类型不是字符串,还返回“不是字符串!”。我创建了这样一个函数 - 它通过了所有测试

Вот тестовые строки
'\x0c3U\x0c P \' /j<c\t M+# ~ \x0bh ^m ?g?-\t#-t +m"0\x0cjvk Ez'
'><#qY= / YbxSltf? GIi(+dl\r .?%E4\r?2\r D'
'r%Q 0 \x0cIYpK IssqER%. ;<*/\x0c9l bC8\'[:\x0b|Z EX!R{" BWP(xTn [B >'

import re
def nothing_special(st):
    if not isinstance(st, str):
        return "Not a string!"
    pattern = r'[A-Za-z0-9 /\n/\t/\r/\x0b/\x0c]'
    st = st.replace('/', '')
    match = re.findall(pattern, re.escape(st))
    if match:
        res = ''.join(match)
        return res
    return ''

无法从创建的正则表达式中删除“斜杠”

我必须使用 st = st.replace('/', '') 告诉我如何在正则表达式中执行此操作!是否可以删除以下字符:

/ просто "слеш"
/\n/\t/\r/\x0b/\x0c  - без экранирования
перенос строки
вертикаль. табуляцию
каретку
нечитаемые символы
python
  • 1 个回答
  • 40 Views
Martin Hope
андрей марченков
Asked: 2024-01-11 17:24:55 +0000 UTC

fst 是一个变量 f 的函数,应用于字符串 s (fst 是两个函数 Vertmirror 或 Hormirror 之一)bash 中的示例

  • 5

Codewars 的分配https://www.codewars.com/kata/56dbe0e313c2f63be4000b25/train/shell 如果我理解正确,下面写的应该理解为 oper(fct, s) - 我很困惑该函数的参数是写在括号中 - 但这是 bash,参数不是以这种方式传递的(可能是为了澄清而写的???)

其中“fct”是我编写的函数 - $1 “s”是测试的行 - $2

这是我的“脚本”

#!/bin/bash

vertMirror() {
    vert_str=""
    str=$(echo "$2" | tr "," " ")
    for word in $str
    do
        rev_str=$(echo "${word}" | rev)
        vert_str+="${rev_str}\r"

    done
    echo "${vert_str%??}"
}


horMirror() {
    hor_st=""
    str=$(echo "$2" | tr "," " ")
    declare -a array
    array=($(echo ${str}))
    count=${#array[*]}  
    for ((i=count -1;i>=0;i--)); do
        hor_st+="${array[i]}\r"
    done
    echo "${hor_st%??}"

}

但在这里我不知道如何运行整个脚本 - 我在 oper() 中编写了这些行。来自服务器的响应 --- 空行。我错误地将它分配给函数变量??? 我不知道oper()中需要写什么

oper() {
   fct=$(vertMirror "$2") # vertMirror "$2"
   fct=$(horMirror "$2")  # horMirror "$2"
   
}
oper $1 $2

Подскажите пожайлуста "куда или как копать!!!!"

bash
  • 1 个回答
  • 37 Views
Martin Hope
андрей марченков
Asked: 2023-01-29 18:09:13 +0000 UTC

如何禁用 PyCharm 中的“黄灯”

  • 5

如何在 PyCharm 中禁用“黄灯”工具提示

python
  • 1 个回答
  • 38 Views
Martin Hope
андрей марченков
Asked: 2022-04-04 04:20:39 +0000 UTC

无法安装 cpmoptimize 库

  • 0
Зашёл на вот этот сайт

https://habr.com/ru/post/236689/

И там 
Ссылки для скачивания
Установить библиотеку можно с помощью pip:
sudo pip install cpmoptimize
Исходный код библиотеки с примерами доступен на github под свободной лицензией MIT.
UPD. Пакет опубликован в Python Package Index
Мои версии (python3.7 в Thonny), python3.8, (python3.9 в Pycharm)
Моя команда sudo pip3 install cpmoptimize
Пробовал во всех редакторах загрузить но получаю одну и туже ошибку

Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-oam94xh5/byteplay/setup.py", line 4, in <module>
        from byteplay import __version__ as lib_version
      File "/tmp/pip-install-oam94xh5/byteplay/byteplay.py", line 181
        raise ValueError, "Opcode stack behaviour depends on arg"
                        ^
    SyntaxError: invalid syntax
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-oam94xh5/byteplay/

Посмотрел на GitHub файл byteplay.py где указывается на запятую.
Обновлял  python -m pip install --upgrade pip 
Пробовал git clone https://...... и запустить из папки cpmoptimize файл установки но тоже не 
помогло

Подскажите как установить данный пакет-библиотеку
python
  • 1 个回答
  • 10 Views
Martin Hope
андрей марченков
Asked: 2022-03-23 21:53:05 +0000 UTC

不使用len(),所有模块都是可插拔的,还有 //, %, &, >>, <<, 写一个从第2个CC到第16个的转换函数,反之亦然

  • 0

来自 Codewars 网站的任务 https://www.codewars.com/kata/55d1b0782aa1152115000037/train/python

Короче нужна функция конвертации (я нашёл несколько разных решений
данной ката и сам написал код) но вот в чём БЕДА.Автор Ката в конце
задания приписал как бы вскользь следующее "О, и я отключил несколько
вещей."
При проверке кода на сервере оказалось что нельзя использовать bin(), hex() и другие функции прописал в вопросе их

我不得不寻求帮助,因为我移交给服务器并且它是这样到达的

function has been disabled for this Kata
STDERR
Traceback (most recent call last):
  File "main.py", line 3, in <module>
  File "/home/codewarrior/solution.py", line 16, in bin_to_hex
TypeError: unsupported format string passed to NoneType.__format__

Вот перевод задания через Google

Определите две функции: hex_to_bin и bin_to_hex (или hextobin и binthex)
hex_to_bin.
Принимает шестнадцатеричную строку в качестве аргумента.
Примечание. Эта строка может содержать верхние или нижние буквы и начать с любого количества нулей.
Возвращает двоичное представление (без ведущих нулей) численного значения шестнадцатеричной строки.
Примеры:
"00f" -> "1111"
"5" -> "101"
"00000" -> "0"
"04d2" -> "10011010010"
bin_to_hex.
Берет двоичную строку (с ведущими нулями или без него) в качестве аргумента.
Возвращает шестнадцатеричное представление численного значения двоичной строки.
Примечание. Любые не численные символы должны быть строчными
Примеры:
"1111" -> "f"
"000101" -> "5"
"10011010010" -> "4d2"
Примечание. Вы можете предположить, что все аргументы действительны, так что нет необходимости в проверке ошибок.

О, и я отключил несколько вещей.

За качество перевода не ручаюсь.
Может не понял задание до конца - но все таки интересно как без
"завсегдашных-друзей-инструментов" наших операторов, встроенных функций решить задание
Примеры кода с перечисленными операторами и встроенными функциями не предлагать!
Я вроде все проверил - но попробуйте сдать на сайте Codewars
Вот из дискуссии с сайта некоторые высказывания:
В Python:
int отключен, но тип (0) включен
Hex / Bin отключен, но форматирование строки включено

Описание не говорит, какие функции отключены.
python-3.x
  • 1 个回答
  • 10 Views
Martin Hope
андрей марченков
Asked: 2022-03-12 02:27:11 +0000 UTC

告诉我如何优化python代码以通过服务器上的随机测试

  • 5
Задача: Создайте функцию, которая принимает положительное целое  число
и возвращает  следующее за представленным большее число,  которое
можно сформировать, переставив его цифры.
Например:    
12 ==> 21   
513 ==> 531   
2017 ==> 2071
Если не получается сформировать число то вернуть -1
Это задание с сайта Codewars.com

https://www.codewars.com/kata/55983863da40caa2c900004e/train/python

这是我的解决方案

def next_bigger(n):
    # Условие для одинаковых цифр типа 1, 2,...111,333,...9999999 
    if str(n).count(str(n)[0]) == len(str(n)):
        return -1
    elif len(str(n)) == 2: # Условие для 2-х цифр
        if n > int(str(n)[::-1]): # для таких чисел 21, 53, 98 - большее число не получить
            return -1
        else:
            return int(str(n)[::-1])
    lst = []
    # Для других чисел производим комбинации и из комбинаций как только найдём
    # первое число больше заданного вставляем его в список и  break
    for el in permutations(str(n), len(str(n))):
        if int(''.join(el)) > n:
            lst.append(int(''.join(el)))
            break
    print(lst)
    if not lst:
        return -1
    return lst[0] 

Базовые тесты проходят все.
А вот случайные --- по времени не проходят
Подскажите пожалуйста!
python
  • 5 个回答
  • 10 Views
Martin Hope
андрей марченков
Asked: 2020-03-10 06:48:32 +0000 UTC

交换两个数组的元素,以便它们的新内容也反转

  • 1

这是一个测试功能

exchange_with(a, b)
Test.assert_equals(a, ["c", "b", "a"])
Test.assert_equals(b,['7', '6', '5', '4', '3', '2', '1']

这是一个例子:

# before

my_list = ['a', 'b', 'c']

other_list = [1, 2, 3]

exchange_with(my_list, other_list)

# after

my_list == [3, 2, 1]

other_list == ['c', 'b', 'a']

任务是写一个函数!这是我的解决方案,但是在被测系统上的测试没有通过

a = ["1", "2", "3", "4", "5", "6", "7"]

b = ['a', 'b', 'c']

def exchange_with(a, b):
    a, b = b[::-1], a[::-1]
    return f"{a},\n {b}"

print(exchange_with(a, b))

这是 print() 的输出

['c', 'b', 'a']

['7', '6', '5', '4', '3', '2', '1']

告诉我我的错误在哪里?

python
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5