Python——面试编程题

一、python----输出1-100之和的方法

  • 方法一: print(sum(range(1,101)))

  • 方法二:
    from functools import reduce
    print(reduce(lambda x, y: x+y, range(101)))

  • 方法三:
    t=0
    for i in range(101):
    t+=i
    print(t)

  • 方法四:
    print(sum([x for x in range(101)]))

二、有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数

  • 方法一
#!/usr/bin/python
# -*- coding: UTF-8 -*-
count=0
for x in range(1,5):
  for y in range(1,5):
    for z in range(1,5):
      if (x != y) and (y != z) and (z != x):
        count+=1
        print(x, y, z)
print ("total count is :%d" %(count))

最终运行结果为:24

三、从字符串中找出 出现次数最多的 字母和 对应出现的个数

  • 方法一
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str='fhgdkgkjkdfg'
a={}
for i in str:
    if syr.count(i)>1:
        a[i]=str.count(i)
print(a)
max_count=max(a.values())
print(max_count)

最终输出结果:
{'f': 2, 'k': 3, 'd': 2, 'g': 3}
3
  • 方法二
s="aabbccddxxxxffff"
count ={}
for i in set(s):
    count[i]=s.count(i)
print(count)
max_value=max(count.values())
print(max_value)
for k,v in count.items():
    if v==max_value:
        print(k,v)

最终输出结果:
{'x': 4, 'f': 4, 'a': 2, 'c': 2, 'd': 2, 'b': 2}
x 4
f 4
  • 方法三
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from collections import Counter

List='fhgdkgkjkdfg'
word_counts = Counter(List)
# 出现频率最高的3个单词
top_three = word_counts.most_common(1)
print(top_three)

最终输出结果:
[('k', 3)]

四、输入三个整数x,y,z,请把这三个数由小到大输出

  • 方法一
#!/usr/bin/python
# -*- coding: UTF-8 -*-

l = []
for i in range(3):
    x = int(input('integer:
'))
    l.append(x)
l.sort()
print (l)

五、list中查找出来第一个不重复的元素

  • 方法一
List=[1,2,3,4,1,2,3,4,5,6]
for i in List:
         if List.count(i)==1:
                   print(i)
                   break
最终输出结果为:5

六、python实现100以内偶数之和

  • 方法一
a = 1
sum = 0
while a <= 100:
    if a % 2 != 0:
        sum += a
    a += 1
print(sum)

七、如何取出两个列表中相同或不同的元素

  • 方法一
list1 = [1,2,3]
list2 = [3,4,5]
list = []

for i in list1:
    if i not in list2:
        list.append(i)
for i in list2:
    if i not in list1:
        list.append(i)
print(list)

最终输出结果:
[1,2,4,5]

print ([i for i in list1 if i in list2])
最终输出结果:
[3]
原文地址:https://www.cnblogs.com/hghua/p/13293506.html