Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

주어진 문자를 사용하여 가능한 단어를 인쇄하는 Python 프로그램

<시간/>

이 튜토리얼에서는 주어진 문자로 가능한 모든 단어를 찾을 것입니다. 더 나은 이해를 위해 몇 가지 테스트 사례를 살펴보겠습니다.

Input:
words = ["hi", "hello", "bye", "good"]
characters = ["h", "i", "b", "y", "e"]
Output:
hi
bye

목표를 달성하기 위해 다음 단계를 따르십시오.

알고리즘

1. Initialize the words and characters list.
2. Write a function which returns a dictionary containing a count of each char of the word.
   2.1. Initialise an empty dictionary.
   2.2. Iterate through the word, and increment char count by one if already present else initialise it with one.
   2.3. After the loop return dictionary.
3. Iterate through the words list.
   3.1. Initialise a variable flag with 1.
   3.2. Find char count with the help of above function and store it in a variable.
   3.3. Iterate through the above-returned dictionary.
      3.3.1. Check whether the key is in the characters or not.
         3.3.1.1. If not present, make the flag to zero.
      3.3.2 Else check for the equality count of character in characters and dictionary.
         3.3.2.1. If not equal, make a flag to zero.
3.4. If the flag is equal to one.
   3.4.1. Print the word.

위의 알고리즘을 구현해보자.

예시

## initializing the lists
words = ["hi", "hello", "bye", "good"]
characters = ["h", "i", "b", "y", "e"]
## function which returns dictionary containing char counts
def char_count(word):
   ## initializing an empty dictionary
   char_count = {}
   ## loop to find the frequency of the chars
   for char in word:
      ## incrementing the char count by one
      char_count[char] = char_count.get(char, 0) + 1
   ## returning dictionary
   return char_count
## iterating through the words list
for word in words:
   ## initializing flag to one
   flag = 1
   ## getting the char count using char_count() function
   chars = char_count(word)
   ## iterating through the chars
   for key in chars:
      ## checking for the presence of key in the characters
      if key not in characters:
         ## updating the flag value to zero
         flag = 0
      else:
         ## comparing the count of chars in chars and characters
         if characters.count(key) != chars[key]:
            ## updating the flag value to zero
            flag = 0
      ## checking the flag value
      if flag == 1:
         print(word)

출력

위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

hi
bye

결론

튜토리얼에 대해 궁금한 점이 있으면 댓글 섹션에 언급하세요.