Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Python Interview Question: Sum Character Positions Using ord() & List Comprehension

Автор: CNP - Code n Program

Загружено: 2025-02-01

Просмотров: 5

Описание:

The video is a Python coding tutorial focused on solving an interview question. It demonstrates how to perform operations on a string using built-in Python functions and shows a more efficient solution using list comprehension.

Detailed Notes:

1. Introduction

The tutorial starts by presenting a typical interview question, which involves calculating a sum based on the character position within the string.
The goal is to map the position of each character in the string to a number and then sum up these numbers.
For example, A = 1, B = 2, C = 3 etc.
2. Setting Up the Problem

A string variable named text is initialized with “ABCDE”.
The goal is to calculate the sum of the position numbers: 1 + 2 + 3 + 4 + 5 = 15.
The expected output is shown: 1 + 2 + 3 + 4 + 5 = 15
3. Using the ord() Function

The tutorial introduces the built-in ord() function.
The ord() function is used with a single character, such as ord('A'), to show its unicode point value, which is 65.
It is important to use quotes around characters when using ord(), otherwise Python will show NameError.
It is then shown that when a string is given to the ord() function rather a single characer, it returns TypeError.
4. Difference Between Unicode and ASCII Values

The video explains that ord() returns the Unicode value of the character, which in most common cases coincides with the ASCII value.
It highlights the fact that in python ord() returns Unicode, not ASCII value.
The presenter also explains the Unicode and ASCII values ​​are similar for Latin characters.
The presenter searches on Google with "what is the unicode value of A" which shows that the Unicode value for ‘A’ is ‘U+0041’, while its ASCII value is 65.
Presenter searches on google “what is the ASCII value of A” which shows that ASCII value of ‘A’ is 65.
5. Understanding chr() Function

The tutorial introduces the built-in chr() function.
The chr() function is used with a number, such as chr(65), to show it the corresponding character, which is ‘A’.
It is explained that Python has a built-in function chr() that can return the character from an integer (unicode point value).
The presenter also explains the difference between chr() and ord() functions, explaining that chr() takes an integer as an argument and returns the character value from unicode points.
6. Printing the Unicode Characters

The tutorial proceeds to iterate over a range and print unicode characters using chr().
It uses for loop and range to print unicode characters using the following code.
for i in range (2300, 24001):
print(chr(i), end = ',')

It is explained that Python uses Unicode values directly instead of ASCII values which is different from other programming languages.
7. Iterating Through Strings

The presenter explains that string are also iterable in Python.
It is shown how a python string can be iterated through using ‘for loop’ as in
for ch in text:
print(ch)

8. Solving the Interview Question

The tutorial then presents two ways of calculating the sum required by the interview question.
In the first method, it creates a total variable and adds the character's number in every loop. The for loop is shown as below :
total = 0
for ch in text:
total += ord(ch) - 64
print (f"Total {total}")

The presenter also shows that the same calculation can be done in a more efficient way using a list comprehension.
It uses the built in sum function along with list comprehension as:
total = sum([ord(ch)-64 for ch in text])
print(f"Total {total}")

It is explained that Python treats strings as an iterable.

Python Interview Question: Sum Character Positions Using ord() & List Comprehension

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Декораторы Python — наглядное объяснение

Декораторы Python — наглядное объяснение

Они убили китайскую электронику! Как США и Нидерланды сломали Китай за один ход

Они убили китайскую электронику! Как США и Нидерланды сломали Китай за один ход

python,dev c installation procedure

python,dev c installation procedure

Твоя ПЕРВАЯ НЕЙРОСЕТЬ на Python с нуля! | За 10 минут :3

Твоя ПЕРВАЯ НЕЙРОСЕТЬ на Python с нуля! | За 10 минут :3

Кто пишет код лучше всех? Сравнил GPT‑5.2, Opus 4.5, Sonnet 4.5, Gemini 3, Qwen 3 Max, Kimi, GLM

Кто пишет код лучше всех? Сравнил GPT‑5.2, Opus 4.5, Sonnet 4.5, Gemini 3, Qwen 3 Max, Kimi, GLM

Python Data Structure for Beginner | LIVE Tutorial 6

Python Data Structure for Beginner | LIVE Tutorial 6

List and Dict

List and Dict

Где начало СХЕМЫ? Понимаем, читаем, изучаем схемы. Понятное объяснение!

Где начало СХЕМЫ? Понимаем, читаем, изучаем схемы. Понятное объяснение!

Музыка для работы за компьютером | Фоновая музыка для концентрации и продуктивности

Музыка для работы за компьютером | Фоновая музыка для концентрации и продуктивности

Путин сделал угрозу НАТО реальной.

Путин сделал угрозу НАТО реальной.

The Windows 11 Disaster That's Killing Microsoft

The Windows 11 Disaster That's Killing Microsoft

Визуализация внимания, сердце трансформера | Глава 6, Глубокое обучение

Визуализация внимания, сердце трансформера | Глава 6, Глубокое обучение

Merge Sort Explained | Data Structures and Algorithms Tutorial in Python

Merge Sort Explained | Data Structures and Algorithms Tutorial in Python

OpenAI, Google, Apple: кто реально победит в гонке AI

OpenAI, Google, Apple: кто реально победит в гонке AI

КАК УСТРОЕН TCP/IP?

КАК УСТРОЕН TCP/IP?

30 самых прекрасных классических произведений для души и сердца 🎵 Моцарт, Бах, Бетховен, Шопен

30 самых прекрасных классических произведений для души и сердца 🎵 Моцарт, Бах, Бетховен, Шопен

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

Но что такое нейронная сеть? | Глава 1. Глубокое обучение

Арестович: Как связаны Гренландия и Иран?

Арестович: Как связаны Гренландия и Иран?

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Преломление и «замедление» света | По мотивам лекции Ричарда Фейнмана

Преломление и «замедление» света | По мотивам лекции Ричарда Фейнмана

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com