小练手2

1.
"""
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
"""
def fun(word):
    u = 0
    l = 0
    for i in word:
        if i.isupper():
            u += 1
        elif i.islower():
            l += 1
    return print(‘大写{}\n小写{}‘.format(u, l))
fun(‘Hello world!‘)

2.
"""
Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
"""
def fun(num):
    return print(int(num)+int(num*2)+int(num*3)+int(num*4))
fun(‘9‘)

3.
"""
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
"""
def fun(word):
    li = [i for i in word.split(‘,‘) if int(i)%2!=0]
    return print(‘,‘.join(li))
fun(‘1,2,3,4,5,6,7,8,9‘)

4.
"""
Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following:
D 100
W 200

D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100
Then, the output should be:
500
"""
def fun():
    count = 0
    while True:
        word = input(‘请输入操作类型和金额,以空格分割:‘)
        if word:
            try:
                type = word.split(‘ ‘)[0]
                num = word.split(‘ ‘)[1]
            except Exception as e:
                print(‘格式错误!‘)
                continue
            if type == ‘D‘:
                count += int(num)
            elif type == ‘W‘:
                if count - int(num) > 0:
                    count -= int(num)
                else:
                    print(‘余额不足!‘)
            else:
                pass
            continue
        else:
            print(count)
            break
fun()

5.
"""
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
[email protected],a F1#,2w3E*,2We3345
Then, the output of the program should be:
[email protected]
"""
import re
def fun(word):
    li = []
    for i in word.split(‘,‘):
        if re.match(‘^(?=.*[a-z])(?=.*[A-Z])(?=.*[$#@])(?=.*[0-9])[A-Za-z0-9$#@]{6,12}$‘,i):
            li.append(i)
    return print(‘,‘.join(li))

fun(‘[email protected],a F1#,2w3E*,2We3345‘)

6.
"""
You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is:
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
If the following tuples are given as input to the program:
Tom,19,80
John,20,90
Jony,17,91
Jony,17,93
Json,21,85
Then, the output of the program should be:
[(‘John‘, ‘20‘, ‘90‘), (‘Jony‘, ‘17‘, ‘91‘), (‘Jony‘, ‘17‘, ‘93‘), (‘Json‘, ‘21‘, ‘85‘), (‘Tom‘, ‘19‘, ‘80‘)]
"""
from operator import itemgetter
def fun():
    li = []
    while True:
        word = input()
        if not word:
            break
        li.append(word)
    return print(sorted(li,key=itemgetter(0,1,2)))

fun()

7.
"""
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
"""
def fun(n):
    for i in range(n):
        if i %7 == 0:
            yield i

for i in fun(100):
    print(i)

8.
"""
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡­
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:
2
"""
import math
def fun():
    zero = [0, 0]
    while True:
        word = input(‘‘)
        if word:
            type,steep = word.split(‘ ‘)[0],int(word.split(‘ ‘)[1])
            if type == ‘UP‘:
                zero[1] += steep
                continue
            elif type == ‘DOWN‘:
                zero[1] -= steep
                continue
            elif type == ‘LEFT‘:
                zero[0] -= steep
                continue
            elif type == ‘RIGHT‘:
                zero[0] += steep
                continue
            else:
                print(‘格式有误,请重新输入!‘)
                continue
        else:
            print(int(math.sqrt(zero[0]*zero[0]+zero[1]*zero[1])))
            break
fun()

9.
"""
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1
"""
def fun(word):
    dic = {}
    for i in word.split(‘ ‘):
        if i not in dic.keys():
            dic[i] = 1
        else:
            dic[i] += 1
    dic1 = sorted(dic.keys())
    for i in dic1:
        print(i+‘:‘+str(dic[i]))
fun(‘New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.‘)

10.
"""
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input
"""
def fun(num):
    li = []
    if num>0:
        for i in range(1,num+1):
           li.append(i/(i+1))
    else:
        return print(sun(li))
    return print(round(sum(li),2))
fun(5)

原文地址:https://www.cnblogs.com/miaoweiye/p/12036479.html

时间: 2024-08-30 06:25:48

小练手2的相关文章

Java程序与RSR232串口通讯小练手(转载)

一直以来都是在学习J2EE方面的应用系统开发,从未想过用JAVA来编写硬件交互程序,不过自己就是喜欢尝试一些未曾接触的新东西.在网上搜索了些资源,了解到JAVA写串口通讯的还是蛮多的,那么便着手准备开发调试环境.软件程序开发环境搭建不成问题,可这硬件环境就有点犯难啦.更何况自己用的是笔记本哪来的串口呀,再说要是真拿这串口硬件来自己也不会弄,随即想到了虚拟机,觉得这东西应该也有虚拟的吧,果真跟自己的猜测一样还真有这东西,顺便也下载了个串口小助手做为调试之用.下面就先看看软件环境的搭建: 1.下载c

微信小程序框架分析小练手(二)——天气微信小程序制作

简单的天气微信小程序. 一.首先,打开微信开发者工具,新建一个项目:weather.如下图: 二.进入app.json中,修改导航栏标题为“贵州天气网”. 三.进入index.wxml,进行当天天气情况的界面布局,包括温度.最低温度和最高温度.天气情况.城市.星期.风向情况.如下图: 四.进入index.js,在data里提供天气数据,让这些数据在界面里显示出来: 五.进入index.wxml,将data里提供的天气数据绑定到页面里: 界面效果如下: 六.进入index.wxss,为index.

微信小程序组件构建UI界面小练手 —— 表单登录注册微信小程序

通过微信小程序中丰富的表单组件来完成登录界面.手机快速注册界面.企业用户注册界面的微信小程序设计. 将会用到view视图容器组件.button按钮组件.image图片组件.input输入框组件.checkbox多项选择器组件.switch开关选择组件.navigator页面连接组件等. Ⅰ.登录设计 登录表单中,需输入账号.密码进行登录,在账号.密码输入框中都有友好的提示信息:登录按钮默认是灰色不可用状态,只有输入内容后,才会变为可用状态:在登录按钮下面提供手机快速注册.企业用户注册.找回密码链

【辅助程序】练手小程序:记录外网动态IP地址

练手小程序 程序作用:对IP实时记录: 1.定时获取外网IP,存储在本地文件中: 编写思路: 1)收集获取外网的API接口 http://bbs.125.la/thread-13838979-1-1.html 2)定时执行 http://blog.csdn.net/imzoer/article/details/8699083/ 4)记录本地文件 1 # -*- coding: utf-8 -*- 2 # -*- coding: gbk -*- 3 # Date: 2016/4/27 4 # Cr

WEBGL学习笔记(七):实践练手1-飞行类小游戏之游戏控制

接上一节,游戏控制首先要解决的就是碰撞检测了 这里用到了学习笔记(三)射线检测的内容了 以鸟为射线原点,向前.上.下分别发射3个射线,射线的长度较短大概为10~30. 根据上一节场景的建设,我把y轴设为前进方向,z轴设为高度~ 如果射线返回有结果,那么说明鸟遇到了障碍物.代码如下: var raycaster1 = new THREE.Raycaster(birdmesh.position, new THREE.Vector3(0, 1, 0), 0, 30) var raycaster2 =

练手小项目(2)-生活小助手--周公解梦

第一篇 练手小项目(2)-生活小助手--身份证查询 第二篇 练手小项目(2)-生活小助手--星座运势查询 我在想就是第三个药品查询要不要写出来,因为布局还在讨论用什么展示,因为药品有很多展示,我也不知道用什么展示. 这是一个很纠结的事情 我就先写第四个吧 周公解梦 其中代码有点错误我想用for循环进行判断返回数据有几个 但是总是失败,如果有看本篇贴子,解决了,给我留个言,在这篇帖子我只显示一个结果 布局跟简单的说 一个Edittext 获取数据,然后button进行数据提取发送到服务器 返回的数

练手小项目(2)-生活小助手--星座运势查询

上一篇内容 练手小项目(2)-生活小助手 今天星期一.趁着中午的歇息时间把 第二个写出来 星座运势,近期看看极客学院 用聚合数据做了天气预报的视频教程,不好评价他.看他在后面的代码变更那么大,我就知道,后面肯定做不下去,于是.就改代码了.代码变更那么大,有几个人会去理解,还不如我自己写................ 先看布局 点击去就是一个spinner 用几个textview显示查询内容   布局有点丑,主要是给别人做功能,UI我就不考虑 关于UI  我还是要贴下代码.假设你有想法就把他美化

练手WPF(三)——扫雷小游戏的简易实现(中)

原文:练手WPF(三)--扫雷小游戏的简易实现(中) 八.随机布雷 /// <summary> /// 随机布地雷 /// </summary> /// <param name="mineNum">地雷数</param> private void SetRndMine(int mineNum) { for (int k = 0; k < mineNum; k++) { int nullnum = 0; for (int j = 0;

java客房管理小项目,适合java小白练手的项目!

java客房管理小项目 这个客房管理小项目,适合java初学者练手.功能虽然不多,但是内容很齐全! 喜欢这样文章的可以关注我,我会持续更新,你们的关注是我更新的动力!需要更多java学习资料的也可以私信我! 祝关注我的人都:身体健康,财源广进,福如东海,寿比南山,早生贵子,从不掉发!共有5层,每层10间客房,以数字101--509标示:具有入住,退房,搜索,退出四个简单功能: public class Hotel { static final int floor = 5; static fina