Python 基础算法

约数

import os
import sys

# 请在此输入您的代码
se = set()
for i in range(1,int(1200000**0.5)+1):
  if 1200000%i==0:
    se.add(i)
    se.add(1200000//i)
print(len(se))

合数

sum = 0
for i in range(3,2021):
  for j in range(2,i):
    if i%j == 0:
      sum += 1
      break
print(sum)

矩形切割

wide = 2019
high = 324
count = 0 # 计数
while wide != high:
    wide = wide - high
    if wide < high:
        wide, high= high, wide # wide, high交换
    count += 1
print(count + 1)

字符出现次数

#最多
st = input()
letters = list(set(st))
letters.sort() # 保证按顺序输出
letter_number = []
for letter in letters:
    letter_number.append(st.count(letter))
# 找到最大的 计数 数字
max_number = max(letter_number)
# 找到最大计数数字对应的index
max_index = []
for i in range(0, len(letter_number)):
    if letter_number[i] == max_number:
        max_index.append(i)
# 输出结果
string = ''
for i in max_index:
    string += str(letters[i])
print(string)

出现次数最多元素

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

找最大或最小

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]

字典排序

from collections import OrderedDict

d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
    print(key, d[key])

foo 1 
bar 2 
spam 3
grok 4

四舍五入

>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254
>>>
>>> a = 1627731
>>> round(a, -1)
1627730
>>> round(a, -2)
1627700
>>> round(a, -3)
1628000
>>>
>>> x = 1.23456
>>> format(x, '0.2f')
'1.23'
>>> format(x, '0.3f')
'1.235'
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'
>>>

真分数

已知 S 是一个小于 11 的循环小数,请计算与 S 相等的最简真分数是多少。

例如 0.3333⋯0.3333⋯ 等于 1331 ,0.1666⋯0.1666⋯ 等于 1661 。

输入描述

输入第一行包含两个整数 pq,表示 S 的循环节是小数点后第 p 位到第 q 位。

第二行包含一个 q 位数,代表 S 的小数部分前 q 位。

其中,1≤pq≤10。

输出描述

输出两个整数,用一个空格分隔,分别表示答案的分子和分母。

from fractions import Fraction
p, q = map(int, input().split())
s = int(input())
m = s - s//(10**(q-p+1))
n = 10**q-10**(p-1)
res = str(Fraction(m, n)).split('/')
print(res[0], res[1])
0%