美文网首页
Python 100练习题 Day1

Python 100练习题 Day1

作者: P酱不想说话 | 来源:发表于2021-03-15 01:09 被阅读0次

Question 1

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.b

for i in range(2000, 3200):
    if i%7==0 and i%5!=0:
        print(i,end=',')
print("\b")

summary:

自己写的时候没有使用\b,导致最后的结尾是以逗号结尾。\b的作用是退格

Question 2

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.

n = int(input())
Result = 1
for i in range(1,n+1):
#     print(i)
    Result = Result * i
print(Result)

示例答案:

def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x = int(raw_input())
print fact(x)

summary:

其实用函数的方法会更好一点,而且在示例里的raw_input()输入的方法是Python2.X的方法。

Question 3

Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i x 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()

个人解法

def fuc(x):
    key = []
    value = []
    for i in range(1, x+1):
        key.append(i)
        value.append(i*i) 
    return dict(zip(key, value))
    
x = int(input())
print(fuc(x))

好的解法

n = int(input())
ans={i : i*i for i in range(1,n+1)}
print(ans)

summary:

两个列表合成字典
===> list X and list Y
===>dict(zip(X,Y))
zip():zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

相关文章

网友评论

      本文标题:Python 100练习题 Day1

      本文链接:https://www.haomeiwen.com/subject/pxpiqltx.html