def digui(n):
if n == 1:
return 0
elif n < 1:
return 1
else:
if n % 2 == 0:
return digui(n / 2)
else:
return 1
while True:
print(digui(int(input())))
#include <iostream>
#include <string>
using namespace std;
double digui(int n) {
double s = 1;
if (n > 1) {
if (n % 2 != 0) {
s = 1.0 / n + digui(n - 1);
}
else{
s = -1.0 / n+ digui(n - 1);
}
}
return s;
}
int main() {
int n;
while (cin>>n) {
printf("%.6f\n", digui(n));
}
return 0;
}
python递归会栈溢出
while True:
t=int(input())
for i in range(t):
n,k=map(int,input().split())
print(2**(n-k))
找规律
from itertools import *
elemt=[1,2,3,4,5,6,7,8,9]
for arr in permutations(elemt):
if 3*(1000*arr[0]+100*arr[1]+10*arr[2]+arr[3])==10000*arr[4]+1000*arr[5]+100*arr[6]+10*arr[7]+arr[8]:
print(str(1000*arr[0]+100*arr[1]+10*arr[2]+arr[3])+"/"+str(10000*arr[4]+1000*arr[5]+100*arr[6]+10*arr[7]+arr[8]))
思路:使用python的全排列permutations函数,也可使用递归算法解决
exp = []
res = []
def digui(n, m):
if n < 1 or m < 1:
return 0
if n == 1 or m == 1:
return 1
if n < m:
return digui(n, n)
if n == m:
return digui(n, m - 1) + 1
return digui(n, m - 1) + digui(n - m, m)
while True:
n = int(input())
if n >= len(exp):
exp.extend([0] * (n - len(exp) + 1))
res.extend([0] * (n - len(res) + 1))
if res[n] == 0:
res[n] = digui(n, n)
print(res[n])
def digui(arr, left, right):
if left == right:
print(''.join(arr))
else:
for i in range(left, right + 1):
arr[left], arr[i] = arr[i], arr[left]
digui(arr, left + 1, right)
arr[left], arr[i] = arr[i], arr[left]
while True:
n = int(input())
arr = [chr(ord('a') + i) for i in range(n)]
digui(arr, 0, n - 1)
print()
from bisect import *
case = 0
while True:
case += 1
n, m, k = map(int, input().split())
exp = sorted(list(map(int, input().split())))
w = [[0, 0] for i in range(m + 1)]
s = [[0] * n for i in range(2)]
w[0][0] = 1
for i in range(m):
w[i][1], w[i + 1][0] = map(int, input().split())
w[i + 1][0] += 1
for i in range(m):
s[1][bisect_left(exp, w[i][0])] += 1
s[0][bisect_right(exp, w[i][1]) - 1] -= 1
flag = 0
ans = 0
for i in range(n):
flag += s[1][i]
if flag >= k:
ans += 1
flag += s[0][i]
if flag == k:
ans += 1
print('Case ' + str(case) + ': ' + str(ans))
一直50%,时间会暴
n = int(input())
exp = input().split()
ind = []
for j in range(len(exp)):
if exp[j] != '?':
ind.append(j)
q = int(input())
for i in range(q):
res = int(input()) - 1
if exp[res] != '?':
print(exp[res])
else:
if res > max(ind):
print('right of ' * (res - ind[-1]) + exp[ind[-1]])
if res < min(ind):
print('left of ' * (ind[0] - res) + exp[ind[0]])
for j in range(len(ind) - 1):
if ind[j + 1] > res > ind[j]:
if res == (ind[j + 1] + ind[j]) / 2:
print('middle of ' + exp[ind[j]] + ' and ' + exp[ind[j + 1]])
if res - ind[j] < ind[j + 1] - res:
print('right of ' * (res - ind[j]) + exp[ind[j]])
if res - ind[j] > ind[j + 1] - res:
print('left of ' * (ind[j + 1] - res) + exp[ind[j + 1]])
简单的字符串处理和判断