1、三角形三条边长度分别为3、7、9,请计算这个三角形的三角度数(用弧度制表示)

  •  数学知识

python123三角形边长 用python求三角形的斜边长_linux

>>> import math
>>> a = 3
>>> b = 7
>>> c = 9
>>> cosC = (a**2 +b**2 - c**2)/(2*a*b) 
>>> C = math.acos(cosC)
>>> C
2.1503123541907514
>>> print(C)
2.1503123541907514

2、对于字符串:'you need python'

  • 分别得到三个单词;
  • 从左到右的顺序,隔一个字符取一个;
  • 从右到左的顺序,隔一个字符取一个;
  • 将字符串区反序
#分别得到三个单词;
#方法1:
>>> s = 'you need python'
>>> s[:3]
'you'
>>> s[4:8]
'need'
>>> s[9:]  
'python'
#方法2:
>>> s = 'you need python'
>>> lst = s.split(' ')
>>> lst
['you', 'need', 'python']
>>> lst[0]
'you'
>>> lst[1]
'need'
>>> lst[2]
'python'
#从左到右的顺序,隔一个字符取一个;
>>> s[::2]
'yune yhn'
#从右到左的顺序,隔一个字符取一个;
>>> s[::-2]
'nhy enuy'
#将字符串区反序
>>> s[::-1]
'nohtyp deen uoy'

3、字符串切割与替代

  • 字符串' hello ',字母h左侧和o右侧都有空格,使用字符串的方法去除空格——strip()
  • 将字符串"you need python"中的空格,用*号替代
>>> st = ' hello ' 
>>> st.strip()
'hello'#*号替代空格
#方法1:
>>> s = "you need python"  
>>> t = s.split()
>>> t
['you', 'need', 'python']
>>> "*".join(t)  
'you*need*python'#方法2:
>>> s.split() 
['you', 'need', 'python']
>>> '*'.join(s.split())
'you*need*python'

 4、编写程序,实现以下操作

  • 通过键盘输入数字,作为圆的半径
  • 计算圆的周长和面积,并分别打印显示出来,结果保留两位小数
[oldboy@linux-node3 ~]$ cat query_cyle.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chenwei
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""

import math
num = input("Please input a num:")
num = float(num)
area = math.pi*num**2
perimeter = math.pi*num*2
print("area is ",round(area,2))
print("perimeter is:",round(perimeter,2))
[oldboy@linux-node3 ~]$ python3 query_cyle.py 
Please input a num:3
area is  28.27
perimeter is: 18.85

5、编写程序,实现如下功能:

  • 询问用户的姓名和年龄
  • 计算10年后的年龄
  • 打印出用户的姓名,及其现在和10年后的年龄
#方法1:
[oldboy@linux-node3 ~]$ cat inquiry_naming_old.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
#author:chenwei
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
old_name = input("Please enter your name:")
old_age = input("Please enter your age:")

old_age = int(old_age)
print("your current name is",old_name)
print("your current age is",old_age)

after_age = old_age + 10
print("10 years later,your age is:",after_age)
[oldboy@linux-node3 ~]$ python3 inquiry_naming_old.py
Please enter your name:chenwei
Please enter your age:25
your current name is chenwei
your current age is 25
10 years later,your age is: 35
#方法2:
[oldboy@linux-node3 ~]$ cat inquiry_naming_old_v2.py     
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
#author:chenwei
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
name = input("your name:")
age = input("your age:")

after_ten = int(age) + 10
print("-"*10)
print("your name is {0}\nyou are {1} years old now\nAfter 10 years later,you are {2} years old".format(name,age,after_ten))
[oldboy@linux-node3 ~]$ python3 inquiry_naming_old_v2.py 
your name:qinxiansi
your age:28
----------
your name is qinxiansi
you are 28 years old now
After 10 years later,you are 38 years old

6、将字符串"python"转化为列表(记为lst),并完成如下操作:

  • 将字符串"rust"中的每个字母作为独立的元素追加到列表lst中
  • 对lst列表进行排序
  • 删除lst中重复的元素
>>> A = "python"
>>> lst = list(A)
>>> lst
['p', 'y', 't', 'h', 'o', 'n']
>>> B = "rust"
#列表尾部追加为元素
>>> lst.extend(B)
>>> lst
['p', 'y', 't', 'h', 'o', 'n', 'r', 'u', 's', 't']
>>> lst.sort()
>>> lst
['h', 'n', 'o', 'p', 'r', 's', 't', 't', 'u', 'y']
>>> sorted(lst)
['h', 'n', 'o', 'p', 'r', 's', 't', 't', 'u', 'y']
#转换为集合进行去重
>>> set(lst)
{'y', 'h', 'u', 's', 'n', 't', 'o', 'p', 'r'}
>>> list(set(lst))
['y', 'h', 'u', 's', 'n', 't', 'o', 'p', 'r']

7、编写程序,实现如下功能:

  • 用户输入国家的名称
  • 打印出所输入国家的名称及其首都
[oldboy@linux-node3 ~]$ cat judge_nation_capital.py 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
# Author:ChenWei
# Version:1.0
# Date:2020-12-14 20:56
# Modified by:ChenWei
# Software: PyCharm 2018.2.4
# Description:This script is used for 
"""
nations = {'China':'Beijing', 'Japan':'Tokyo', 'India':'New Delhi', 'Sweden': 'Stockholm', 'Russian':'Moscow', 'Germany':'Berlin', 'UK':'London', 'French':'Paris', 'Swiss':'Bern', 'Egypt':'Cairo', 'Australia':'Canberra', 'New Zealand':'Wellington', 'Canada':'Ottawa', 'USA':'Washington', 'Cuba':'Havana', 'Brazil':'Brasilia'}

name = input('input a name of country:')

capital = nations.get(name)
print("the country:", name)
print("the capital:", capital)

8、有如下技术栈名称集合: skills={'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'},假设自己的技术是:mySkills={'Python', 'R'}

  • 判断自己所掌握的技术是否在上述技术栈范围之内——查出集合的交集
>>> skills={'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}
>>> mySkills={'Python', 'R'}
>>> res = skills.intersection(mySkills) 
>>> print(res)
{'Python', 'R'}

9、找出以下两个字典共有的键:

{'a':1, 'b':2, 'c':3, 'd':4}
  {'b':22, 'd':44, 'e':55, 'f':77}
#普通方法:
>>> d1={'a':1, 'b':2, 'c':3, 'd':4} 
>>> d2={'b':22, 'd':44, 'e':55, 'f':77}
>>> d1_set=set(d1.keys())
>>> d2_set=set(d2.keys())  
>>> d1_set.intersection(d2_set)
{'b', 'd'}
#py3.8新方法:
>>> d1.keys()          
dict_keys(['a', 'b', 'c', 'd'])
>>> type(d1.keys())
<class 'dict_keys'>
>>> d1.keys() & d2.keys()      
{'b', 'd'}

10、字符串:songs='You raise my up so can stand on mountains You raise my up to walk on stormy seas am strong when am on your shoulders You raise me up to more than can be'

  • 制作上述字符串的单词表——即去重
  • 统计每个单词的出现次数——统计
#制作上述字符串的单词表——即去重
>>> songs='You raise my up so can stand on mountains You raise my up to walk on stormy seas am strong when am on your shoulders You raise me up to more than can be'
>>> songs.split()
['You', 'raise', 'my', 'up', 'so', 'can', 'stand', 'on', 'mountains', 'You', 'raise', 'my', 'up', 'to', 'walk', 'on', 'stormy', 'seas', 'am', 'strong', 'when', 'am', 'on', 'your', 'shoulders', 'You', 'raise', 'me', 'up', 'to', 'more', 'than', 'can', 'be']
>>> songs_set=set(songs.split())
>>> songs_set
{'shoulders', 'mountains', 'up', 'You', 'when', 'than', 'stand', 'be', 'can', 'raise', 'strong', 'more', 'my', 'am', 'walk', 'me', 'so', 'seas', 'on', 'your', 'to', 'stormy'}
#列表不唯一性,所以有count方法;集合唯一性,故没有count方法,具体看dir()
>>> songs_set=songs.split()
>>> songs_set
['You', 'raise', 'my', 'up', 'so', 'can', 'stand', 'on', 'mountains', 'You', 'raise', 'my', 'up', 'to', 'walk', 'on', 'stormy', 'seas', 'am', 'strong', 'when', 'am', 'on', 'your', 'shoulders', 'You', 'raise', 'me', 'up', 'to', 'more', 'than', 'can', 'be']
>>> songs_set.count('up')  
3
#字符串个数统计
>>> songs 
'You raise my up so can stand on mountains You raise my up to walk on stormy seas am strong when am on your shoulders You raise me up to more than can be'
>>> songs.count('You')  
3

11、判断用户输入的数字是奇数还是偶数

[oldboy@linux-node3 ~]$ cat judge_num.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""

def judge_number():
    count = 0
    instr = input("Please input your digit number:")

    if instr.isdigit():
        n = int(instr)
        if n%2 == 0:
            print("your number {0} is 偶数".format(n))
            print(n)
        else:
            print("your number {0} is 奇数".format(n))
            print(n)
    else:
        print("Input error! requred a digit number.")

judge_number()
[oldboy@linux-node3 ~]$ python3 judge_num.py 
Please input your digit number:5
your number 5 is 奇数
5
[oldboy@linux-node3 ~]$ python3 judge_num.py 
Please input your digit number:4a
Input error! requred a digit number.

12、编写程序:判断用户输入的网站域名是否符合规定的格式要求

  • 网站主域名格式:www.xxxx.xxx
[oldboy@linux-node3 ~]$ cat judge_domain_v1.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
dom_put = input("Please input your domain:")
domain_format = ('com','net','org','cn')

if dom_put.isdigit():
    print("Input error!please try again.")
else:
    len_str=dom_put.split(".")
    if (len(len_str) < 2 or len(len_str) > 4):
        print("Input error!your domain is not correct")
    elif len_str[-1] not in domain_format:
        print("Input error!correct")
    else:
        print("your domain is correct")
[oldboy@linux-node3 ~]$ python3 judge_domain_v1.py 
Please input your domain:www.123.com
your domain is correct
[oldboy@linux-node3 ~]$ python3 judge_domain_v1.py 
Please input your domain:www.123ad.net
your domain is correct
[oldboy@linux-node3 ~]$ python3 judge_domain_v1.py 
Please input your domain:www.1234.12.com
your domain is correct
[oldboy@linux-node3 ~]$ python3 judge_domain_v1.py 
Please input your domain:www.1234.123com
Input error!correct

13、判断用户的键盘输入内容:

  • 如果都是数字,则将该数字扩大10倍,然后打印显示。
  • 如果是字母,则在其后面增加"@python"后打印显示。
  • 其他情况则将输入的内容按原样显示
[oldboy@linux-node3 ~]$ cat judge_num_v2.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
import re
def is_number(num):
    pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
    result = pattern.match(num)
    if result:
    return True
    elif instr.isalnum():
    return False
    else:
        #print(num)
    passinstr = input("Please input your digit number:")
if is_number(instr):
    instr = float(instr)
    print(instr * 10)
elif instr.isalpha():
    print(instr + '@python')
else:
    print(instr)[oldboy@linux-node3 ~]$ python3 judge_num_v2.py
Please input your digit number:13.12      
131.2
[oldboy@linux-node3 ~]$ python3 judge_num_v2.py
Please input your digit number:-24.6 
-246.0
[oldboy@linux-node3 ~]$ python3 judge_num_v2.py
Please input your digit number:#aed
#aed
[oldboy@linux-node3 ~]$ python3 judge_num_v2.py
Please input your digit number:dabcd
dabcd@python

14、统计如下字符串中每个单词出现的次数、每个单词的长度

  • songs = "when I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountains YOu raise me up to walk on stormy sears I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains Your raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains"
[oldboy@linux-node3 ~]$ cat count_str_count.py         
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
songs = "when I am down and oh my soul so weary When troubles come and my heart burdened be Then I am still and wait here in the silence Until you come and sit awhile with me You raise me up so I can stand on mountains YOu raise me up to walk on stormy sears I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains Your raise me up to walk on stormy seas I am strong when I am on your shoulders You raise me up to more than I can be You raise me up so I can stand on mountains"

lsts=songs.split()
d = {}

for i in lsts:
    i = i.lower()
    if i in d:
        d[i] +=1
    else:
        d[i] = 1

print(d)
[oldboy@linux-node3 ~]$ python3 count_str_count.py 
{'when': 4, 'i': 11, 'am': 6, 'down': 1, 'and': 4, 'oh': 1, 'my': 2, 'soul': 1, 'so': 4, 'weary': 1, 'troubles': 1, 'come': 2, 'heart': 1, 'burdened': 1, 'be': 3, 'then': 1, 'still': 1, 'wait': 1, 'here': 1, 'in': 1, 'the': 1, 'silence': 1, 'until': 1, 'you': 7, 'sit': 1, 'awhile': 1, 'with': 1, 'me': 8, 'raise': 7, 'up': 7, 'can': 5, 'stand': 3, 'on': 7, 'mountains': 3, 'to': 4, 'walk': 2, 'stormy': 2, 'sears': 1, 'strong': 2, 'your': 3, 'shoulders': 2, 'more': 2, 'than': 2, 'seas': 1}
cat count_str_num_v2.py
#方法1
lst = songs.split()
for st in lst:
    print(len(st))

#方法2
ds = {}
for i in lst:
    ds[i] = len(i)

print(ds)

15、如下字典,将键和值对换,即键作为值,值作为键。

  • d = {‘book’: [‘python’, ‘datascience’], ‘author’: ‘laoqu’, ‘publisher’: ‘phei’}
[oldboy@linux-node3 ~]$ cat tran_key_val.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
d = {'book': ['python', 'datascience'], 'author': 'laoqu', 'publisher': 'phei'}
new_d = {}

for k, v in d.items():
    if type(v) == list:
        v = tuple(v)
    new_d[v] = k

print(new_d)
[oldboy@linux-node3 ~]$ python3 tran_key_val.py 
{('python', 'datascience'): 'book', 'laoqu': 'author', 'phei': 'publisher'}
[oldboy@linux-node3 ~]$ cat tran_key_val_coll.py        
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
import collections.abc
d = {'book': ['python', 'datascience'], 'author': 'laoqu', 'publisher': 'phei'}

dd = {}
for k, v in d.items():
    if isinstance(v,collections.abc.Hashable):#可Hashable的是不可变对象
        dd[v] = k
    else:
        dd[tuple(v)] = k#不可Hashable的,是list等可变对象

print(dd)
[oldboy@linux-node3 ~]$ python3 tran_key_val_coll.py 
{('python', 'datascience'): 'book', 'laoqu': 'author', 'phei': 'publisher'}
ddd = {v if isinstance(v, collections.abc.Hashable)#可Hashable的是不可变对象
      else tuple(v): k for k, v in d.items()}
print(ddd)

 16、有字符串 : Life is short You need python

  • 显示每个单词大写和小写两种状态
  • 统计每个单词的长度
[oldboy@linux-node3 ~]$ cat count_str_num_v2.py        
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
  Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
songs='Life is short You need python'
lst = songs.split()

for st in lst:
    print(st.lower())
    print(st.upper())
    print(len(st))
ds = {}
for i in lst:
    ds[i] = len(i)

print(ds)
[oldboy@linux-node3 ~]$ python3 count_str_num_v2.py 
life
LIFE
4
is
IS
2
short
SHORT
5
you
YOU
3
need
NEED
4
python
PYTHON
6
{'Life': 4, 'is': 2, 'short': 5, 'You': 3, 'need': 4, 'python': 6}

 17、写一个猜数字游戏程序:

  • 计算机随机生成一个100以内的正整数
  • 用户通过键盘输入数字,猜测所生成的随机数
  • 对用户的输入次数不作限制
[oldboy@linux-node3 ~]$ cat judge_while_num.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Date:2020-12-10 21:30
# Filename: query_cyle.py
# Software: vscode-1.14.10
# Description:This script is used for 
"""
import random

numst = random.randint(0,100)
gres = input("Input your number:")

if gres.isdigit():
    gres = int(gres)
    while gres > 0 and gres < 100:
        if gres == numst:
            print("your number is correct")
            break
        elif gres > numst:
            print("It is too big,try again",numst)
        else:
            print("It is too small,try again",numst)
else:
    print("Input error,it requires a digit number")
[oldboy@linux-node3 ~]$ python3 judge_while_num.py       
Input your number:45
It is too small,try again 69
[oldboy@linux-node3 ~]$ python3 judge_while_num.py 
Input your number:20
It is too small,try again 49
[oldboy@linux-node3 ~]$ python3 judge_while_num.py 
Input your number:46
It is too big,try again 27
[oldboy@linux-node3 ~]$ cat judge_input_num.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Description:This script is used for 
"""
import random

numst = random.randint(0,100)
guesstime = 0

while True:
    gres = input("Input your number:")
    if gres.isdigit():
        guesstime += 1
        if int(gres) > 0 and int(gres) < 100:
            if int(gres) == numst:
                print("your number is correct")
                print("you guess times:",guesstime)
                break
            elif int(gres) > numst:
                print("It is too big,try again",numst)
            else:
                print("It is too small,try again",numst)
        else:
            print("you must input a number between 0 and 100")
        continue
    else:
        print("Input error,it requires a digit number")
[oldboy@linux-node3 ~]$ python3 judge_input_num.py
Input your number:45
It is too big,try again 39
Input your number:39
your number is correct
you guess times: 2

 18、编写函数,对单词中的字母实现以下操作:

  • 根据参数设置,将单词中的字母转换为大写或小写
  • 返回转化之后的单词
[oldboy@linux-node3 ~]$ cat trans_strword_maxmin.py     
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:chengzi
# Version:1.0
# Description:This script is used for 
"""

def exchange(word):
    word = str(word)
    if word.islower() == True:
        print("这个单词为全小写单词:")
        word = word.upper()
        return word
    elif word.isupper() == True:
        word = word.lower()
        print("您输入的为全大写单词:")
        return word
    else:
        print("输入错误,请输入一个全大写或者全小写的单词!")

word = str(input("请输入一个全大写或者全小写的单词:"))
cword = exchange(word)
print("转化后的单词为:",cword)
[oldboy@linux-node3 ~]$ python3 trans_strword_maxmin.py 
请输入一个全大写或者全小写的单词:dabs
这个单词为全小写单词:
转化后的单词为: DABS
[oldboy@linux-node3 ~]$ python3 trans_strword_maxmin.py 
请输入一个全大写或者全小写的单词:SDAC
您输入的为全大写单词:
转化后的单词为: sdac
[oldboy@linux-node3 ~]$ python3 trans_strword_maxmin.py 
请输入一个全大写或者全小写的单词:STda
输入错误,请输入一个全大写或者全小写的单词!
转化后的单词为: None

 19、编写函数

  • 编写函数,计算平面直角坐标系中两点的距离,函数和的参数是两点的坐标
  • 编写函数,判断某字符串中是否含有指定集合的字母
[oldboy@linux-node3 ~]$ cat cacul_twopiot_distance.py         
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:ChengZi
# Version:1.0
# Date:2020-12-21 22:33
# Modified by:ChengZi
"""
def distance(a,b):
    import math
    try:
        dres = math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
        return (round(dres,3))
    except Exception as e:
        return str(e)

def dist_point():
    p = input("input your point:")
    pl = []
    pls = p.split(",")
    for i in range(0,len(pls)):
        pl.append(float(pls[i]))
    return pl

pa = dist_point()
pb = dist_point()

ds = distance(pa,pb)
print(ds)
[oldboy@linux-node3 ~]$ python3 cacul_twopiot_distance.py 
input your point:3,5
input your point:7,8
5.0
[oldboy@linux-node3 ~]$ python3 cacul_twopiot_distance.py 
input your point:3,7
input your point:4,9
2.236
[oldboy@linux-node3 ~]$ cat judge_set_collec.py                
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:ChengZi
# Version:1.0
# Date:2020-12-21 22:33
# Modified by:ChengZi
"""
baseset = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}
#input_set = {'Python','Git','hub'}
input_set =input("input your sections:")
evput = eval(input_set)
res = evput.intersection(baseset)
print("your sections {0} is in\n {1}".format(evput,baseset))
print(res)
[oldboy@linux-node3 ~]$ python3 judge_set_collec.py 
input your sections:{'Python','Git','hub'}
your sections {'hub', 'Python', 'Git'} is in
 {'R', 'SAS', 'Tableau', 'Python', 'Git', 'SQL'}
{'Python', 'Git'}

参考答案

def distance(pa, pb):
    import math
    lst = [(x-y)**2 for x, y in zip(pa, pb)]
    #lst = map[(lambda x,y:(x-y)**2,pa,pb)] 
    d = math.sqrt(sum(lst))
    return d

pa = (1, 2)
pb = (3, 4)
print('d=', distance(pa, pb))
def contain_any_1(seq,aset):
    for c in seq:
        if c in aset:
            return True
        return False

def contain_any_2(seq,aset):
    for item in filter(aset.__contains__,seq):
        return True
    return False

def contain_any_3(seq,aset):
    return boll(aset.intersection(seq))

seq = "apython"
aset = set(['a','b','c','d','e'])
result = contain_any_3(seq,aset)
print(result)

20、找出其中键值对的值最小的那个键值对

  • 参考地址:

d = {'huawei': 91.2, 'alibaba': 94.1, 'qq':90.1, 'baidu':89.4, 'xiaomi':88.4}

#方法1:此方法适用于只有一个最小值的情况
>>> d = {'huawei': 91.2, 'alibaba': 94.1, 'qq':90.1, 'baidu':89.4, 'xiaomi':88.4}
>>> max_d = max(zip(d.values(),d.keys()))
>>> min_d = min(zip(d.values(),d.keys()))
>>> print(max_d)
(94.1, 'alibaba')
>>> print(min_d)
(88.4, 'xiaomi')

#方法2:
d = {'huawei': 91.2, 'alibaba': 94.1, 'qq': 90.1, 'baidu': 89.4, 'xiaomi': 88.4}
d_new = sorted(d.values())
min_value = d_new[0]
tget = {}
for k in d:
    if d[k] == min_value:
        tget[k] = min_value
print(tget)

# 方法3:
d = {'huawei': 91.2, 'alibaba': 94.1, 'qq': 90.1, 'baidu': 89.4, 'xiaomi': 88.4}
tget2 = {}
min_key = min(d, key=d.get)
tget2[min_key] = d[min_key]
print(tget2)

#方法4:此方法适用有多个最小值的情况
d = {'huawei': 91.2, 'alibaba': 94.1, 'qq': 90.1, 'baidu': 89.4, 'xiaomi': 88.4}
males = filter(lambda x: min(d.values()) == x[1], d.items())
for i in males:
    print(i)

21、rang函数的参数都是正数,即必须按照正数步长变化,得到的整数元素组成的rang对象。现在要求写一个函数,实现以浮点数为数列开始、结束和步长,创建等差数列。

#自定义输入
[oldboy@linux-node3 ~]$ cat frange_def_v1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:ChengZi
# Version:1.0
# Filename: frange_def.py
# Description:This script is used for 
"""
def frange(start, stop, step):
    lst = []
    while start < stop:
        lst.append(start)
        start += step
    return lst

nlist = input("input a float range numbers:")
n=[]
nls = nlist.split(",")
for i in range(0,len(nls)):
    n.append(float(nls[i]))

frang_res = frange(start=n[0],stop=n[1],step=n[2])
print(frang_res)
# print("The list is {0:.2f}".format(frang_res))
[oldboy@linux-node3 ~]$ python3 frange_def_v1.py
input a float range numbers:0.2,2.5,0.5
[0.2, 0.7, 1.2, 1.7, 2.2]
#判断起始值与终止值和步长之差的大小
>>> def dc(start,step,stop):      
...     lst = [start]
...     s = start
...     while s <= stop-step:
...         s = round(s + step,2)
...         lst.append(s)
...     return lst
... 
>>> dc(0.4,5.3,0.9)
[0.4]
>>> dc(0.4,0.9,5.3)
[0.4, 1.3, 2.2, 3.1, 4.0, 4.9]
#判断起始值和终止值大小
>>> def frange(start, stop, step):
...     lst = []
...     while start < stop:
...        lst.append(start)
...        start += step
...     return lst
... 
>>> frange(0.4,5.3,0.9)
[0.4, 1.3, 2.2, 3.1, 4.0, 4.9]
>>> frange(0.4,1.2,0.9)    
[0.4]

22、在字典中有get方法,但在列表中没有;请编写函数,对列表实现类似字典中get方法的功能

[oldboy@linux-node3 ~]$ cat get_index_method.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#method 1
def get_by_index_1(lst,i,value=None):
    if i < len(lst):
        return lst[i]
    else:
        return value

#method 2
def get_by_index_2(lst,i,value=None):
    if -len(lst) <= i < len(lst):
        return lst[i]
    else:
        return value

#method 3
def get_by_index_3(lst,i,value=None):
    try:
       return lst[i]
    except IndexError:
       return value

lst = [1,2,3,4,5]
while True:
    try:
        idx = int(input("input index of list:"))
    except ValueError:
        print("Index should be int")
        continue
    value = input("input value:")
    
    if value !='q':
        r1 = get_by_index_1(lst,idx,value)
        r2 = get_by_index_2(lst,idx,value)
        r3 = get_by_index_3(lst,idx,value)
        print(r1,r2,r3)
    else:
        break

23、编写函数,实现正整数的阶乘。

[oldboy@linux-node3 ~]$ cat jc_func.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:ChengZi
# Version:1.0
# Filename: jc_func.py
# Description:This script is used for 
"""

def jc_func(n):
    assert n >0
    res = 1
        
    for i in range(1,n+1):
        res = res * i
        i += 1
    return res

n = input("input your number:")
lnb = int(n)
bf = jc_func(lnb)
print(bf)
[oldboy@linux-node3 ~]$ python3 jc_func.py      
input your number:10
3628800
[oldboy@linux-node3 ~]$ python3 jc_func.py 
input your number:6
720
[oldboy@linux-node3 ~]$ python3 jc_func.py 
input your number:8
40320

24、物体的重力G=mg,其中m是物体的质量,g是重力加速度。通常认为g=9.8ms-2,但实际上在地球表面不同维度和不同高度,g的值会有所不同,例如在赤道海平面g=9.78046ms-2。要求写一个计算物体重力的嵌套函数,将g和m两个参数分别赋值。

>>> def grav(g):
...     def qual(m):
...         G = m * g
...         return G
...     return qual
... 
>>> grav(9.8)(2.5)
24.5
>>> grav(9.78046)(2.5)
24.45115

25、假设列表中有多个文件名,编写程序,从这些文件中选出图片文件,即扩展名分别是('.jpg', '.gif', '.png')的文件。

['a.py', 'b.jpg', 'c.gif', 'd.map', 'e.png', 'f.jpg', 'k.txt', 'f.gif', 'h.png', 'm.docx']

[oldboy@linux-node3 ~]$ cat pictures_judge.py 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
# Author:ChengZi
# Version:1.0
# Filename: jc_func.py
# Description:This script is used for 
"""
lst = ['a.py','b.jpg','c.gif','d.map','e.png','f.jpg','k.txt','f.gif','h.png','m.docx']
pts = ('.jpg','.gif','.png')

pics = [i for i in lst if i.endswith(pts)]
print(lst)
print(pics)
[oldboy@linux-node3 ~]$ python3 pictures_judge.py 
['a.py', 'b.jpg', 'c.gif', 'd.map', 'e.png', 'f.jpg', 'k.txt', 'f.gif', 'h.png', 'm.docx']
['b.jpg', 'c.gif', 'e.png', 'f.jpg', 'f.gif', 'h.png']

26、有列表[1, "a", 2, "b", 3, "c", 4, "d"],要求交替使用列表中的元素作为字典的键和值,创建一个字典,即得到字典{1: "a", 2: "b", 3: "c", 4: "d"}

>>> lst = [1, "a", 2, "b", 3, "c", 4, "d"]
>>> k_list = [lst[i] for i in range(0,len(lst)) if int(i)%2 == 0]
>>> v_list = [lst[i] for i in range(0,len(lst)) if int(i)%2 == 1]
>>> k_list
[1, 2, 3, 4]
>>> v_list
['a', 'b', 'c', 'd']
>>> dict(zip(k_list,v_list))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

拓展:求出得到的字典后,value值原始的key值

>>> lst = [1, "a", 2, "b", 3, "c", 4, "d"]
>>> [i for i in range(0,len(lst)) if int(i)%2 == 1]
[1, 3, 5, 7]
>>> [lst[i] for i in range(0,len(lst)) if int(i)%2 == 1]
['a', 'b', 'c', 'd']
>>> k_list = [i for i in range(0,len(lst)) if int(i)%2 == 1]
>>> v_list = [lst[i] for i in range(0,len(lst)) if int(i)%2 == 1]
>>> kv = set(zip(k_list,v_list))
>>> kv
{(1, 'a'), (7, 'd'), (3, 'b'), (5, 'c')}

27、假设有文件名:py10.py,py2.py,py1.py,py14.py,编写函数对文件名进行排序

import re

def select_numbers(s):
    pieces = re.compile(r'(\d+)').split(s)
    pieces[1::2] = map(int, pieces[1::2])
    return pieces

def sort_filename(filename):
    return sorted(filename, key=select_numbers)

files = ['py10.py', 'py2.py', 'py1.py', 'py14.py']
result = sort_filename(files)
print(files)
print(result)

28、打印菱形

# 打印菱形
#    *
#   ***
#  ***** 
# *******
#  *****
#   ***
#    *
# 方法1
n = int(input("请输入菱形*号最大长度>>>: ").strip())
for i in range(-((n-1)//2),(n+1//2)):
    if i < 0:
        spaces = -i
    else:
        spaces = i
    print((''* spaces + "*" *(n-2*spaces)).center(n+1))

# 方法2
k = ((n+1)//2)
for i in range(1,n+1):
    if i == k:
        print(("*" * n).center(n+1))
    elif i > k:
        print(("*" * (n - (i%k)*2)).center(n+1))
    else:
        print(("*" * (i * 2 -1)).center(n+1))

29、打印对顶三角形

# 打印对顶三角形
# *******
#  *****
#   ***
#    *
#    *
#   ***
#  *****
# *******
# 方法1
e = n // 2
for i in range(-e,n - e):
    print((e - abs(i))* ' ' + (2*(abs(i))+1)* '*')
    
# 方法2
k = ((n+1)//2)
for i in range(1,n+1):
    if i <= k:
        print(("*" * (n-(2*i-2))).center(n+1))
    else:
        print(("*" * (2*i-n)).center(n+1))

 30、打印闪电

# 打印闪电
#    *
#   **
#  ***
# *******
#    ***
#    **
#    *
# 方法1:
n = 9
e = n // 2
x = n - e
for i in range(-e,x):
    if i < 0:
        print(('' * -i + (x + i)* '*'))
    elif i > 0:
        print((' ' * e + (x - i)* '*'))
    else: #i == 0
        print('*' * n)
# 方法2
k = ((n+1)//2)
for i in range(1,n+1):
    if i < k:
        print((('*' * i).rjust(k) + (' ' * k)))
    elif i == k:
        print(('*' * n).center(n))
    else:
        print(((' ' * (k - 1)) + ('*' * (n + 1 - i))).ljust(k))

31、求斐波那契数列第101项数值

# 求斐波那契数列第101项数值
# 斐波那契数列:0 1 1 2 3 5 8 13 21 34 55 ...
n = int(input("请输入数列的序列号>>>: ").strip())

def fibs(num):
    res = [0,1]
    for i in range(num-2):
        res.append(res[-2] + res[-1])
    return res
cnum = fibs(n)
print("斐波那契数列第{}项数值为:".format(n),cnum[n-1])