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

หาผลคูณสูงสุดของตัวเลขติดกันในสตริงใน Python

กำหนดสตริงตัวเลข ต้องหาผลคูณสูงสุดของ 2 หลักที่ติดกัน

ตัวอย่าง: '5238521' → max product = 5*8=40 (หลักที่ 3 และ 4)

ใช้ zip และ max

แปลงสตริงเป็นลิสต์ zip กับ list[1:] คูณหา max

ตัวอย่าง

Astring = '5238521'
print("Given String : ", Astring)
Astring = list(Astring)
print("String converted to list:\n", Astring)
res = max(int(a) * int(b) for a, b in zip(Astring, Astring[1:]))
print("The maximum consecutive product is : ", res)

ผลลัพธ์

Given String : 5238521
String converted to list: ['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40

ใช้ map และ operator.mul

map(mul, map(int, Astring), map(int, Astring[1:])) แล้ว max()

ตัวอย่าง

from operator import mul
Astring = '5238521'
print("Given String : ", Astring)
Astring = list(Astring)
print("String converted to list:\n", Astring)
res = max(map(mul, map(int, Astring), map(int, Astring[1:])))
print("The maximum consecutive product is : ", res)

ผลลัพธ์

Given String : 5238521
String converted to list: ['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40