草庐IT

【Python编程基础练习】 Python编程基础练习100题学习记录第一期(1~10)

”心有猛虎,细嗅蔷薇。“ 2023-04-15 原文

1.此为GitHub项目的学习记录,记录着我的思考,代码基本都有注释。
2.可以作为Python初学者巩固基础的绝佳练习,原题有些不妥的地方我也做了一些修正。
3.建议大家进行Python编程时使用英语,工作时基本用英语。
4.6~17题为level1难度,18-22题为level3难度,其余都为level1难度。
项目名称:
100+ Python challenging programming exercises for Python 3

#!usr/bin/env Python3.9     # linux环境运行必须写上
# -*- coding:UTF-8 -*-      # 写一个特殊的注释来表明Python源代码文件是unicode格式的

"""Question:
    Write a program which will find all such numbers
    which are divisible by 7 but are not a multiple of 5,
    between 2000 and 3200 (both included).
    The numbers obtained should be printed
    in a comma-separated sequence on a single line."""

'''Hints: Consider use range(#begin, #end) method'''

l1 = []  # 建立空列表
for i in range(2000, 3201):     # for循环寻找能被7整除但不能被5整除的数字
    if (i % 7 == 0) and (i % 5 != 0):
        l1.append(str(i))       # 列表里的数据需要是字符串
print(','.join(l1))             # 在一行显示,以逗号隔开
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program which can compute the factorial of a given numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
"""

'''Hints: In case of input data being supplied to the question, it should be assumed to be a console input.'''
i = 1
result = 1
t = int(input('请输入一个数字: '))
while i <= t:                   # while循环
    result = result * i         # 实现阶乘
    i += 1
print(result)

# 源代码
'''
def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x=int(input('请输入一个数字: '))
print(fact(x))
'''
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Question:
With a given integral number n,
write a program to generate a dictionary
that contains (i, i*i) such that is an integral number between 1 and n (both included).
and then the program should print the dictionary.
Suppose the following input is supplied to the program: 8
Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input. 
Consider use dict()
'''
m = int(input('请输入一个数字1~n:'))
n = {}                      # 创建一个空字典
for i in range(1, m+1):
    n[i] = (i * i)          # 将键值对存入空字典
    i += 1
print(n)

# 源代码
'''
n=int(input())
d=dict()
for i in range(1,n+1):
    d[i]=i*i

print(d)

'''
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple
which contains every number.
Suppose the following input is supplied to the program: 34,67,55,33,12,98
Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98')
"""

'''
Hints: In case of input data being supplied to the question, 
it should be assumed to be a console input. 
tuple() method can convert list to tuple
'''

import re

t = input('请输入数据:')
d = t.split(',')                 # split()函数按照所给参数分割序列
k = re.findall(r'\d+', t)        # findall()函数在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回
# \d  相当于[0-9],匹配0-9数字
r = tuple(k)                     # 转换为元组类型
print(k)
print(r)

#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Define a class which has at least two methods:
getString: to get a string from console
input printString: to print the string in upper case.
Also please include simple test function to test the class methods.
"""

'''
Hints: Use init method to construct some parameters
'''


class InputOutputString():      # 创建类函数
    def __init__(self):
        self.s = ''

    def __getString__(self):
        self.s = input('Please input what you want:')

    def __printString__(self):
        print(self.s.upper())       # upper()函数使字符串字母变为大写


stringRan = InputOutputString()
stringRan.__getString__()
stringRan.__printString__()

#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H: C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example Let us assume the following comma separated input sequence is given to the program: 100,150,180
The output of the program should be: 18,22,24
"""

'''
If the output received is in decimal form, 
it should be rounded off to its nearest value 
(for example, if the output received is 26.0, it should be printed as 26) 
In case of input data being supplied to the question, it should be assumed to be a console input.
'''

import math

C = 50
H = 30
value = []      # 创建空列表
t = input('Please input your values, example:34, 23, 180, ... :')
x = [i for i in t.split(',')]           # 列表推导式

for d in x:
    value.append(str(round(math.sqrt((2 * C * float(d)) / H))))  # round()函数实现四舍五入,sqrt表示平方

print(','.join(value))
#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array.
The element value in the i-th row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1,¡..., Y-1.
Example Suppose the following inputs are given to the program: 3,5
Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
"""

'''
Note: In case of input data being supplied to the question, 
it should be assumed to be a console input in a comma-separated form.
'''

input_String = input('Please input 2 digits, example:2,3.:')
dimensions = [int(x) for x in input_String.split(',')]  # 表示数组行数和列数
rowNum = dimensions[0]  # 赋予行数
colNum = dimensions[1]  # 赋予列数
multi_list = [[0 for col in range(colNum)] for row in range(rowNum)]  # 创建一个空数组列表

for col in range(colNum):
    for row in range(rowNum):
        multi_list[row][col] = col * row  # 向空数组填入数值
print(multi_list)

#!usr\bin\env Python3
# encoding:UTF-8

"""
Question:
Write a program that accepts a comma separated sequence of words as input
and prints the words in a comma-separated sequence after sorting them alphabetically.
Suppose the following input is supplied to the program: without,hello,bag,world
Then, the output should be: bag,hello,without,world
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
'''

temp = input('Please input your words:')
inputStr = temp.split(',')              # 按“, ”分隔输入的单词
inputStr.sort()                         # 按字母顺序进行排列
print(','.join(inputStr))               # 输出按字母顺序排列的单词,单词之间用逗号分隔


# 源代码
"""
items=[x for x in input().split(',')]
items.sort()
print(','.join(items))
"""
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-

"""
Question:
Write a program that accepts sequence of lines as input
and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program: Hello world Practice makes perfect
Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
'''
lines = []

while True:
    s = input('Please input your sentences:')
    if s:
        lines.append(s.upper())             # 将大写过后的句子放进列表里,可以放进去多个句子
    else:
        break

for sentence in lines:                      # 打印每一句句子
    print(sentence)
#!usr/bin/env Python3.9
# -*- coding:UTF-8 -*-
"""
Question:
Write a program that accepts a sequence of whitespace separated words as input
and prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again
Then, the output should be: again and hello makes perfect practice world
"""

'''
Hints: In case of input data being supplied to the question, it should be assumed to be a console input. 
We use set container to remove duplicated data automatically and then use sorted() to sort the data.
'''

temp = input('Please input your words: ')               # 输入想说的话
words = [x for x in temp.split(' ')]                    # 按照空格分割,把单词放进列表

print(' '.join(sorted(list(set(words)))))               # 用set()函数创建一个无序的、不重复(可利用这一点删除重复元素)
                                                        # 元素集,并可进行与或等运算。经过排序后再用空格分隔装进列表打印出来

再附上Python常用标准库供大家学习使用:
Python一些常用标准库解释文章集合索引(方便翻看)

“学海无涯”

有关【Python编程基础练习】 Python编程基础练习100题学习记录第一期(1~10)的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  3. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  4. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  5. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  6. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  7. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  8. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  9. 网络编程套接字 - 2

    网络编程套接字网络编程基础知识理解源`IP`地址和目的`IP`地址理解源MAC地址和目的MAC地址认识端口号理解端口号和进程ID理解源端口号和目的端口号认识`TCP`协议认识`UDP`协议网络字节序socket编程接口`sockaddr``UDP`网络程序服务器端代码逻辑:需要用到的接口服务器端代码`udp`客户端代码逻辑`udp`客户端代码`TCP`网络程序服务器代码逻辑多个版本服务器单进程版本多进程版本多线程版本线程池版本服务器端代码客户端代码逻辑客户端代码TCP协议通讯流程TCP协议的客户端/服务器程序流程三次握手(建立连接)数据传输四次挥手(断开连接)TCP和UDP对比网络编程基础知识

  10. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

随机推荐