基础算法题(python)——重新排序得到 2 的幂,旋转链表,分类颜色,根据字符出现频率排序

八、重新排序得到 2 的幂

题目:

从正整数 N 开始,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。

示例 1:
输入:1
输出:true

示例 2:
输入:10
输出:false

示例 3:
输入:16
输出:true

代码:

import itertools

N = eval(input("输入一个数:"))

# 判断是否为2的幂
def judge(num):
    # 位与运算
    result = num & (num-1)
    return result

# 将数字转化为列表
list_num = list(str(N))
# 数字进行任意组合
term = list(itertools.permutations(list_num, len(list_num)))
flag = "false"
# 判断每个组合成的数字是否为2的幂
for item in term: 
    # 判断首个数字不为0
    if item[0] != "0":
        # 组合为新的排列形式数字
        new_str = ""
        for i in item:
            new_str += i
        TorF = judge(int(new_str))
        if TorF == 0:
            flag = "true"
            break
# 输出结果
print(flag)               

九、旋转链表

题目:

实例:

代码:

十、分类颜色

题目:

代码:

# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 10:43:37 2018

@author: haotian

题目:分类颜色
要求:不能用排序函数
"""

color_list = eval(input("输入颜色混乱的数组:"))

red , white, blue = [], [], []

for color in color_list:
    if color == 0:
        red.append(color)
    elif color == 1:
        white.append(color)
    else:
        blue.append(color)

print("排序后的数组为:")
print(red + white + blue)

十一、根据字符出现频率排序

题目:

代码:

# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 10:51:50 2018

@author: haotian

题目:根据字符出现频率排序
"""
# 输入字符串
strings = input("输入字符串:")

# 将字符串转为一个列表
string_list = []
for i in range(0, len(strings)):
    string_list.append(strings[i])

# 将字符串列表按照 值:出现次数 存为字典
d = {}
for i in set(string_list):
    d[i] = string_list.count(i)

# 对字典按照出现次数进行排序
ls = sorted(d.items(), key=lambda item:item[1])

# 对字典进行拼接输出最终结果字符串
last_string = ""
for i in range(0, len(ls)):
    last_string += (ls[len(ls)-1-i][0] * ls[len(ls)-1-i][1])
    
print("排序后结果:" + last_string)
 

发布了33 篇原创文章 · 获赞 43 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_31967985/article/details/81093960