ผลลัพธ์สำหรับการสร้างหมายเลขพินสุ่มสี่หลักที่มีความยาวเท่ากันเป็น,
enter the series size 4 Random four digit pin number series 0 0813 1 7218 2 6739 3 8390
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนด้านล่าง -
วิธีแก้ปัญหา
-
สร้างรายการว่างและตั้งค่าผลลัพธ์เป็น True
-
ตั้งค่าในขณะที่วนซ้ำและรับขนาดจากผู้ใช้
-
ตั้งค่าเงื่อนไขว่าจะหาขนาดเป็นคู่หรือคี่ หากขนาดเป็นคี่ ให้กำหนดผลลัพธ์เป็นเท็จ และรันวนซ้ำจนกว่าจะป้อนเลขคู่
l = []
while(True):
size = int(input("enter the series size"))
if(size%2==1):
result = False -
หากขนาดเป็นค่าคู่ ให้กำหนดผลลัพธ์เป็น True และตั้งค่าให้ลูปเข้าถึงช่วงของขนาด
result = True for i in range(size):
-
สร้างตัวเลขสี่หลักแบบสุ่มและจัดเก็บเป็น Rand_pin
-
เพิ่มค่า rand_pin ต่อท้ายรายการ จากนั้นสร้างชุดข้อมูล
rand_pin = random.sample(num,4)
l.append("".join(rand_pin))
pd.Series(l) -
หากค่าผลลัพธ์เป็น True ให้เปลี่ยนรูปลักษณ์โดยใช้เงื่อนไข if
if(result==True): break
ตัวอย่าง
มาทำความเข้าใจโค้ดด้านล่างกัน −
# importing pandas as pd
import pandas as pd
import random,string
num = string.digits
result = True
l = []
while(True):
size = int(input("enter the series size"))
if(size%2==1):
result = False
else:
result = True
for i in range(size):
rand_pin = random.sample(num,4)
l.append("".join(rand_pin))
series = pd.Series(l)
print("Random four digit pin number series\n",series)
if(result==True):
break ผลลัพธ์
enter the series size 3 oops! enter an even number! enter the series size 5 oops! enter an even number! enter the series size 4 Random four digit pin number series 0 0813 1 7218 2 6739 3 8390 dtype: object