10: Tuple, Set, Dict

10-3: for e in a_set & Membership

** ถ้าใช้งานบนมือถือหรือ tablet แนะนำให้ใช้ Chrome หรือ Safari เท่านั้น **

แบบฝึกหัด 10-3 ข้อที่ 1

จงเขียนฟังก์ชัน partition(s, k) ที่รับเซตของจำนวนเต็ม s และจำนวนเต็ม k ฟังก์ชันนี้คืนเซต 3 เซต เซตแรกเก็บทุกจำนวนใน s ที่มีค่าน้อยกว่า k, เซตที่สองเก็บทุกจำนวนใน s ที่มีค่าเท่ากับ k และเซตสุดท้ายเก็บทุกจำนวนใน s ที่มีค่ามากกว่า k เช่น s1,s2,s3 = partition({5,2,3,4,1},3) จะได้ s1 = {1,2}, s2 = {3} และ s3 = {4,5}

def partition(s, k): def partition(s, k): s1 = set() s2 = set() s3 = set() for e in s: if e < k: s1.add(e) elif e > k: s3.add(e) else: s2.add(e) return s1, s2, s3 q = "`" fname = "partition" func = Ex().check_function_def(fname, missing_msg="ไม่พบฟังก์ชัน " + (q+fname+q)) func.has_equal_part_len('args', 'ฟังก์ชันนี้รับพารามิเตอร์สองตัว') import random s = {random.randint(0,30) for k in range(15)} k = sorted(s)[random.randint(2,10)] for a in ['{1,2,3,5,6,7,8}, 4', str(s)+", "+str(k)]: fcall = fname + "(" + a + ")" func.check_call(fcall).has_equal_value(incorrect_msg=(q+fcall+q) + " ให้ผลผิด")
แบบฝึกหัด 10-3 ข้อที่ 2

Heterogram คือสตริงที่ ถ้ามีตัวอักษรภาษาอังกฤษ (ใหญ่หรือเล็กก็ได้) ตัวไหน ก็จะมีแค่ตัวเดียว เช่น "Python" เป็น heterogram แต่ "Java" ไม่ใช่ (เพราะมี a สองตัว) จงเขียนฟังก์ชัน is_heterogram(s) ที่รับสตริง s และคืนว่า s เป็น heterogram หรือไม่

def is_heterogram(s): def is_heterogram(s): found_alphabets = set() for c in s.lower(): if "a" <= c <= "z" and \ c in found_alphabets: return False found_alphabets.add(c) return True q = "`" fname = "is_heterogram" func = Ex().check_function_def(fname, missing_msg="ไม่พบฟังก์ชัน " + (q+fname+q)) func.has_equal_part_len('args', 'ฟังก์ชันนี้รับพารามิเตอร์ตัวเดียว') import random t = "".join([chr(random.randint(65, 65+27)) for i in range(8)]) for a in ["'copyrightable'", "'Hello'", "'Lampez un fort whisky!'", "'"+t+"'" ]: fcall = fname + "(" + a + ")" func.check_call(fcall).has_equal_value(incorrect_msg=(q+fcall+q) + " ให้ผลผิด")