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

โปรแกรม Python กรองจำนวนกำลังสองสมบูรณ์ใน Series


อินพุต -

สมมติคุณมี series

0    14 1    16 2    30 3    49 4    80

เอาต์พุต -

ผลลัพธ์สมาชิกที่เป็นกำลังสองสมบูรณ์

0    4 1    16 3    49

วิธีที่ 1

ใช้ regular expression และ lambda filter หาค่ากำลังสอง

  • สร้าง Series

  • ใช้ lambda filter ตรวจสอบค่าเป็นกำลังสอง

l = [14,16,30,49,80]
data=pd.Series([14,16,30,49,80])
result =pd.Series(filter(lambda x: x==int(m.sqrt(x)+0.5)**2,l))
  • ตรวจสอบด้วย isin()

ตัวอย่าง

import pandas as pd
import math as m
l = [4,16,30,49,80]
data = pd.Series(l)
print(data)
lis = []
for i in range(len(data)):
    for j in data:
        if(data[i]==int(m.sqrt(j)+0.5)**2):
            lis.append(data[i])
print("Perfect squares in the series: \n", data[data.isin(lis)])

ผลลัพธ์

Given series: 0    4 1    16 2    30 3    49 4    80 dtype: int64 Perfect Squares in the series: 0    4 1    16 3    49 dtype: int64

วิธีที่ 2

ตัวอย่าง

import re
import math as m
l = [14,16,30,49,80]
data = pd.Series([14,16,30,49,80])
print("Given series:\n", data)
result = pd.Series(filter(lambda x: x==int(m.sqrt(x)+0.5)**2,l))
print(data[data.isin(result)])

ผลลัพธ์

Given series: 0    14 1    16 2    30 3    49 4    80 dtype: int64 Perfect squares: 1    16 3    49 dtype: int64