github python100题笔记

目录

Question 2 阶乘问题

lambda函数

Question 4列表元组

Question 5

Question 6

Question 7

Question 8

Question 9

Question 10

Question 11

Question

Question 12

Question:

Question 15

Question 15

Question:

Hints:

Question 16

Question:

Question:

Question 18

Question:

Question 19

Question:

Hints:

Question 20

Question:

Question 21

Question:

Hints:

Question 22-25

Question 32

Question 39

Question 45

Question 50

Question 53

Question 56

Question 61

Question 63

Question 64

Question 65

Question 67

Question 68




Question 2 阶乘问题

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

也就是阶乘,一般有while循环 for循环

  • Using While Loop

    n = int(input()) #input() function takes input as string type
                     #int() converts it to integer type
    fact = 1
    i = 1
    while i <= n:
        fact = fact * i;
        i = i + 1
    print(fact)

  • Using For Loop

    n = int(input()) #input() function takes input as string type
                    #int() converts it to integer type
    fact = 1
    for i in range(1,n+1):
        fact = fact * i
    print(fact)

  • Using Lambda Function

    # Solution by:  harshraj22
    
    n = int(input())
    def shortFact(x): return 1 if x <= 1 else x*shortFact(x-1)
    print(shortFact(n))

  • 第三个没有用lambda 但是那种应该也叫lambda函数吧,自己仿写一个
fact=lambda n: 1 if n <= 1 else n*fact(n-1)
print(fact(int(input())))

lambda函数

插:这里加一个lambda函数的简单用法,做个笔记

学习地址:【Python】lambda - 匿名函数的基本用法_哔哩哔哩_bilibili

1.

def add(a,b=1):
    return a+b
print(add(10,20))
print(add(10))

输出结果为:

30

11

那么改成lambda表示

add_lambda=lambda a,b=1:a+b
print(add_lambda(10,20))
print(add_lambda(10))

 2.if 条件文

get_odd_even = lambda x:'even' if x%2==0 else 'odd'
print(get_odd_even(8))
print(get_odd_even(9))

3.无参数表达式

import random
ran_lambda=lambda:random.random()
print(ran_lambda())
print(ran_lambda())
print(ran_lambda())

4.活用例map()

def add(x):
    return x**2
mobj=map(add,[1,2,3,4])
print(list(mobj))
mobj=map(lambda x:x**2,[1,2,3,4,5])
print(list(mobj))

Question 3创建字典

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

链接:Python 字典(Dictionary) | 菜鸟教程 (runoob.com)

  • 键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行
  • Using for loop
n = int(input())
ans = {}
for i in range (1,n+1):
    ans[i] = i * i
print(ans)
  • Using dictionary comprehension
n = int(input())
ans={i : i*i for i in range(1,n+1)}
print(ans)
num = int(input("Number: "))
print(dict(list(enumerate((i * i for i in range(num+1))))))

for 循环挺好理解的,这里看到了新的结构,就是在字典里的循环,第一次见。找了些博客,看到一个。

链接:https://blog.csdn.net/weixin_42608414/article/details/109923442https://blog.csdn.net/weixin_42608414/article/details/109923442

 这里写了尽量不要使用map函数,因为其可读性差,不容易理解。

enumerate()函数

链接:Python enumerate() 函数 | 菜鸟教程 (runoob.com)

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

Question 4列表元组

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

lst = input()#.split(",")
# the input is being taken as string and as it is string it has a built in
# method name split. ',' inside split function does split where it finds any ','
# and save the input as list in lst variable

tpl = tuple(lst)  # tuple method converts list to tuple

print(lst)
print(tpl)

tuple()函数:tuple 函数将可迭代系列(如列表)转换为元组。

Question 5

首先学一下class(),知识盲区了属于是。

链接https://blog.csdn.net/weixin_50123771/article/details/108960333

https://blog.csdn.net/weixin_50123771/article/details/108960333

那么在学习中了解到了初始化的概念,那么要不要初始化呢,或者说什么时候要用。找了一些博客,说,在有实例变量的时候需要,什么又是实例化呢

链接:python中实例化是什么-Python学习网

Question 6

Write a program that calculates and prints the value according to the given formula:

Q = Square root of [(2 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.For 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

Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

所以本题最后将int转换成了str 再用的join函数。

round函数如果没指定小数点位数,就是int型(应该吧)

from math import sqrt  # import specific functions as importing all using *

# is bad practice

C, H = 50, 30


def calc(D):
    return sqrt((2 * C * D) / H)


D = [int(i) for i in input().split(",")]  # splits in comma position and set up in list
D = [int(i) for i in D]  # converts string to integer
D = [calc(i) for i in D]  # returns floating value by calc method for every item in D
D = [round(i) for i in D]  # All the floating values are rounded
D = [
    str(i) for i in D
]  # All the integers are converted to string to be able to apply join operation

print(",".join(D))
from math import sqrt

C, H = 50, 30


def calc(D):
    return sqrt((2 * C * D) / H)


D = input().split(",")  # splits in comma position and set up in list
D = [
    str(round(calc(int(i)))) for i in D
]  # using comprehension method. It works in order of the previous code
print(",".join(D))

这里又用到了list内循环。

Question 7

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

答案:

x, y = map(int, input().split(","))
lst = []

for i in range(x):
    tmp = []
    for j in range(y):
        tmp.append(i * j)
    lst.append(tmp)

print(lst)
x, y = map(int, input().split(","))
lst = [[i * j for j in range(y)] for i in range(x)]
print(lst)

这里都用了map函数说明很有用啊,那还是学一学吧

链接:https://www.runoob.com/python/python-func-map.html

 举个例子:

list(map(square, [1,2,3,4,5]))   # 使用 list() 转换为列表
[1, 4, 9, 16, 25]
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

答案里呢,就用map函数把输入int了一遍。

我的解答:

x,y=input().split(',')
x=int(x)
y=int(y)
lis=[[i*j for i in range(y)] for j in range(x)]
print(lis)

list内循环是真香啊

Question 8

sort()函数 排序

sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。

list.sort( key=None, reverse=False)
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。

Question 9

答案没看明白

lst = []

while input():
    x = input()
    if len(x) == 0:
        break
    lst.append(x.upper())

for line in lst:
    print(line)

OR

def user_input():
    while True:
        s = input()
        if not s:
            return
        yield s


for line in map(str.upper, user_input()):
    print(line)
  • 什么是generator?
  • 是一个生成器,可以生成一个个东西,通过next(),是一个iterable
  • 为什么要用generator?
  • 列表很大的时候,Generator按需给你产生,不会一次性生成而占用很大的内存

yield

https://www.bilibili.com/video/BV1aK4y1k7jZ?p=2&spm_id_from=333.880.my_history.page.clickhttps://www.bilibili.com/video/BV1aK4y1k7jZ?p=2&spm_id_from=333.880.my_history.page.click

ls=[]
while True:
    x=input()
    if len(x)!=0:
        ls.append(x.upper())
    else:
        break
for line in ls:
    print(line)
lines = []
while True:
    s = input()
    if s:
        lines.append(s.upper())
    else:
        break;

for sentence in lines:
    print(sentence)

while input():  和whileTrue: 有什么区别

  • sort和sorted的区别:

  1. sort 是应用在 list 上的方法,属于列表的成员方法,sorted 可以对所有可迭代的对象进行排序操作。
  2. list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
  3. sort使用方法为ls.sort(),而sorted使用方法为sorted(ls)

Question 10

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

我的答案:

words=input().split()
x=set(words)
y=list(x)
y.sort()
print(" ".join(y))

想到了集合的用法,set函数,集合类型能够过滤重复元素。

查了相关资料,split()返回的是列表类型

给出的答案也有用到set函数:

word = sorted(
    list(set(input().split()))
)  #  input string splits -> converting into set() to store unique
#  element -> converting into list to be able to apply sort
print(" ".join(word))

 感觉和答案一样,用的sorted 这样嵌套方便。

其他的答案:

用到while和count:

word = input().split()

for i in word:
    if (
        word.count(i) > 1
    ):  # count function returns total repeatation of an element that is send as argument
        word.remove(i)  # removes exactly one element per call

word.sort()
print(" ".join(word))
OR

word = input().split()
[
    word.remove(i) for i in word if word.count(i) > 1
]  # removal operation with comprehension method
word.sort()
print(" ".join(word))

Question 11

Question

Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.

Example:

0100,0011,1010,1001

Then the output should be:

1010

Notes: Assume the data is input by console.

我的答案:

ls=[]
calc=[]
nums=input().split(',')
for number in nums:
    ls.append(int(number, 2))
for i in ls:
    if i%5==0:
        calc.append(bin(i)[2:])
print(",".join(calc))

 用int 输出十进制,bin输出二进制,[2:]隐藏0b

那试着用一下lambda函数和map函数吧

calc=[]
nums=input().split(',')
ls=list(map(lambda number:int(number, 2),nums))
for i in ls:
    if i%5==0:
        calc.append(bin(i)[2:])
print(",".join(calc))

lambda函数 搭配for循环有待研究,输出的是地址,不是值 

其他答案:

filter函数

Python3 filter() 函数 | 菜鸟教程 (runoob.com)https://www.runoob.com/python3/python3-func-filter.html过滤掉不符合规定的元素,通常会定义一个函数。

Question 12

Question:

Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line.

lst = []

for i in range(1000, 3001):
    flag = 1
    for j in str(i):  # every integer number i is converted into string
        if ord(j) % 2 != 0:  # ord returns ASCII value and j is every digit of i
            flag = 0  # flag becomes zero if any odd digit found
    if flag == 1:
        lst.append(str(i))  # i is stored in list as string

print(",".join(lst))
OR

def check(element):
    return all(
        ord(i) % 2 == 0 for i in element
    )  # all returns True if all digits i is even in element


lst = [
    str(i) for i in range(1000, 3001)
]  # creates list of all given numbers with string data type
lst = list(
    filter(check, lst)
)  # filter removes element from list if check condition fails
print(",".join(lst))
OR

lst = [str(i) for i in range(1000, 3001)]
lst = list(
    filter(lambda i: all(ord(j) % 2 == 0 for j in i), lst)
)  # using lambda to define function inside filter function
print(",".join(lst))

 str 和ord 函数配合用 很不错。

filter 和all 都返回 True 和False。

Question 15

Question 15

Question:

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


Hints:

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


Solutions:


a = input()
total, tmp = 0, str()  # initialing an integer and empty string

for i in range(4):
    tmp += a  # concatenating 'a' to 'tmp'
    total += int(tmp)  # converting string type to integer type

print(total)
OR

a = input()
total = int(a) + int(2*a) + int(3*a) + int(4*a)  # N*a=Na, for example  a="23", 2*a="2323",3*a="232323"
print(total)


 

这题应该注意的是input输入的是字符那么2*a 那么就是两个字符累计。学到了学到了

Question 16

Question:

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,9,25,49,81

这题看着挺简单的,但是在输出的时候出问题了,我的第一遍代码如下:

ls=input().split(",")
for i in ls:
    if int(i)%2==0:
        ls.remove(i)
a=list(map(lambda x:int(x)**2),ls)
print(",".join(a))

输出会报错:

print(",".join(a))
TypeError: sequence item 0: expected str instance, int found

这里查了资料说是,列表里面要是有数字,不能直接转换成字符串,要str一下。我于是改了一下,

ls=input().split(",")
for i in ls:
    if int(i)%2==0:
        ls.remove(i)
a=list(map(lambda x:str(int(x)**2),ls))
print(",".join(a))

这样就好了,从网上又学到了在join上下功夫

print(",".join(map(str,a)))

亲测可用,最近简直是被 lambda和map种草,但是都说map函数可读性差,用for循环最好,为了不忘了for循环怎么用哈哈哈哈 ,再用for写一下 也不用lambda试一试。

附:map函数再python3中返回的是迭代器不是列表。

ls=input().split(",")
for i in ls:
    if int(i)%2==0:
        ls.remove(i)
calc=[]
for i in ls:
    x=int(i)**2
    calc.append(x)
print(",".join(str(i) for i in calc))

 那么现在去看看答案怎么写的。

lst = [str(int(i) ** 2) for i in input().split(",") if int(i) % 2]
print(",".join(lst))
"""Solution by: shagun"""

lst = input().split(",")  # splits in comma position and set up in list

seq = []
lst = [int(i) for i in lst]  # converts string to integer
for i in lst:
    if i % 2 != 0:
        i = i * i
        seq.append(i)


seq = [
    str(i) for i in seq
]  # All the integers are converted to string to be able to apply join operation
print(",".join(seq))

第一个解法就是list内嵌套for循环和if语句,如果if放在for前面就要补全else

Question 17

Question:

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

我的代码 但是报错了,如果不放在while循环里就没问题

count=0
while True:
    sr=input()
    if sr=='\n':
        break
    elif sr[0] == 'D':
        count+=int(sr[2:])
    elif sr[0] == 'W':
        count-=int(sr[2:])
print(count)

有待解决。

答案都是借用了列表

lst = []
while True:
    x = input()
    if len(x) == 0:
        break
    lst.append(x)

balance = 0
for item in lst:
    if "D" in item:
        balance += int(item.strip("D "))
    if "W" in item:
        balance -= int(item.strip("W "))
print(balance)
lines = []
while True:
    loopInput = input()
    if loopInput == "done":
        break
    else:
        lines.append(loopInput)

lst = list(int(i[2:]) if i[0] == "D" else -int(i[2:]) for i in lines)
print(sum(lst))

Question 18

Question:

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:

  • At least 1 letter between [a-z]
  • At least 1 number between [0-9]
  • At least 1 letter between [A-Z]
  • At least 1 character from [$#@]
  • Minimum length of transaction password: 6
  • 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:

ABd1234@1,a F1#,2w3E*,2We3345

Then, the output of the program should be:

ABd1234@1

自己的答案最终被for和if套进去了出不来了。

def is_low(x):  # Returns True  if the string has a lowercase
    for i in x:
        if "a" <= i and i <= "z":
            return True
    return False


def is_up(x):  # Returns True  if the string has a uppercase
    for i in x:
        if "A" <= i and i <= "Z":
            return True
    return False


def is_num(x):  # Returns True  if the string has a numeric digit
    for i in x:
        if "0" <= i and i <= "9":
            return True
    return False


def is_other(x):  # Returns True if the string has any "$#@"
    for i in x:
        if i == "$" or i == "#" or i == "@":
            return True
    return False


s = input().split(",")
lst = []

for i in s:
    length = len(i)
    if (
        6 <= length
        and length <= 12
        and is_low(i)
        and is_up(i)
        and is_num(i)
        and is_other(i)
    ):  # Checks if all the requirments are fulfilled
        lst.append(i)

print(",".join(lst))
aaaaa

OR

def check(x):
    cnt = 6 <= len(x) and len(x) <= 12
    for i in x:
        if i.isupper():
            cnt += 1
            break
    for i in x:
        if i.islower():
            cnt += 1
            break
    for i in x:
        if i.isnumeric():
            cnt += 1
            break
    for i in x:
        if i == "@" or i == "#" or i == "$":
            cnt += 1
            break
    return (
        cnt == 5
    )  # counting if total 5 all conditions are fulfilled then returns True


s = input().split(",")
lst = filter(
    check, s
)  # Filter function pick the words from s, those returns True by check() function
print(",".join(lst))
OR

import re

s = input().split(",")
lst = []

for i in s:
    cnt = 0
    cnt += 6 <= len(i) and len(i) <= 12
    cnt += bool(
        re.search("[a-z]", i)
    )  # here re module includes a function re.search() which returns the object information
    cnt += bool(
        re.search("[A-Z]", i)
    )  # of where the pattern string i is matched with any of the [a-z]/[A-z]/[0=9]/[@#$] characters
    cnt += bool(
        re.search("[0-9]", i)
    )  # if not a single match found then returns NONE which converts to False in boolean
    cnt += bool(re.search("[@#$]", i))  # expression otherwise True if found any.
    if cnt == 5:
        lst.append(i)

print(",".join(lst))

自己的思想被套在那里了,要把问题细分,一个一个解决问题,不要老在那套娃,答案的两个解法清晰,看着也明白,多试着用定义函数,还有return

python re库入门(正则表达式) - 星空纪 - 博客园 (cnblogs.com)

我的答案:

借鉴了一下

password=input().split(",")
sc=[]
for ls in password:
    count = 0
    length=len(ls)
    if  length>=6 and length<=12:
        count+=1
    for i in ls:
        if i  in ['$','#','@']:
            count += 1
            break
    for i in ls:
        if ord('a')<=ord(i)<=ord('z'):
            count += 1
            break
    for i in ls:
        if ord('A')<=ord(i)<=ord('Z'):
            count += 1
            break
    for i in ls:
        if "0" <= i and i <= "9":
            count += 1
            break
    if count==5:
        sc.append(ls)
print(",".join(sc))

Question 19

Question:

You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string, age and score 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')]


Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.We use itemgetter to enable multiple sort keys.


Solutions:

In [ ]:

lst = []
while True:
    s = input().split(",")
    if not s[0]:  # breaks for blank input
        break
    lst.append(tuple(s))

lst.sort(
    key=lambda x: (x[0], x[1], x[2])
)  # here key is defined by lambda and the data is sorted by element priority 0>1>2 in accending order
print(lst)

sort函数的key 可以指定。

Question 20

Question:

Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.

 我的答案:

class divided:
    def __init__(self):
        print("shiyishi")
    def by_seven(self,n):
        for i in range(n+1):
            if i%7==0:
                yield i
dd=divided()
generator=dd.by_seven(int(input()))
for i in generator:
    print(i)

Question 21

Question:

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

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.Here distance indicates to euclidean distance.Import math module to use sqrt function.


Solutions:

import math

x, y = 0, 0
while True:
    s = input().split()
    if not s:
        break
    if s[0] == "UP":  # s[0] indicates command
        x -= int(s[1])  # s[1] indicates unit of move
    if s[0] == "DOWN":
        x += int(s[1])
    if s[0] == "LEFT":
        y -= int(s[1])
    if s[0] == "RIGHT":
        y += int(s[1])
        # N**P means N^P
dist = round(
    math.sqrt(x ** 2 + y ** 2)
)  # euclidean distance = square root of (x^2+y^2) and rounding it to nearest integer
print(dist)

Question 22-25

搞清楚class怎么用的啊

Question 32

Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.

def printDict():
    dict = {i: i ** 2 for i in range(1, 21)}
    print(dict.keys())  # print keys of a dictionary


printDict()

字典内for循环,纸打印键cict.keys   只打印值dict.values

Question 39

tpl1 = tuple(i for i in tpl if i % 2 == 0)

tpl1 = tuple(
    filter(lambda x: x % 2 == 0, tpl)

两种过滤方法。

Question 45

Define a class named American which has a static method called printNationality.

class American:
    @staticmethod
    def printNationality():
        print("I am American")


american = American()
american.printNationality()  # this will not run if @staticmethod does not decorates the function.
# Because the class has no instance.

American.printNationality()  # this will run even though the @staticmethod
# does not decorate printNationality()

注释有点没看懂,运行也能运行啊!

Question 50

raise函数

链接:Python raise用法(超级详细,看了无师自通) (biancheng.net)

Question 53

熟悉正则表达式

Question 56

unicode 和encode

Question 61

斐波那契数列

def f(n):
    if n < 2:
        fibo[n] = n
        return fibo[n]
    fibo[n] = f(n - 1) + f(n - 2)
    return fibo[n]


n = int(input())
fibo = [0] * (n + 1)  # initialize a list of size (n+1)
f(n)  # call once and it will set value to fibo[0-n]
fibo = [str(i) for i in fibo]  # converting integer data to string type
ans = ",".join(fibo)  # joining all string element of fibo with ',' character
print(ans)

答案,先确定了数列的尺寸。这个之前没见过,可以学习一下。

fibo = [0] * (n + 1)  # initialize a list of size (n+1)

那么用append形式应该也能实现吧。

参考了知乎。

def fb(n):
    if n==1:
        return [1]
    elif n==2:
        return [1,1]
    fibs=[1,1]
    for i in range(2, n):
        fibs.append(fibs[-1] + fibs[-2])
    return fibs
n=int(input())
print(fb(n))

Question 63

yield生成器再复习一遍

python中yield的用法详解——最简单,最清晰的解释_冯爽朗的博客-CSDN博客_yieldhttps://blog.csdn.net/mieleizhi0522/article/details/82142856

Question 64

Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.

Example: If the following n is given as input to the program:

100

Then, the output of the program should be:

0,35,70

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

我的答案

def Gen(n):
    i = 0
    while i <=n:
        if i%5==0 and i%7==0:
            yield i
        i=i+1

values=[]
n=int(input())
for i in Gen(n):
    values.append(str(i))
print(",".join(values))

给的答案:

def generate(n):
    for i in range(n + 1):
        if (
            i % 35 == 0
        ):  # 5*7 = 35, if a number is divisible by a & b then it is also divisible by a*b
            yield i


n = int(input())
resp = [str(i) for i in generate(n)]
print(",".join(resp))

5和7 那直接对35取余

然后,列表内循环。突发奇想,那如果不要求生成器的话是不是for 和if 列表内循环就可以了试一下,可以的。

n=int(input())
ls=[str(i) for i in range(0,n+1) if i%35==0]
print(",".join(ls))

Question 65

Please write assert statements to verify that every number in the list [2,4,6,8] is even.

data = [2, 4, 5, 6]
for i in data:
    assert i % 2 == 0, "{} is not an even number".format(i)

assertPython3 assert(断言) | 菜鸟教程 (runoob.com)

Question 67

eDSA - 二进制搜索(Binary Search)_数据结构和算法|WIKI教程 (iowiki.com)

二进制搜索技术

Question 68

  • 在random.random()中,输出介于0&1之间,不接受任何输入参数
  • 而random.uniform()接受参数,您可以在其中提交随机数的范围。 a、b.
  • random.random()为您提供一个在[0.0, 1.0)范围内的随机浮点数(因此包括0.0,但不包括1.0,也被称为半开放范围)。
  • random.uniform(a, b)给你一个在[a, b]范围内的随机浮点数(取整可能会给你b)

Question 70-74

random库

详解Python中random库 - random的用法_秃秃兔不秃的博客-CSDN博客_python random库

Question 77

datetime库

【Python】datetime库详解 - 简书 (jianshu.com)

Question 80 

Please write a program to print the list after removing even numbers in [5,6,77,45,22,12,24].

第一个想法就是用ls.remove函数,但用了之后就发现有点问题。查阅了相关资料后,得知 

删除之后,remove函数并没有执行结束。而是将a数组中索引号大于删除元素索引号的所有元素依次前一位。

就是说如果两个偶函数连在一起,第一个删除了,第二个会补到前面,就没有遍历到第二个偶数。

如果还想用remove函数的话,可以利用浅拷贝,目前还不懂具体的意思。

我的答案如下:

ls=[5,6,77,45,22,12,24]
for i in ls[:]:
    if i%2==0:
        ls.remove(i)
print(ls)

参考答案用的是filter函数,也算了解。但是第一时间不会想到他,多记一记吧。

def isEven(n):
    return n % 2 != 0


li = [5, 6, 77, 45, 22, 12, 24]
lst = list(filter(isEven, li))
print(lst)
OR

li = [5, 6, 77, 45, 22, 12, 24]
lst = list(filter(lambda n: n % 2 != 0, li))
print(lst)

Question 82

By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].

我的答案:

li = [12, 24, 35, 70, 88, 120, 155]
ls=[]
for i in range(len(li)):
    if i%2!=0:
        ls.append(li[i])
print(ls)

参考答案:

li = [12, 24, 35, 70, 88, 120, 155]
li = [li[i] for i in range(len(li)) if i % 2 != 0]
print(li)

答案列表内循环,用过很多次了,注意积累。

Question 84

By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.

array = [[[0 for col in range(8)] for col in range(5)] for row in range(3)]
print array

Question87

With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.

list1 = [1, 3, 6, 78, 35, 55]
list2 = [12, 24, 35, 24, 88, 120, 155]
set1 = set(list1)
set2 = set(list2)
intersection = set1 & set2
print(intersection)
OR

list1 = [1, 3, 6, 78, 35, 55]
list2 = [12, 24, 35, 24, 88, 120, 155]
set1 = set(list1)
set2 = set(list2)
intersection = set.intersection(set1, set2)
print(intersection)

set函数 set.intersection 交集。

Question 88

With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.

 脑子里回想出set函数,但是是无须的,之前好像做过这种题,通过计数count

li = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
for i in li:
    if li.count(i) > 1:
        li.remove(i)
print(li)
OR

def removeDuplicate(li):
    seen = {}  # dictionary
    for item in li:
        if item not in seen:
            seen[item] = True
            yield item


li = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
ans = list(removeDuplicate(li))
print(ans)

第二种方法要注意一下。

Question 90

Please write a program which count and print the numbers of each character in a string input by console.

import string

s = input()
for letter in string.ascii_lowercase:
    cnt = s.count(letter)
    if cnt > 0:
        print("{},{}".format(letter, cnt))
OR

s = input()
for letter in range(ord("a"), ord("z") + 1):  # ord() gets the ascii value of a char
    letter = chr(letter)  # chr() gets the char of an ascii value
    cnt = s.count(letter)
    if cnt > 0:
        print("{},{}".format(letter, cnt))

 python中ascii_uppercase_Python之字符串操作_weixin_39703773的博客-CSDN博客

question 91

python 中的[:-1]和[::-1]_CodingALife的博客-CSDN博客_python

 Question 96

python textwrap模块_林边清泉1的博客-CSDN博客_python textwrap

 Question 97

You are given an integer, N. Your task is to print an alphabet rangoli of size N. (Rangoli is a form of Indian folk art based on creation of patterns.)

Different sizes of alphabet rangoli are shown below:

size=3

----c----

--c-b-c--

c-b-a-b-c

--c-b-c--

----c----

size=5

--------e--------

------e-d-e------

----e-d-c-d-e----

--e-d-c-b-c-d-e--

e-d-c-b-a-b-c-d-e

--e-d-c-b-c-d-e--

----e-d-c-d-e----

------e-d-e------

--------e--------

First print the half of the Rangoli in the given way and save each line in a list. Then print the list in reverse order to get the rest.


import string


def print_rangoli(size):
    n = size
    alph = string.ascii_lowercase
    width = 4 * n - 3

    ans = []
    for i in range(n):
        left = "-".join(alph[n - i - 1 : n])
        mid = left[-1:0:-1] + left
        final = mid.center(width, "-")
        ans.append(final)

    if len(ans) > 1:
        for i in ans[n - 2 :: -1]:
            ans.append(i)
    ans = "\n".join(ans)
    print(ans)


if __name__ == "__main__":
    n = int(input())
    print_rangoli(n)

Question 98

Python-标准库calendar的使用_玉米丛里吃过亏的博客-CSDN博客_calendar python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值