Python algorithm

Former story https://towardsdatascience.com/10-algorithms-to-solve-before-your-python-coding-interview-feb74fb9bc27

Manipulating strings

1. Inverse integer

If an integer is given, it returns an integer with the digits reversed. Note: Integers can be positive or negative.

def solution(x):
    string = str(x)
    if string[0] == '-':
        return int('-'+string[:0:-1])
    else:
        return int(string[::-1])    
print(solution(-231))
print(solution(345))

Output:
-132
543

First, practice slicing. The point is to enter a negative integer

2. Average word length

Returns the average word length for a given sentence. Note: Don't forget to remove the punctuation marks first.


sentence1 = "Hi all, my name is Tom...I am originally from Australia."
sentence2 = "I need to work very hard to learn more about algorithms in Python!"

def solution(sentence):
    for p in "!?',;.":
        sentence = sentence.replace(p, '')
    words = sentence.split()
    return round(sum(len(word) for word in words)/len(words),2)
    
print(solution(sentence1))
print(solution(sentence2))

Output:
4.2
4.08

In a calculation algorithm using a general character string The points are methods such as .replace () and .split ().

to be continued

Recommended Posts

Python algorithm
Python memorandum (algorithm)
A * algorithm (Python edition)
Python
Genetic algorithm in python
Algorithm in Python (Bellman-Ford)
Relearn Python (Algorithm I)
Algorithm in Python (Dijkstra's algorithm)
Algorithm in Python (primality test)
Search algorithm using word2vec [python]
Reproduce Euclidean algorithm in Python
Algorithm in Python (binary search)
[Python3] Dijkstra's algorithm with 14 lines
Implement Dijkstra's Algorithm in python
kafka python
Algorithm in Python (breadth-first search, bfs)
Algorithm gymnastics 12
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Algorithm gymnastics 10
Studying python
Algorithm exercise 6
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Algorithm gymnastics 3
Python basics
Python memo
ufo-> python (3)
Algorithm gymnastics 9
Sorting algorithm and implementation in Python
Algorithm gymnastics 14
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Algorithm gymnastics 2
Python installation
Algorithm gymnastics 7
python tips
Try python
Python memo
Python iterative
Write A * (A-star) algorithm in Python
Python2 + word2vec
Develop an investment algorithm in Python 2
[Python] Variables
Python functions