1 功能:输入一个正整数,按照从小到大的顺序输出它的所有质因子(如180的质因子为2 2 3 3 5 )
最后一个数后面也要有空格
a, res = int(input()), []
for i in range(2, a // 2 + 1):
while a % i == 0:
a = a / i
res.append(i)
print(" ".join(map(str, res)) + " " if res else str(a) + " ")
2 功能:等差数列 2,5,8,11,14。。。。
输入:正整数N >0
输出:求等差数列前N项和
while True:
try:
n = int(input())
li = 0
for i in range(n):
an = 2+i*3
li += an
print(li)
except:
break
3 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.accept_stack = []
self.output_stack = []
def push(self, node):
# write code here
self.accept_stack.append(node)
def pop(self):
# return
if self.output_stack == []:
while self.accept_stack:
self.output_stack.append(self.accept_stack.pop())
return self.output_stack.pop()
if self.output_stack != []:
return self.output_stack.pop()
else:
return None
4 输入字符串(输出次数为N,字符串长度小于100),请按长度为8拆分每个字符串后输出到新的字符串数组,长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
while True:
try:
nums = int(input())
for i in range(nums):
str1 = input()
while len(str1) > 8:
print(str1[:8])
str1 = str1[8:]
print(str1+"0"*(8-len(str1)))
except:
break
5 将一个字符中所有出现的数字前后加上符号“”,其他字符保持不变
**关键点:最后两个数字间肯定是两个号,将其替换为空。**
while True:
try:
str1 = input()
if not str1:
break
str2 = ''
for i in str1:
if i.isdigit():
str2 = str2 + '*' + i + '*'
else:
str2 = str2 + i
print(str2.replace("**",""))
except:
break
6 输出第一个只出现一次的字符,如果不存在输出-1
这里使用了for 加else。以前没用过。。
while True:
try:
str1 = input()
for i in str1:
num = str1.count(i)
if num ==1:
print(i)
break
else:
print(-1)
except:
break