Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e63c5c8

Browse files
committed
Some Algo Added
1 parent 3649572 commit e63c5c8

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

Other Algorithms/Add_Strings.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
2+
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
3+
4+
#Notes:
5+
#Both num1 and num2 contains only digits 0-9.
6+
#Both num1 and num2 does not contain any leading zero.
7+
8+
num1 = '364'
9+
num2 = '1836'
10+
11+
# Approach 1:
12+
def solution(num1,num2):
13+
eval(num1) + eval(num2)
14+
return str(eval(num1) + eval(num2))
15+
16+
print(solution(num1,num2))
17+
18+
#Approach2
19+
#Given a string of length one, the ord() function returns an integer representing the Unicode code point of the character
20+
#when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.
21+
22+
def solution(num1, num2):
23+
n1, n2 = 0, 0
24+
m1, m2 = 10**(len(num1)-1), 10**(len(num2)-1)
25+
26+
for i in num1:
27+
n1 += (ord(i) - ord("0")) * m1
28+
m1 = m1//10
29+
30+
for i in num2:
31+
n2 += (ord(i) - ord("0")) * m2
32+
m2 = m2//10
33+
34+
return str(n1 + n2)
35+
print(solution(num1, num2))
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
# Given a string, find the first non-repeating character in it and return its index.
3+
# If it doesn't exist, return -1. # Note: all the input strings are already lowercase.
4+
5+
#Approach 1
6+
def solution(s):
7+
frequency = {}
8+
for i in s:
9+
if i not in frequency:
10+
frequency[i] = 1
11+
else:
12+
frequency[i] +=1
13+
for i in range(len(s)):
14+
if frequency[s[i]] == 1:
15+
return i
16+
return -1
17+
18+
print(solution('alphabet'))
19+
print(solution('barbados'))
20+
print(solution('crunchy'))
21+
22+
print('###')
23+
24+
#Approach 2
25+
import collections
26+
27+
def solution(s):
28+
# build hash map : character and how often it appears
29+
count = collections.Counter(s) # <-- gives back a dictionary with words occurrence count
30+
#Counter({'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1})
31+
# find the index
32+
for idx, ch in enumerate(s):
33+
if count[ch] == 1:
34+
return idx
35+
return -1
36+
37+
print(solution('alphabet'))
38+
print(solution('barbados'))
39+
print(solution('crunchy'))

0 commit comments

Comments
 (0)