TheBeginner
TheBeginner

Reputation: 3

Python - Expected list using most_common is different to the one given for less frequent in number

This is the question given

        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. 
         

Below is the modified query where i have put the entire program where i have written for the query.

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)

Below is the input provided

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

Where i have got the below result , where you can see everything matches, except the 20 less frequently used words part.

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

Whereas the output they need is

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

Whereas i've got as below, which doesn't seem to be incorrect

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

Upvotes: 0

Views: 17798

Answers (7)

Minu
Minu

Reputation: 47

#!/bin/python3

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):
    # Write your code here
    a=para
    b=special1
    word1="".join(i for i in a if i not in b)
    #print(word1)
    c=word1[:70]
    rword2=c[::-1]
    print(rword2)
    d=rword2.replace(" ","")
    newword=special2.join(d)
    print(newword)
    if all(i in para for i in list1):
        print(f'Every string in {list1} were present')
    else:
        print(f'Every string in {list1} were not present')
    l=word1.split()
    print(l[:20])
    f = Counter(l)
    temp =[]
    for k,v in f.items():
        if(v < 3):
            temp.append(k)
    print(temp[-20:])
    print(word1.rfind(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)

Upvotes: 1

Rajneesh Bharti
Rajneesh Bharti

Reputation: 1

#For me this below is running fine

def stringmethod(para, special1, special2, list1, strfind):

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))

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)

Upvotes: 0

Nikhil
Nikhil

Reputation: 1

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))

Upvotes: 0

sounish nath
sounish nath

Reputation: 681

Some tuning

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))


Upvotes: 2

mohan kumar anem
mohan kumar anem

Reputation: 31

The question was wrong itself in hacker rank try the below code it will pass all the test cases. The original condition in hacker rank is less than 3 but it should be less than 13 then only you can pass all the test cases because the word 'ac' is repeating 7 times

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)

Upvotes: 3

Eswar
Eswar

Reputation: 1

Try below code

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))

Upvotes: 0

issuesolver in
issuesolver in

Reputation: 39

Try below code

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:])

Please refer blog for a full explanation: Here

Upvotes: 0

Related Questions