s=''
def Suan(a):
if(a):
Suan(int(a/2))
global s
s+=str(a%2)
def Suan2(a):
if(a==0):
return ""
else:
return Suan2(a//2)+str(a%2)
a=int(input())
Suan(a)
print(s)
print(Suan2(a))
def HeNeiTa(n,x,y,z):
if(n>0):
HeNeiTa(n-1,x,z,y);
print("把{}从{}拿下来,放到{}上".format(n,x,z))
HeNeiTa(n - 1, y, x, z);
n=int(input("请输入有多少个需要移动:"))
HeNeiTa(n,'X','Y','Z')
字典代码:
1.
dict={'<':'less than','==':'equal'}
print('Here is the original dict:')
for x in sorted(dict):
print(f'Operator {x} means {dict[x]}.')
dict['>']='greater than'
print(" ")
print("The dict was changed to:")
for x in sorted(dict):
print(f'Operator {x} means {dict[x]}.')
2.
survey_list=['Niumei','Niu Ke Le','GURR','LOLO']
result_dict={'Niumei':'Nowcoder','GURR':'HUAWEI'}
for element in survey_list:
if element in result_dict.keys():
print(f'Hi, {element}! Thank you for participating in our graduation survey!')
else:
print(f'Hi, {element}! Could you take part in our graduation survey?')
3.
my_dict_1 = {"name": "Niuniu", "Student ID": 1}
my_dict_2 = {"name": "Niumei", "Student ID": 2}
my_dict_3 = {"name": "Niu Ke Le", "Student ID": 3}
dict_list = []
dict_list.append(my_dict_1)
dict_list.append(my_dict_2)
dict_list.append(my_dict_3)
for i in dict_list:
print("{}'s student id is {}.".format(i["name"], i["Student ID"]))
4.
cities_dict = {
'Beijing': {'Capital': 'China'},
'Moscow': {'Capital': 'Russia'},
'Paris': {'Capital': 'France'}
}
for city, country in sorted(cities_dict.items()):
print(f'{city} is the capital of {country["Capital"]}!')
for city in sorted(cities_dict):
print(f'{city} is the capital of {cities_dict[city]["Capital"]}!')
5.
result_dict = {
'Allen': ['red', 'blue', 'yellow'],
'Tom': ['green', 'white', 'blue'],
'Andy': ['black', 'pink']
}
for i in sorted(result_dict):
print("%s's favorite colors are:" % i)
for j in result_dict[i]:
print(j)
for m, n in sorted(result_dict.items()):
print("%s's favorite colors are:" % m)
for o in n:
print(o)
6.
name=input().split()
langu=input().split()
# dict1=zip(name,langu)
# print(dict(dict1))
dict1={}
for i in range(len(name)):
dict1[name[i]]=langu[i]
print(dict1)
7.
d = {'a': ['apple', 'abandon', 'ant'],
'b': ['banana', 'bee', 'become'],
'c': ['cat', 'come'],
'd': 'down'}
word = input()
print(' '.join(d[word]))
8.
my_dict={'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
letter=input()
word=input()
my_dict[letter]=word
print(my_dict)
my_dict = {'a': ['apple', 'abandon', 'ant'],
'b': ['banana', 'bee', 'become'],
'c': ['cat', 'come'],
'd': 'down'}
new_key = input()
new_valu = input()
keys = my_dict.keys()
if new_key in keys:
my_dict[new_key].append(new_valu)
else:
my_dict[new_key] = new_valu
print(my_dict)
9.
word = list(input())
dictionary ={}
for i in word:
value = word.count(i)
dictionary[i] = value
print(dictionary)
n = input()
dict_list = dict()
for i in n :
if i in dict_list:
dict_list[i] += 1
else:
dict_list[i] = 1
print(dict_list)
内置函数代码:
1.
l1=list(map(int,input().split()))
print(max(l1))
print(min(l1))
2.
l1=list(map(int,input().split()))
print(sum(l1))
3.
a=eval(input())
print(abs(a))
4.
a=input()
print(ord(a))
5.
a=eval(input())
print(hex(a))
6.
a=eval(input())
print(bin(a))
7.
a,b=map(int,input().split())
print(pow(a,b))
print(pow(b,a))
8.
l1=list(map(int,input().split()))
print(l1.count(0))
9.
l1=input().split()
print(l1.index('NiuNiu'))
10.
a=input()
print(a.isalpha())
print(a.isdigit())
print(a.isspace())
11.
a=input()
print(a.find('NiuNiu'))
12.
a=input()
print(a.count('Niu'))
13.
a=input().split()
print(a)
14.
la=[]
a=input()
while(a!='0'):
la.append(a)
a=input()
s=' '.join(la)
print(s)
15.
s=input()
print(s.replace('a*','ab'))
16.
s=eval(input())
print(round(s,2))
17.
x=eval(input())
print(x)
18.
a=set(input().split())
print(sorted(a))
面向对象代码:
1.
def f(x, y):
return x - y
x = int(input())
y = int(input())
print(f(x, y))
print(f(y, x))
2.
def habit_count(n):
ncount = 0
if n == 1:
ncount = 2
elif n == 2:
ncount = 3
else:
ncount = habit_count(n - 1) + habit_count(n - 2)
return ncount
n_habit = int(input())
print(habit_count(n_habit))
3.
import math
def area(r):
s=4*math.pi*r*r
return s
list_a = [1, 2, 4, 9, 10, 13]
for i in list_a:
print(round(area(i), 2))
4.
class Student(object):
def __init__(self, name, number, grade, level):
self.name = name
self.number = number
self.grade = grade
self.level = level
self.times = len(level.split(" "))
def p(self):
return "{}'s student number is {}, and his grade is {}. He submitted {} assignments, each with a grade of {}".format(
self.name, self.number, self.grade, self.times, self.level
)
name = input()
number = input()
grade = int(input())
level = input()
student = Student(name, number, grade, level)
print(student.p())
5.
class Employee:
def __init__(self, name, salary) -> None:
self.name = name
self.salary = salary
def printclass(self):
try:
print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")
except AttributeError:#AttributeError:属性不存在的异常
print("Error! No age")
# 数据输入:姓名,薪水,年龄
name = input()
salary = int(input())
age = int(input())
# 先使用name和salary 创建实例e
e = Employee(name, salary)
e.printclass()
# 直接在实例e上添加属性年龄age, #动态给对象加属性,此属性只属于该实例。
e.age = age
e.printclass()
6.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def printclass(self):
try:
print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")
except:
print("Error! No age")
name = input()
salary = input()
age = input()
e = Employee(name, salary)
if print(hasattr(e, "age")):
e.printclass()
else:
setattr(e, "age", age)
e.printclass()
# 1.hasattr(object,name)函数:判断一个对象里面是否有name属性或者name方法,返回bool值,有name属性(方法)返回True,否则返回False
# 2.setattr(object,name,values)函数:给对象的属性赋值,若属性不存在,先创建再赋值
# 3.getattr(object, name[,default])函数:获取对象object的属性或者方法,如果存在则打印出来,如果不存在打印默认值,默认值可选。注意:如果返回的是对象的方法,则打印结果是:方法的内存地址,如果需要运行这个方法,可以在后面添加括号()
7.
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
#返回一个对象的描述信息,用于定义对象的字符串表示形式。当你使用 print 函数或 str 函数将对象转换为字符串时,Python 会调用该对象的 __str__ 方法。
def __str__(self):
return f"({self.x}, {self.y})"
# 加法运算 重载==重新载入运算
def __add__(self, other):
return Coordinate(self.x + other.x, self.y + other.y)
#__add__ 是一个特殊方法,用于定义对象的加法操作。当你使用 + 运算符对两个对象进行加法操作时,Python 会调用该对象的 __add__ 方法。
x1, y1 = list(map(int, input().split()))
x2, y2 = list(map(int, input().split()))
c1 = Coordinate(x1, y1)
c2 = Coordinate(x2, y2)
print(c1 + c2)
c3 = Coordinate.__add__(c1,c2)
#这种写法相当于直接调用类方法,c1和c2相当于传递给方法的参数,不太适用
c3 = c1.__add__(c2)
#这种写法通过实例c1调用add方法,c2是传递给方法的参数。是常见的调用方式,遵循面向对象编程的常规模式。在这种情况下,add方法使用self来引用c1实例的属性和方法。因为在通过实例调用方法时,python会自动将实例传递给方法的第一个参数。
print(c3.__str__())
正则表达式代码:
正则表达式是一种强大的文本处理工具,用于匹配字符串中的字符组合。它被广泛应用于各种编程语言和工具中,如Perl、Python、JavaScript等,用于搜索、替换和处理文本数据。正则表达式通过定义一个模式,可以匹配一系列符合该模式的字符串。
正则表达式全解析+常用示例_(2)试求所有的仅由终结符组成的活前缀所对应的正则表达式;-优快云博客
1.
s = input()
s1 = 'https://www'
countNum = 0
for i in range(0,len(s1),1):
if s1[i] == s[i]:
countNum += 1
else:
break;
print("(0, "+str(countNum)+')')
2.
# 清理电话簿
# 1.使用findall()函数找出所有数字后拼接成新的字符串
import re
while True:
try:
print(''.join(re.findall(r'\d',input())))
#:使用正则表达式 r'\d' 查找输入字符串中的所有数字,并返回一个包含所有匹配项的列表。
except:
break
# 2.使用re.sub()替换函数
import re
while True:
try:
s = input()
print(re.sub('[a-z]+|[A-Z]+|-','',s))
except:
break
3.
import re
phone = input()
matchobj = re.match(r"[0-9|-]*", phone)
#[0-9|-]:匹配一个数字或连字符。*:匹配前面的字符零次或多次。
if matchobj:
print(matchobj.group())
else:
print("No match found")
#group() 方法:用于获取匹配的结果。
# 如果输入的字符串以数字或连字符开头,并且后面的部分也是由数字或连字符组成,那么 matchobj.group() 将返回整个输入字符串。
# 如果输入的字符串包含不符合模式的字符,那么 matchobj.group() 将返回从开头到第一个不符合模式的字符之间的部分。
# 如果输入的字符串为空或以不符合模式的字符开头,matchobj 将为 None,调用 group() 方法会引发 AttributeError。