【面试题】python代码

1.99乘法表

复制代码
for i in range(1, 10):
    for j in range(1, i+1):
        print(f'{i}*{j}={i*j}', end=' ')
    print()

2.求1-100内能被7整除和包含7的数

复制代码
l = []
for i in range(7,101):
    if i % 7 == 0:
        l.append(i)
    elif i % 10 == 7:
        l.append(i)
print(l)

3. 判断回文数的三种方法

双指针(时间复杂度和空间复杂度均为O(n)
复制代码
    def func(num):
        if not num:
            return False
        else:
            s = str(num)
            start_index = 0
            end_index = len(s)-1
            while start_index <= end_index:
                if s[start_index] != s[end_index]:
                    return False
                start_index += 1
                end_index -= 1
            return True


    print(func('0'))
逆序(时间复杂度和空间复杂度均为O(n))
复制代码
def func(s):
    if not s:
        return False
    s = str(s)
    return s[::] == s[::-1]


print(func('srtrs'))

4.给定字符串,不论大小写,统计文中出现的字符个数。

时间复杂度O(n).
  • 因为需要for循环遍历一次所有的字符,n为字符串长度
空间复杂度O(n)
  • 因为最坏的情况下,所有字符不同

    def func(s):
    char_dic = {}
    if not s:
    return None
    else:
    s = s.lower()
    for i in s:
    if i not in char_dic:
    char_dic[i] = 1
    else:
    char_dic[i] += 1
    return char_dic

    if name == 'main':
    t = "12w234WooOuU"
    print(f'字符个数分别是:{func(t)}')

5.1返回列表中的多数元素,多数元素是指元素重复出现的次数大于列表长度的一半

时间复杂度O(n)
  • 因为所有操作主要是线性操作的。for循环遍历可迭代对象中所有元素
空间复杂度O(n)
  • 针对字段list_dic和element,最坏的情况是存储所有元素。

    def func(obj):
    list_dic = {}
    if not obj:
    return None
    elif len(obj) == 1:
    return obj[0]
    else:
    for i in obj:
    if i not in list_dic:
    list_dic[i] = 1
    else:
    list_dic[i] += 1
    element = [key for key, value in list_dic.items() if value > len(obj)/2]
    return element

5.2返回列表中的多数元素,多数元素是指元素重复出现的次数大于列表长度的一半

时间复杂度O(n)
  • for循环遍历所有元素

空间复杂度O(1)
  • candidate变量只会存储一个值

复制代码
  def func(obj):
      candidate = None
      count = 0
      # 找出可能的多数元素.由于多数元素的数量超过列表长度的一半,所以即使其他元素试图"抵消"它的计数,它最终也会成为候选。
      for num in obj:
          if not count:
              candidate = num
              count += 1
          elif num == candidate:
              count += 1
          else:
              count -= 1
      # 判断是否为真的多数元素
      count = 0
      for num in obj:
          if num == candidate:
              count += 1
      if count > len(obj)//2:
          return candidate
      else:
          return None


  if __name__ == '__main__':
      t = [3, 3, 4, 2, 4, 4, 2, 4, 4]
      print(f'多数元素是:{func(t)}')
相关推荐
程序员晚枫6 分钟前
Python 3.14正式发布!这5大新特性太炸裂了
python
先做个垃圾出来………16 分钟前
SortedList
python
这里有鱼汤18 分钟前
从DeepSeek到Kronos,3个原因告诉你:Kronos如何颠覆传统量化预测
后端·python·aigc
晓宜27 分钟前
Java25 新特性介绍
java·python·算法
深栈1 小时前
机器学习:决策树
人工智能·python·决策树·机器学习·sklearn
MediaTea1 小时前
Python:匿名函数 lambda
开发语言·python
hui函数1 小时前
Python全栈(基础篇)——Day07:后端内容(函数的参数+递归函数+实战演示+每日一题)
后端·python
MYX_3092 小时前
第二章 预备知识(线性代数)
python·线性代数·机器学习
zhangfeng11332 小时前
亲测可用,R语言 ggplot2 箱线图线条控制参数详解,箱线图离散数值控制
开发语言·python·r语言·生物信息
yzx9910132 小时前
国庆科技感祝福:Python 粒子国旗动画
开发语言·人工智能·python