python核心编程学习笔记-2016-07-26-01-习题6-13
来源:互联网 发布:c语言wait函数头文件 编辑:程序博客网 时间:2024/06/07 11:15
习题6-13
将复数字符串转变成复数,由例子'-1.23e+4-5.67j',要考虑用科学计数法表示数字的情况。
代码如下:
#-*-coding: utf-8-*-import stringnum = string.digitsvalid = num + '.' + '+' + '-' + 'e' + 'E' # 复数字符串中可能出现的字符,包括以科学计数法表示的数字def getInput(): while True: str = raw_input("Please enter a complex number: ") new_str = ''.join(str.split()) # 需要去掉空格,不然后面截得的实部和虚部会含有空格,而float(' +3.4')会报错。 is_valid = True if new_str[-1] not in ['J', 'j']: # 复数字符串的最后一位必定是j或J is_valid = False else: for i in range(-2, -len(new_str), -1): if new_str[i] == '+' or new_str[i] == '-': if new_str[i - 1] != 'e' and new_str[i - 1] != 'E': # +或-的前面有两种可能性,一是例如'3+4j',二是例如'3e+4 - 5j',需要排除'e+'这种情况。 str_real = new_str[-len(new_str):i] str_imag = new_str[i:-1] break try: real = float(str_real) except ValueError, e: is_valid = False else: try: imag = float(str_imag) except ValueError, e: is_valid = False if is_valid: return new_str else: print "Your enter is invalid." def atoc(new_str): real = '' imag = '' for i in range(-2, -len(new_str), -1): if new_str[i] == '+' or new_str[i] == '-': if new_str[i - 1] != 'e' and new_str[i - 1] != 'E': str_real = new_str[-len(new_str):i] str_imag = new_str[i:-1] real = float(str_real) imag = float(str_imag) break return complex(real, imag)if __name__ == "__main__": str = getInput() print atoc(str)
0 0
- python核心编程学习笔记-2016-07-26-01-习题6-13
- python核心编程学习笔记-2016-07-20-01-习题3-13
- python核心编程学习笔记-2016-07-23-01-习题5-6
- python核心编程学习笔记-2016-07-28-01-习题6-16
- python核心编程学习笔记-2016-07-30-01-习题7-5
- python核心编程学习笔记-2016-08-23-01-习题16-13
- python核心编程学习笔记-2016-08-28-01-习题18-4和习题18-9
- python核心编程学习笔记-2016-08-03-01-习题9-9
- python核心编程学习笔记-2016-08-05-01-习题9-19
- python核心编程学习笔记-2016-08-28-02-习题18-6
- python核心编程学习笔记-2016-07-18-01-print
- python核心编程学习笔记-2016-08-26-01-文件传输
- 《Python核心编程》第13章 习题
- 《Python核心编程》第6章 习题
- 《Python核心编程》第6章 习题
- python核心编程学习笔记-2016-07-19-02-__name__
- python核心编程学习笔记-2016-08-13-03-授权
- python核心编程学习笔记【2016-10-13】
- Elasticsearch(入门篇)——Query DSL与查询行为
- HDU 4284-状压DP+最短路
- 2016暑假集训7.26 顺序表(例题为之前字符串题)
- Codeforces Round #201 (Div. 1) C. Number Transformation II(思路)
- lua的string库
- python核心编程学习笔记-2016-07-26-01-习题6-13
- android开发性能优化经验总结二
- 虚拟化技术—— 介绍
- poj 2506 Tiling
- 计算机网络基础总结
- EJB系列(二)---开发
- 再看冒泡和选择排序以及折半查找(二分查找)
- easyui 源码分析(easyloader.js)(2)
- Eclipse插件开发学习笔记【1】---Eclipse环境搭建