Python3求解字符串滤值与百元买百鸡算法
2018-07-05 11:45
197 查看
[本文出自天外归云的博客园]
第一题:给你一个字符串,打印出来前后没有空格,单词之间只有一个空格的字符串。
第二题:公鸡3元/只,母鸡4元/只,小鸡1元3只,给你money元一共多少种买法。
普通版解法如下:
def print_str(str, ret=[]): for i in range(len(str)): if i == 0: ret.append(str[i]) else: if str[i - 1] == " " and str[i] == " ": pass else: ret.append(str[i]) print("".join(ret).strip()) def calc(money, count=0): for i in range(1, money // 3 + 1): for j in range(1, (money - i * 3) // 4 + 1): count += 1 # print(f"公鸡{i}只 母鸡{j}只 小鸡{(money-i*3-j*4)*3}只") print(f"共有{count}种买法") return count if __name__ == '__main__': print_str(" I love Netease ") calc(100)
Pythonic版解法如下,一个算法一行:
print_str = lambda str: print("".join([str[i] if i == 0 else str[i] for i in range(len(str)) if not (str[i - 1] == " " and str[i] == " ")]).strip()) calc = lambda money, count=0: print(f"共有{len([(i,j,(money-i*3-j*4)*3) for i in range(1, money // 3 + 1) for j in range(1, (money - i * 3) // 4 + 1)])}种买法") if __name__ == '__main__': print_str(" I love Netease ") calc(100)
对于第一题,大师兄后来给我一个更简单的解法:
print(" ".join(" I love Netease ".strip().split()))
果然思路的优先级是更高的,一个好的思路有时候比好的实现优先级应该更高才对。
再来一个不用内置函数解决的方法:
str = " I love Netease " new_str = "" for i in range(len(str)): if len(new_str)==0: if str[i]==" ": pass else: new_str += str[i] else: if new_str[::-1][0] != " ": new_str += str[i] else: if str[i] != " ": new_str += str[i] if new_str[::-1][0] == " ": new_str = new_str[:-1] print(new_str)
相关文章推荐
- 一种快速求解最长回文字符串长度的算法
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- 面试宝典_Python.常规算法.0002.输出任意两个字符串中最长公共子串?
- 字符串相似度算法 递归与动态规划求解分析
- 求解最大回文字符串长度 — 三种算法
- 字符串相似度算法 递归与动态规划求解分析
- C语言求解最长公共子字符串问题及相关的算法分析
- Python练习(4):牛顿拉复生算法求解根
- Python实现的破解字符串找茬游戏算法示例
- python 数字 字符串 翻转算法
- python算法-字符串查找KMP算法
- Python实现的求解最大公约数算法示例
- python算法——字符串表达式的计算(转自:无限大地NLP_空木)
- 算法——动态规划算法求解字符串的编辑距离
- 蛮力法:设计算法求解字符串的模式匹配问题,并编程实现。
- 算法之美——求解 字符串间最短距离(动态规划)
- 算法:用Python判断两个版本号(字符串)大小
- python算法——字符串表达式的计算
- Python实现常见的回文字符串算法
- 最长公共子序列和最长子字符串_python_算法与数据结构