This is the second segment of simple to advanced codes
Efficient Python 2
This is the second segment of Efficient python : From Long and Basic to Short
1.Reverse a string in python
Simple code
Reverse a string using for loop
reversed_text
text
“hello”
char
text =
reversed_text = ""
for char in :
reversed_text = +
Output:
olleh
Advanced code
Reverse a string using splicing
text
reversed_text
text = "hello"
= [::-1]
Output:
olleh
2.Compute factorials in python
Simple code
Computing Factorials with for loop
factorial
return
result
n + 1
1
factorial(8)
def (n):
result = 1
for i in range( , ):
*= i
result
print( )
Output:
40320
Advanced code
Computing Factorials with math.factorial
factorial(8)
factorial(n)
def
math
import
factorial(n):
return math.
print( )
Output:
40320
3. Find common elements between two lists
Simple code
Find common elements between 2 lists with for loop
append
common_elements
list2
[1, 2, 3, 4, 5]
list1
item
list1 =
list2 = [4, 5, 6, 7, 8]
= []
for item in :
if in :
common_elements. (item)
print(common_elements)
Output:
[4, 5]
Advanced code
Find common elements between 2 lists set() operations
[4, 5, 6, 7, 8]
set
list
list2
common_elements
list1 = [1, 2, 3, 4, 5]
list2 =
common_elements = ( (list1) & set( ))
print( )
Output:
[4, 5]
4. Counting characters in a string
Simple code
Count characters in a string using for loop
{}
“hello world”
char
char_counts
[char]
1
else
print
text =
char_counts =
for in text:
if char in :
char_counts += 1
:
char_counts[char] =
(char_counts)
Output:
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Advanced code
Count characters in a string using counter from collections
char_counts
collections
Counter
from import Counter
text = "hello world"
= (text)
print(char_counts)
Output:
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
5. Combine two lists
Simple code
merge two lists with for loop
range
[1, 2, 3]
combined_list
len
list1[i]
list1 = ['a', 'b', 'c']
list2 =
= []
for i in ( (list1)):
combined_list.append(( , list2[i]))
print(combined_list)
Output:
[('a', 1), ('b', 2), ('c', 3)]
Advanced code
merge two lists with zip function
list1
[1, 2, 3]
combined_list
list1 = ['a', 'b', 'c']
list2 =
combined_list = list(zip( , list2))
print( )
Output:
[('a', 1), ('b', 2), ('c', 3)]
Manova Quiz
Solve this quiz for testing Manova Basics
Efficient Python 2
This is the second segment of simple to advanced codes