一次小的上机试题

1、8<<2等于 #32 

2、通过内置函数计算5除以2的余数  
  print(divmod(5,2)[1]) #(2, 1)
3、s=[1,"h",2,"e",[1,2,3],"l",(4,5),"l",{1:"111"},"o"],将s中的5个字符提取出来并拼接成字符串。
  
#1.观察法
s=[1,"h",2,"e",[1,2,3],"l",(4,5),"l",{1:"111"},"o"]
print("".join(s[1::2]))#hello

#.法二
tlist = []
for i in s:
    # if type(i) == str:
    if isinstance(i,str):
        tlist.append(i)
s1 = ''.join(tlist)
print(s1)

 4、判断"yuan"是否在[123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"],如何判断以及对应结果?

  

#法一.
lst1 = [123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"]
for i in range(len(lst1)):
    if lst1[i] == 'yuan':
        print(lst1[i])
    elif isinstance(lst1[i],tuple ):
        print(lst1[i])
    elif isinstance(lst1[i], str):
        print(lst1[i])
    elif isinstance(lst1[i], dict):
        print(lst1[i])
#法二
lst1 = [123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"]
for i in  range(len(lst1)):
    if str(lst1[i]).find('yuan') != -1:
        print(lst1[i]) # (1, 'yuan') {'yuan': 'handsome'} yuanhao

 5、l=[1,2,3]

l2=l.insert(3,"hello")

print(l2)

执行结果并解释为什么?

l=[1,2,3]
l2 = l.insert(3,"hello")
print(l2)  #None  因为insert这个函数没有返回值,所以输出是None

 

# 6、
a = [1, 2, [3, "hello"], {"egon": "aigan"}]
b = a[:]
a[0] = 5
a[2][0] = 666
print(a) #[5, 2, [666, 'hello'], {'egon': 'aigan'}],
# 首先b= a[:]  创建一个新的列表,\
# 修改a[0]=5,因为5是一个不可变数据类型,会重新创建一个新内存地址,并把值引用赋给a[0],所以a[0]=5 由原来1变成5.
# print(b) #[1, 2, [666, 'hello'], {'egon': 'aigan'}]
#首先b= a[:]  创建一个新的列表, 但是,元素如果嵌套有超过一层,那么它复制只是复制引用地址,里面值它不管的,也就是说
# 新列表的b里的b[2][0], 跟a[2][0] 是共享一个内存地址,,而a[2][0] = 666变了,那么b[2][0] =666.
# 计算结果以及为什么?

7 使用文件读取,找出文件中最长的行的长度(用一行代码解决)?

with open('a.txt','r') as f:print(len(max(f.__iter__())))

 8,


def add(s, x):
    return s + x
def generator():
    for i in range(4):
        yield i
base = generator()
for n in [1, 11]:
    base = (add(i, n) for i in base)
print(list(base))  #[22, 23, 24, 25]

9
hello.py(gbk方式保存):
#coding:GBK
 print(“老男孩”)
 如果用py2,py3下在cmd下运行回报错吗?为什么并提出解决方案? (编码)

#coding:GBK
 print("老男孩")
# 都不报错,cmd 默认就是Gbk编码,此文件开头已经声明gbk编码方式unicode,编码也是gbk编码方式与cmd一样

10 # 通过函数化编程实现5的阶乘 # n!=n*(n-1)! 阶乘的计算方法 阶乘指从1乘以2乘以3乘以4 24

def gat(n):
    ps = n
    for i in range(1,n):
        ps *= i
    print(ps)
gat(5)

11 # 打印如下图案:

       *
          ***
         *****
        *******
         *****
          ***
            *

 

str1 = " "
str2 = "*"
for i in range(1,8,2):
    s = (7-i)//2
    print(str1*s,i*str2,s*str1)
for i in reversed(range(1,6,2)):
    s = (7 - i) // 2
    print(str1 * s,i * str2, s * str1 )

12. 

def outer():
    count = 10
    def inner():
        count = 20
        print(count)
    inner()
    print(count)
outer()
# 20
# 10
# 当调用 outer(),先是程序执行outer 定义的函数体,里面嵌套有一个inner方法
# 当count=20,outer函数里调用一个的inner(),inner被 调用 时,内部有一个变量count=20,,
# 当inner 内的print count,优先找到它自己内字义的count=20,所以第一闪打印20,内部的inner被执行完
# 接着跑outer函数定义体的print(count),此时作用就优先找 它自己定义 的count=10.所以结果 为10

(1)分析运行结果?
(2)如何让两个打印都是20

def outer(count = 20):
    count = 10
    def inner():
        count = 20
        print(count)
    inner()
    return inner()
outer()
#20
#20

13 # 输入一个年份,判断是否是闰年? 

p = int(input('inpu year'))
if p % 4 == 0 and (p % 100 != 0 ):
    print('%s 年是闰年'%p)
elif  (p % 400 == 0):
    print('%s 年是闰年'%p)
else:
    print('%s 年不是闰年'%p)

14.任意输入三个数,判断大小?

def max_d(x,y,z):
    def wapper():
        p = max(x,y)
        p = max(p,z)
        return p
    return wapper()
print(max_d(23,32,9))
print(max_d(923,332,9)

15 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。

例如2+22+222+2222+22222 # ,几个数相加以及a的值由键盘控制。

 

while 1:
    p = int(input('input num'))
    p_count = int(input('input count'))
    def func_re():
        res = p
        for i in range(1,p_count):
            res += int((i+1)*str(p))
        print(res)
    func_re()

16# 请问程序有无bug,怎么解决?

f=open("a.txt")
while 1:
    choice=input("是否显示:[Y/N]:")
    if choice.upper()=="Y":
        for i in f:
            print(i)
    else:
        break
# 有bug #添加 f.seek(0)

 修改后如下

f = open("a.txt")
while 1:
    choice = input("是否显示:[Y/N]:")
    if choice.upper() == "Y":
        for i in f:
            print(i)
        f.seek(0)  #每次读取好,游标记它到开始处
    else:
        break

# 17

 


def foo():
    print('hello foo')
    return()
def bar():
    print('hello bar')

(1) 为这些基础函数加一个装饰器,执行对应函数内容后,将当前时间写入一个文件做一个日志记录。

import  time
def timer(func):
    def wapper(*args,**kwargs):
        f = open('a.log','a+')
        res = func(*args,**kwargs)
        f.write(str(time.time())+"\n")
        return  res
    return wapper
@timer
def foo():
    print('hello foo')
    return()
@timer
def bar():
    print('hello bar')
foo()
bar()

(2) 改成参数装饰器,即可以根据调用时传的参数决定是否记录时间,比如@logger(True)

#有参数
import  time
def loger(l_type):
    def timer(func):
        def wapper(*args,**kwargs):
            f = open('a.log','a+')
            res = func(*args,**kwargs)
            if l_type == True:
                f.write(str(time.time())+"\n")
                return  res
            else:
                pass
        return wapper
    return timer
@loger(True)
def foo():
    print('hello foo')
    return()
@loger(True)
def bar():
    print('hello bar')
foo()
bar()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 




 

 
posted @ 2017-04-19 01:37  福临  阅读(220)  评论(0编辑  收藏  举报