检验素数
from math import sqrt
a = int(input("请输入一个数:"))
for i in range(2,int(sqrt(a))):
if a%i == 0:
print("该数不是素数")
break
else:
print("该数是素数")
# # 1既不是素数也不是合数
# #可以用flag做标志位
# b = int(input("请输入一个数:"))
# Flag = False
# for i in range(2,b):
# if b%i == 0:
# Flag = True
# if Flag:
# print("是合数")
# else:
# print("是素数")
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int a = 0;
printf("请输入一个大于1的自然数:");
scanf("%d", &a);
int flag = 0;
for (int i = 2; i < a; i++)
{
if (a % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
printf("输入的数是一个素数");
}
else
{
printf("输入的数不是一个素数");
}
return 0;
}
逐字检查法
自解
解法1
a = "python"
b = "typhon"
list1 = list(b)
print(list1)
def judge(a,b):
for i in range(len(a)):
for j in range(len(a)):
if a[i] == b[j]:
list1[j] = None
break
for i in range(len(a)):
list1[i] == None
if list1[i] != None:
return False
return True
if judge(a,b) == True:
print("是变位词")
elif judge(a,b) == False:
print("不是变位词")
解法2
a = "python"
b = "typhon"
def judge(a,b):
list1 = list(a)
list2 = list(b)
j = len(list2)
list1.sort()
list2.sort()
for i in range(len(list1)):
if list1[i] == list2[i]:
pass
else:
return False
return True
if judge(a,b) == True:
print("是变位词")
elif judge(a,b) == False:
print("不是变位词")
计数比较法
a = "pythoe"
b = "typhon"
"""计数比较-自解"""
dict1 = dict()
dict2 = dict()
list1 = list(a)
list2 = list(b)
for i in range(ord("a"),ord("z")+1):
dict1[i] = 0
for i in range(ord("a"),ord("z")+1):
dict2[i] = 0
def judge(a,b):
for j in range(len(a)):
for i in range(ord("a"),ord("z")+1):
if ord(list1[j]) == i:
dict1[i] = dict1[i] + 1
for j in range(len(a)):
for i in range(ord("a"),ord("z")+1):
if ord(list2[j]) == i:
dict2[i] = dict2[i] + 1
for i in range(ord("a"),ord("z")+1):
if dict1[i] == dict2[i]:
pass
else:
return False
return True
if judge(a,b) == True:
print("是变位词")
elif judge(a,b) == False:
print("不是变位词")
"""计数比较-仿他解"""
def judge(a,b):
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(a)):
pos = ord(a[i]) - ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(a)):
pos = ord(b[i]) - ord('a')
c2[pos] = c2[pos] + 1
for i in range(26):
if c1[i] == c2[i]:
pass
else:
return False
return True
if judge(a,b) == True:
print("是变位词")
elif judge(a,b) == False:
print("不是变位词")
他解
\
鹏哥C语言
、