Skip to content

Commit 153b2bc

Browse files
authored
Merge pull request #103 from dsrao711/issue_101
Python solutions of String Problems in DSA-450
2 parents afd66ad + 8163cb5 commit 153b2bc

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

DSA 450 GFG/CountAndSay.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Problem : https://leetcode.com/problems/count-and-say/
2+
3+
# Input: n = 4
4+
# Output: "1211"
5+
# Explanation:
6+
# countAndSay(1) = "1"
7+
# countAndSay(2) = say "1" = one 1 = "11"
8+
# countAndSay(3) = say "11" = two 1's = "21"
9+
# countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"
10+
11+
# Initialize counter = 1 to store the count of every element
12+
# Initialize o/p string as ret = ""
13+
# If the previous element in the string is equal to the current element in the string , increament the counter
14+
# else Concatenate the count and the previous element of the string in ret
15+
16+
# Return ret
17+
18+
class Solution:
19+
def countAndSay(self, n):
20+
if (n == 1):
21+
return ("1")
22+
23+
s = self.countAndSay(n-1)
24+
25+
ret = ""
26+
cnt = 1
27+
i = 1
28+
while i < len(s) + 1:
29+
if i < len(s) and s[i] == s[i-1]:
30+
cnt += 1
31+
else:
32+
ret += str(cnt) + str(s[i-1])
33+
cnt = 1
34+
i += 1
35+
36+
return (ret)

DSA 450 GFG/PrintAnagrams.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
# Problem : https://practice.geeksforgeeks.org/problems/print-anagrams-together/1
3+
4+
5+
# Input:
6+
# N = 5
7+
# words[] = {act,god,cat,dog,tac}
8+
# Output:
9+
# god dog
10+
# act cat tac
11+
# Explanation:
12+
# There are 2 groups of
13+
# anagrams "god", "dog" make group 1.
14+
# "act", "cat", "tac" make group 2.
15+
16+
from collections import defaultdict
17+
18+
def Anagrams(words,n):
19+
'''
20+
words: list of word
21+
n: no of words
22+
return : list of group of anagram {list will be sorted in driver code (not word in grp)}
23+
'''
24+
25+
#code here
26+
anagrams = defaultdict(list)
27+
28+
for word in words:
29+
anagrams["".join(sorted(word))].append(word)
30+
31+
return anagrams.values()
32+
33+
34+
# Driver Code
35+
36+
if __name__ =='__main__':
37+
t= int(input())
38+
for tcs in range(t):
39+
n= int(input())
40+
words=input().split()
41+
42+
ans=Anagrams(words,n)
43+
44+
for grp in sorted(ans):
45+
for word in grp:
46+
print(word,end=' ')
47+
print()
48+
49+
50+
51+
# Used default dict from collections module . It does not raise key value error

0 commit comments

Comments
 (0)