Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหา Longest Common Directory Path ใน Python

โจทย์: หา Directory Path ที่ยาวที่สุดและซ้ำกัน (Common prefix) จากลิสต์ของ File Paths

Input/Output

paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
Output: home/tutorialspoint

วิธีแก้: ใช้ os.path Module

  1. os.path.commonprefix(paths) หา Common prefix ของสตริงทั้งหมด
  2. os.path.dirname(common_prefix) ดึงเฉพาะ Directory path (ตัดไฟล์/โฟลเดอร์สุดท้ายออก)

ตัวอย่างโค้ด

import os

paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']

common_prefix = os.path.commonprefix(paths)
longest_common_directory = os.path.dirname(common_prefix)

print(longest_common_directory)

ผลลัพธ์

home/tutorialspoint

โมดูล os.path อื่นๆ ที่น่าสนใจ:

  • os.path.join() - รวม path อย่างปลอดภัย
  • os.path.basename() - ดึงชื่อไฟล์/โฟลเดอร์สุดท้าย
  • os.path.split() - แยก (head, tail)
  • os.path.relpath() - หา Relative path

ข้อควรระวัง: commonprefix ทำงานแบบ Character-by-character ไม่ใช่ Path-component อาจให้ผลลัพธ์ผิดหากชื่อโฟลเดอร์มี prefix เหมือนกัน (เช่น /home/user1 และ /home/user2 จะได้ /home/user) ควรใช้ os.path.commonpath (Python 3.5+) แทน