q11:
'''Question:
Write a program which accepts a sequence of comma separated 4 digit binary numbers
as its input and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
Notes: Assume the data is input by console.
'''
a="0100,0011,1010,1001"
a_=list(a.split(","))
s=[]
print(a_)
for i in a_:
z=int(i[0])*(2**3)+int(i[1])*(2**2)+int(i[2])*2+int(i[3])
s.append(z)
print(s)
z=[]
jieguo=[]
for i in s:
i=int(i)
if i % 5 == 0:
m=s.index(i)
z.append(i)
jieguo.append(a_[m])
print(z)
print(jieguo)
#方法二
value = []
items=[x for x in raw_input().split(',')]
for p in items:
intp = int(p, 2)
if not intp%5:
value.append(p)
print ','.join(value)
总结:对于转换进制的问题,python中int可以直接进行转换
int 可以将 2 进制到 36 进制的字符串、字节串或者字节数组实例转换成对应的 10 进制整数。具体的调用形式为:int(x, base=10),其中 x 即为字符串、字节串或字节数组的实例。
q12:
"""Question:
Write a program, which will find all such numbers between 1000 and 3000 (both included)
such that each digit of the number is an even number.
The numbers obtained should be printed in a comma-separated sequence on a single line.
"""
o=list(range(1000,3001))
z=[0,2,4,6,8]
s=[]
for i in o:
n=0
i=str(i)
x=[int(a) for a in i]
for a in x:
if a in z:
n+=1
if n==4:
s.append(i)
continue
else:
break
print(s)
#方法二
values = []
for i in range(1000, 3001):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
values.append(s)
print ",".join(values)
总结:range函数直接打印,无法打印出来,需要先转换成列表形式
将整数拆分,若m为一个两位以上数字,可以用for a in m 提取
在一个循环中不可以一直用i