Python -使用most_common的预期列表与针对数字频率较低给出的列表不同

neskvpey  于 2022-12-15  发布在  Python
关注(0)|答案(6)|浏览(148)

这是给出的问题

Define a function called 'stringmethod ; which takes five parameters. 
        • The first parameter is para, which takes a string sentence. 
        • The second parameter is speciall, which takes a string of special characters. 
        • The third parameter is speciall, which takes a single string of special characters. 
        • The fourth parameter is listl, which takes a list of strings. 
        • The fifth parameter is strfind, which takes a string. 

The function definition code stub is given in the editor. Generate print statements based on the following conditions: 
        • Remove all the special characters from para specified in speciall and save them in the variable wordl. 
        • Get the first 70 characters from words, reverse the strings, save it in variable rword2, and print it. 
        • Remove all the wide spaces from rword2, join the characters using the special character specified in speciall, and print the joint string. 
        • If every string from listl is present in para, then format the print statement as follows: 
           o "Every string in {listl } were present" 
        • else 
          o "Every string in {listl } were not present" 
        • Split every word from wordl and print the first 20 strings as a list. 
        • Calculate the less frequently used words whose count < 3. and print the last 20 less frequent words as a list. • Print the last index in wordl, where the substring strfind is found. 
        
       Input Format for Custom Testing 
        • In the first line, the string 'para' is given. 
        • In the second line, the string 'speciall is given. 
        • In the third line, the string 'special2' is given. 
        • The fourth line contains an integer a the size of the listl. 
        • In the next line, strfind is given.

下面是修改后的查询,我把整个程序放在我为查询编写的地方。

import math
import os
import random
import re
import sys


#
# Complete the 'strmethod' function below.
#
# The function accepts following parameters:
#  1. STRING para
#  2. STRING spch1
#  3. STRING spch2
#  4. LIST li1
#  5. STRING strf
#

from collections import Counter
def stringmethod(para, special1, special2, list1, strfind):
    word1 = ''.join(i for i in para if not i in special1)

    word2 = word1[69::-1] 
    print(word2)
    
    rem=word2.replace(" ","")
    sp=special2.join(rem)
    print(sp)
    
    if all(x in para for x in list1): 
        print("Every string in  {} were present" .format(list1) ) 
    else: 
        print("Every string in {} were not present " .format(list1)) 
    
    sp2 = word1.split()
    print(sp2[0:20])

    l = list(word1.split())
            
    sorted_items = [w for w, _ in Counter(l).most_common()]
    print(sorted_items[-20:])

    print(word1.rindex(strfind))

if __name__ == '__main__':
    para = input()

    spch1 = input()

    spch2 = input()
    
    qw1_count = int(input().strip())

    qw1 = []

    for _ in range(qw1_count):
        qw1_item = input()
        qw1.append(qw1_item)

    strf = input()

    stringmethod(para, spch1, spch2, qw1, strf)

以下是提供的输入

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sem odio, varius nec aliquam nec, tempor commodo ante. Pellentesque sit amet augue vel ante dictum placerat ut ut sapien. Proin maximus eu diam in posuere. Suspendisse in lectus in lectus finibus auctor. Nam sed porttitor arcu. Vestibulum augue odio, posuere quis libero sed, pharetra sollicitudin est. Donec sit amet nunc eu nisi malesuada elementum id ut purus.Nunc sit amet % massa rhoncus, venenatis eros sit amet, ornare augue. Nunc a mi sed est tincidunt facilisis at nec diam. Donec nec ex lorem. Morbi vitae diam tincidunt, dignissim arcu ut, facilisis nisi. Maecenas non felis #ullamcorper, viverra augue id, consequat_nunc. Suspendisse potenti. Proin tempor, sapien ut ornare placerat, sapien mauris luctus sapien, eget aliquam turpis urna at quam. Sed a&eros vel@ ante vestibulum vulputate. Suspendisse vitae vulputate velit. Suspendisse! ligula nisl, semper ut sodales et, ultricies porttitor felis. Nunc ac mattis erat, aliquet pretium risus. Nullam quis congue lacus, et mollis nulla. Nunc laoreet in nisi sit amet facili*sis. Cras rutrum justo ut eros mollis volutpat. Sed quis mi nunc. Nunc sed bibendum nibh, quis bibendum tortor.
,_!@*%#$.
,
3
adipiscing
Aliquam
Suspendisse
vulputate

我得到了下面的结果,你可以看到所有的匹配,除了20个不常用的单词部分。

ido mes mauqilA tile gnicsipida rutetcesnoc tema tis rolod muspi meroL
i,d,o,m,e,s,m,a,u,q,i,l,A,t,i,l,e,g,n,i,c,s,i,p,i,d,a,r,u,t,e,t,c,e,s,n,o,c,t,e,m,a,t,i,s,r,o,l,o,d,m,u,s,p,i,m,e,r,o,L
Every string in  ['adipiscing', 'Aliquam', 'Suspendisse'] were present
['Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'Aliquam', 'sem', 'odio', 'varius', 'nec', 'aliquam', 'nec', 'tempor', 'commodo', 'ante', 'Pellentesque', 'sit']
['semper', 'sodales', 'ultricies', 'ac', 'mattis', 'erat', 'aliquet', 'pretium', 'risus', 'Nullam', 'congue', 'lacus', 'nulla', 'laoreet', 'Cras', 'rutrum', 'justo', 'volutpat', 'nibh', 'tortor']
851

而他们需要的输出是

['ultricies', 'ac', 'mattis', 'erat', 'aliquet', 'pretium', 'risus', 'Nullam', 'congue', 'lacus', 'mollis', 'nulla', 'laoreet', 'Cras', 'rutrum', 'justo', 'volutpat', 'bibendum', 'nibh', 'tortor']

而我有如下,这似乎并不正确

['semper', 'sodales', 'ultricies', 'ac', 'mattis', 'erat', 'aliquet', 'pretium', 'risus', 'Nullam', 'congue', 'lacus', 'nulla', 'laoreet', 'Cras', 'rutrum', 'justo', 'volutpat', 'nibh', 'tortor']
inn6fuwd

inn6fuwd1#

这个问题是错误的本身在黑客等级尝试下面的代码,它将通过所有的测试用例。在黑客等级的原始条件是小于3,但它应该小于13,然后只有你可以通过所有的测试用例,因为单词'ac'是重复7次

import math
import os
import random
import re
import sys

def stringmethod(para, special1, special2, list1, strfind):
    word1=para
    for i in special1:
        word1=word1.replace(i,'')
    word2=word1[0:70]
    word2=word2[-1:-71:-1]
    print(word2)
    l=special2.join(list(word2.replace(" ",'')))
    print(l)
    count=0
    for i in list1:
        if (i in para):count+=1
    if count==len(list1):
        print("Every string in ",list1,"were present")
    else:print("Every string in ",list1,"were not present")
    print(word1.split()[0:20])
    list2=list()
    freq=[]
    for i in word1.split(" "):
        if word1.count(i)<13:
            if i in freq:pass
            else:freq.append(i)
    list2=freq[-1:-21:-1]
    print(list2[-1:-21:-1])
    print(word1.rindex(strfind))
    # Write your code here

if __name__ == '__main__':
    para = input()

    spch1 = input()

    spch2 = input()
    
    qw1_count = int(input().strip())

    qw1 = []

    for _ in range(qw1_count):
        qw1_item = input()
        qw1.append(qw1_item)

    strf = input()

    stringmethod(para, spch1, spch2, qw1, strf)
bvuwiixz

bvuwiixz2#

一些调整

def stringmethod(para: str, special1: str, special2: str, list1: list, strfind: str):
    tpara = para

    """
    Remove all the special characters from para specified in special1 and save them in the variable word1.
    Get the first 70 characters from word1, reverse the strings, save it in variable rword2, 
    and print it.
    """
    for symbol in special1:
        tpara = tpara.replace(symbol, '')
    word1 = tpara
    rword2 = word1[0:70]
    rword2 = rword2[::-1]
    print(rword2)

    """
    Remove all the wide spaces from rword2, join the characters using the special 
    character specified in special2, and print the joint string.
    """
    rword3 = special2.join(rword2.replace(" ", ''))
    print(rword3)

    """
    If every string from list1 is present in para, then format the print statement as follows:
    "Every string in {list1} were present"
    else"Every string in {list1} were not present"
    """

    status = True
    for pattern in list1:
        if pattern not in para:
            status = False
            break

    if status == True:
        print("Every string in", list1, "were present")
    else:
        print("Every string in", list1, "were not present")

    """
    Split every word from word1 and print the first 20 strings as a list.
    Calculate the less frequently used words whose count < 13**. and print the last 20 less frequent 
    words as a list.

    *** Note: Count the words in the order that they appear
    """

    spitted_word = word1.split(' ')
    first_20 = spitted_word[:20]
    print(first_20)

    less_freq_word_lists = []

    for word in spitted_word:
        if word1.count(word) < 13:
            if word not in less_freq_word_lists:
                less_freq_word_lists.append(word)

    print(less_freq_word_lists[-20:])

    """
    Print the last index in word1, where the substring strfind is found.
    """
    print(word1.rfind(strfind))
sqyvllje

sqyvllje3#

尝试以下代码

number=word1
splitAll = number.split()
print(splitAll[0:20])
mylist=[]
myDict = dict()
for t in splitAll:
    myDict[t]=myDict.get(t,0)+1
for x,y in myDict.items():
    if(y<3):
        mylist.append(x)
print(mylist[-20:])

请参考博客的完整解释:Here

qpgpyjmq

qpgpyjmq4#

尝试以下代码

import math
import os
import random
import re
import sys

from collections import Counter
def stringmethod(para, special1, special2, list1, strfind):
    # Write your code here
    word1 = ''.join([i  for i in para if i not in special1] )
    # print( special1)
    rword2 = word1[:70]
    rword2 = rword2[::-1]
    print(rword2)
    
    rjoin = special2.join(rword2.replace(" ",""))
    print(rjoin)
    
    if all(  x in para for x in list1  ):
        print(f"Every string in  {list1} were present")
    else:
        print(f"Every string in  {list1} were not present")
    
    a = word1.split()
    print(a[:20])
    
    l = word1.split()
    f = Counter(l)
    temp =[]
    for k,v in f.items():
        if  v < 3:
            temp.append(k)
    print(temp[-20:])
    
    print(word1.rfind(strfind))
tzxcd3kk

tzxcd3kk5#

import math
import os
import random
import re
import sys
def stringmethod(para, special1, special2, list1, strfind):
for i in range(len(special1)):
    para=para.replace(special1[i],'')

word1=para
rword2=word1[69::-1]
print(rword2)
print(special2.join(rword2.replace(' ','')))
a=True
for i in list1:
    if i in para:
        a=True
    else:
        a=False
        
if a:
    print(f'Every string in {list1} were present')
else:
    print(f'Every string in {list1} were not present')
        
l1=word1.split()
print(l1[0:20])

l2=list()

for i in l1:
    if l1.count(i) < 3 and i not in l2: 
        l2.append(i)
        
print(l2[-20:])
print(word1.rfind(strfind))
cld4siwp

cld4siwp6#

对我来说这下面是运行良好
定义字符串方法(帕拉、特殊1、特殊2、列表1、字符串查找):

word1 = ''.join(i for i in para if not i in special1)
rword2 = word1[:70][::-1] 
print(rword2)

temp =rword2.replace(" ","").strip()
temp =special2.join(temp)
print(temp)

if all(x in para for x in list1): 
    print("Every string in  {} were present" .format(list1) ) 
else: 
    print("Every string in {} were not present " .format(list1)) 
    
s =word1.split()
print(s[:20])

un_lst=[]
fnl_lst=[]
for i in s:
    if i not in un_lst:
        un_lst.append(i)
        
for i in un_lst:
    s.count(i)<3:
        fnl_lst.append(i)
print(fnl_lst[-20:])

print(word1.rindex(strfind))

如果名称==“”:帕拉=输入()

spch1 = input()

spch2 = input()

qw1_count = int(input().strip())

qw1 = []

for _ in range(qw1_count):
    qw1_item = input()
    qw1.append(qw1_item)

strf = input()

stringmethod(para, spch1, spch2, qw1, strf)

相关问题