找到1-1000以内的所有素数
这是第一次敲的【让1-1000的数除以"2到(本身-1的数)",根据是否有余数来进行打印】
但是发现,9、15……数字都被打印出来了,而且同一个数会被多次打印(问题有点大)
j=1
i=1
print("1-1000里的所有素数为:")
for i in range(1,1001):
for j in range(2,i):
if i % j == 0:
break
else:
print(i)
于是去百度搜索:for else和 if else误区…
原来:
- i=5,只有当i%2和i%3都不等于0才能执行打印;
- i=7,lis=[2,3,5],时,只有当i%2,i%3,和i%才能执行print(7)
所以,只有for else才能正确的执行才代码
加一个,end=" " 吧,让数字打印出来是一行一行的
i=2
for i in range (2, 1001):
j=2
for j in range(2, i):
if (i%j==0):
break
else:
print (i,end=" ")
但是,他会在数字中间断开(我人裂开……
再来,每十个数字就换行
a=0
i=2
for i in range (2, 1001):
j=2
for j in range(2, i):
if (i%j==0):
break
else:
print (i,end=" ")
a+=1
if a%10==0:
print("\n")
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
还行还行,靠着百度做出来了
判断[0,3,2,1]是否为山脉数值
仅仅是判断[0,3,2,1]
a=0
b=3
c=2
d=1
if a<b and b>c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
elif a<b and b<c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
else:
print("[{},{},{},{}]不是山脉数值".format(a,b,c,d))
那么如果我想判断我输入的是不是山脉数值
a=int(input("请你输入第一个数值"))
b=int(input("请你输入第二个数值"))
c=int(input("请你输入第三个数值"))
d=int(input("请你输入第四个数值"))
if a<b and b>c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
elif a<b and b<c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
else:
print("[{},{},{},{}]不是山脉数值".format(a,b,c,d))
同时输入多个数值,字符串间以逗号/空格间隔
a,b,c,d=eval(input('请输入4个数字:'))
if a<b and b>c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
elif a<b and b<c and c>d:
print("[{},{},{},{}]是山脉数值".format(a,b,c,d))
else:
print("[{},{},{},{}]不是山脉数值".format(a,b,c,d))
请你输入第一个数值8
请你输入第二个数值9
请你输入第三个数值10
请你输入第四个数值1
[8,9,10,1]是山脉数值
判断两个字符串是否为换位词
输入字符串后,转换为列表,再进行排序,如果排序后的列表相同,则输入的两个字符串为换位词
a=str(input("请输入第一个:"))
b=str(input("请输入第二个:"))
list1 = list(a)
list2 = list(b)
list1.sort()
list2.sort()
print(list1)
print(list2)
if list1==list2:
print("{}和{}互为换位词".format(a,b))
else:
print("{}和{}不互为换位词".format(a,b))
请输入第一个:55abc88
请输入第二个:58cab85
[‘5’, ‘5’, ‘8’, ‘8’, ‘a’, ‘b’, ‘c’]
[‘5’, ‘5’, ‘8’, ‘8’, ‘a’, ‘b’, ‘c’]
55abc88和58cab85互为换位词
再换一个方法:逐个比对
如果两个字符串的长度相同,开始逐个比对,若其中比对成功的次数=字符串长度,则打印"互为换位词",否则为"不互为换位词"
a=str(input("请输入第一个:"))
b=str(input("请输入第二个:"))
c=0
list1 = list(a)
list2 = list(b)
A=len(list1)
B=len(list2)
if A==B:
for i in range(0,A):
for j in range(0,B):
if list1[i]==list2[j]:
c=c+1
else:
c=c+0
if c==A:
print("{}和{}互为换位词".format(a,b))
break
else:
print("{}和{}不互为换位词".format(a,b))
else:
print("{}和{}不互为换位词".format(a,b))