itertools-combinations_with_replacement |HackerRank

admin
By -
0

 This problem far simple then combinations once here we just need to use combination_with_replacment of itertools  which take two  argument  one is items to  be paired and second  r, which is tuples.

here we just called that function and pass our values to  it we are sorted our S so  we can get combinations for sorted item ,  and we taking loop help to print each pair its als give use repeated set  

lie ABCD it be AA, AB, BB, AC , AD, DD,CC etc




The code generates all possible combinations with replacement of length k from a sorted string S.

  1. It first reads the input string S and the integer k (which specifies the length of the combinations).

  2. The string S is sorted to ensure combinations are generated in lexicographical order.

  3. Using the combinations_with_replacement function from the itertools module, it generates combinations of length k, allowing repeated characters.

  4. Finally, it prints each combination as a string, where each combination is a tuple of characters.


Problem:https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem?isFullScreen=true


Code:

# Enter your code here. Read input from STDIN. Print output to STDOUT

#Naive Code:

S,k=input().split()
from itertools import combinations_with_replacement
S=sorted(S)
# ls_tuples = list(combinations_with_replacement(S,int(k)))
# for x in ls_tuples:print("".join(x))
for x in combinations_with_replacement(S, int(k)):
    print("".join(x))

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*