Python - 作业 - 将任意基数转换为任意基数

2024-02-03

我正在尝试编写一个程序,将任何基数中的数字转换为用户选择的另一个基数。到目前为止我的代码是这样的:

innitvar = float(raw_input("Please enter a number: "))
basevar = int(raw_input("Please enter the base that your number is in: "))
convertvar = int(raw_input("Please enter the base that you would like to convert to: "))

这些是我从用户那里获得的数据。初始数字、其初始基数以及用户想要转换到的基数。据我了解,我需要转换为基数 10,然后转换为用户指定的所需基数。

这就是我遇到困难的地方:我需要将初始数字中最左边的数字与其初始基数相乘,然后将下一个数字添加到右侧,然后重复,直到达到最右边的数字。我知道如何在纸上做到这一点,但我不知道如何将其放入 Python 代码中。我不确定如何乘以第一个数字,然后添加下一个数字,我也不知道如何让程序知道何时停止执行此操作。

我并不是要求为我编写程序,但我希望有人指出正确的方向。

谢谢你的时间!


这应该是您问题答案的前半部分。你能弄清楚如何转换为基础吗?

# Create a symbol-to-value table.
SY2VA = {'0': 0,
         '1': 1,
         '2': 2,
         '3': 3,
         '4': 4,
         '5': 5,
         '6': 6,
         '7': 7,
         '8': 8,
         '9': 9,
         'A': 10,
         'B': 11,
         'C': 12,
         'D': 13,
         'E': 14,
         'F': 15,
         'G': 16,
         'H': 17,
         'I': 18,
         'J': 19,
         'K': 20,
         'L': 21,
         'M': 22,
         'N': 23,
         'O': 24,
         'P': 25,
         'Q': 26,
         'R': 27,
         'S': 28,
         'T': 29,
         'U': 30,
         'V': 31,
         'W': 32,
         'X': 33,
         'Y': 34,
         'Z': 35,
         'a': 36,
         'b': 37,
         'c': 38,
         'd': 39,
         'e': 40,
         'f': 41,
         'g': 42,
         'h': 43,
         'i': 44,
         'j': 45,
         'k': 46,
         'l': 47,
         'm': 48,
         'n': 49,
         'o': 50,
         'p': 51,
         'q': 52,
         'r': 53,
         's': 54,
         't': 55,
         'u': 56,
         'v': 57,
         'w': 58,
         'x': 59,
         'y': 60,
         'z': 61,
         '!': 62,
         '"': 63,
         '#': 64,
         '$': 65,
         '%': 66,
         '&': 67,
         "'": 68,
         '(': 69,
         ')': 70,
         '*': 71,
         '+': 72,
         ',': 73,
         '-': 74,
         '.': 75,
         '/': 76,
         ':': 77,
         ';': 78,
         '<': 79,
         '=': 80,
         '>': 81,
         '?': 82,
         '@': 83,
         '[': 84,
         '\\': 85,
         ']': 86,
         '^': 87,
         '_': 88,
         '`': 89,
         '{': 90,
         '|': 91,
         '}': 92,
         '~': 93}

# Take a string and base to convert to.
# Allocate space to store your number.
# For each character in your string:
#     Ensure character is in your table.
#     Find the value of your character.
#     Ensure value is within your base.
#     Self-multiply your number with the base.
#     Self-add your number with the digit's value.
# Return the number.

def str2int(string, base):
    integer = 0
    for character in string:
        assert character in SY2VA, 'Found unknown character!'
        value = SY2VA[character]
        assert value < base, 'Found digit outside base!'
        integer *= base
        integer += value
    return integer

这是解决方案的后半部分。通过使用这两个函数,转换基数非常容易。

# Create a value-to-symbol table.
VA2SY = dict(map(reversed, SY2VA.items()))

# Take a integer and base to convert to.
# Create an array to store the digits in.
# While the integer is not zero:
#     Divide the integer by the base to:
#         (1) Find the "last" digit in your number (value).
#         (2) Store remaining number not "chopped" (integer).
#     Save the digit in your storage array.
# Return your joined digits after putting them in the right order.

def int2str(integer, base):
    array = []
    while integer:
        integer, value = divmod(integer, base)
        array.append(VA2SY[value])
    return ''.join(reversed(array))

将它们放在一起后,您应该得到下面的程序。请花点时间弄清楚!

innitvar = raw_input("Please enter a number: ")
basevar = int(raw_input("Please enter the base that your number is in: "))
convertvar = int(raw_input("Please enter the base that you would like to convert to: "))

# Create a symbol-to-value table.
SY2VA = {'0': 0,
         '1': 1,
         '2': 2,
         '3': 3,
         '4': 4,
         '5': 5,
         '6': 6,
         '7': 7,
         '8': 8,
         '9': 9,
         'A': 10,
         'B': 11,
         'C': 12,
         'D': 13,
         'E': 14,
         'F': 15,
         'G': 16,
         'H': 17,
         'I': 18,
         'J': 19,
         'K': 20,
         'L': 21,
         'M': 22,
         'N': 23,
         'O': 24,
         'P': 25,
         'Q': 26,
         'R': 27,
         'S': 28,
         'T': 29,
         'U': 30,
         'V': 31,
         'W': 32,
         'X': 33,
         'Y': 34,
         'Z': 35,
         'a': 36,
         'b': 37,
         'c': 38,
         'd': 39,
         'e': 40,
         'f': 41,
         'g': 42,
         'h': 43,
         'i': 44,
         'j': 45,
         'k': 46,
         'l': 47,
         'm': 48,
         'n': 49,
         'o': 50,
         'p': 51,
         'q': 52,
         'r': 53,
         's': 54,
         't': 55,
         'u': 56,
         'v': 57,
         'w': 58,
         'x': 59,
         'y': 60,
         'z': 61,
         '!': 62,
         '"': 63,
         '#': 64,
         '$': 65,
         '%': 66,
         '&': 67,
         "'": 68,
         '(': 69,
         ')': 70,
         '*': 71,
         '+': 72,
         ',': 73,
         '-': 74,
         '.': 75,
         '/': 76,
         ':': 77,
         ';': 78,
         '<': 79,
         '=': 80,
         '>': 81,
         '?': 82,
         '@': 83,
         '[': 84,
         '\\': 85,
         ']': 86,
         '^': 87,
         '_': 88,
         '`': 89,
         '{': 90,
         '|': 91,
         '}': 92,
         '~': 93}

# Take a string and base to convert to.
# Allocate space to store your number.
# For each character in your string:
#     Ensure character is in your table.
#     Find the value of your character.
#     Ensure value is within your base.
#     Self-multiply your number with the base.
#     Self-add your number with the digit's value.
# Return the number.

integer = 0
for character in innitvar:
    assert character in SY2VA, 'Found unknown character!'
    value = SY2VA[character]
    assert value < basevar, 'Found digit outside base!'
    integer *= basevar
    integer += value

# Create a value-to-symbol table.
VA2SY = dict(map(reversed, SY2VA.items()))

# Take a integer and base to convert to.
# Create an array to store the digits in.
# While the integer is not zero:
#     Divide the integer by the base to:
#         (1) Find the "last" digit in your number (value).
#         (2) Store remaining number not "chopped" (integer).
#     Save the digit in your storage array.
# Return your joined digits after putting them in the right order.

array = []
while integer:
    integer, value = divmod(integer, convertvar)
    array.append(VA2SY[value])
answer = ''.join(reversed(array))

# Display the results of the calculations.
print answer
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - 作业 - 将任意基数转换为任意基数 的相关文章

  • docker 容器中的“(pygame parachute)分段错误”

    尝试在 docker 容器中使用 pygame 时出现以下错误 我想从容器中获取显示 Fatal Python error pygame parachute Segmentation Fault 重现 Docker已安装 docker ru
  • 从内存地址创建python对象(使用gi.repository)

    有时我需要调用仅存在于 C 中的 gtk gobject 函数 但返回一个具有 python 包装器的对象 之前我使用过基于 ctypes 的解决方案 效果很好 现在我从 PyGtk import gtk 切换到 GObject intro
  • Python 不考虑 distutils.cfg

    我已经尝试了给出的所有内容 并且所有教程都指向相同的方向 即使用 mingw 作为 python 而不是 Visual C 中的编译器 我确实有 Visual C 和 mingw 当我想使用 pip 安装时 问题开始出现 它总是给Unabl
  • 使用 Boto3 超时的 AWS Lambda 函数

    我已经解决了我自己的问题 但无论如何我都会发布它 希望能节省其他人几个小时 我在 AWS 上有一个无服务器项目 使用 Python 将记录插入到 kinesis 队列中 但是 当我使用 boto3 client kinesis 或 put
  • Python Requests 库重定向新 url

    我一直在浏览 Python 请求文档 但看不到我想要实现的任何功能 在我的脚本中我设置allow redirects True 我想知道该页面是否已重定向到其他内容 新的 URL 是什么 例如 如果起始 URL 为 www google c
  • Scrapy 文件管道不下载文件

    我的任务是构建一个可以下载所有内容的网络爬虫 pdfs 在给定站点中 Spider 在本地计算机和抓取集线器上运行 由于某种原因 当我运行它时 它只下载一些但不是全部的 pdf 通过查看输出中的项目可以看出这一点JSON 我已经设定MEDI
  • Python3将模块从文件夹导入到另一个文件夹

    我的结构字典是 mainFolder folder1 init py file1 py file2 py folder2 init py file3 py file4 py setup py init py 我需要将 file4 py 从f
  • Python 内置对象的 __enter__() 和 __exit__() 在哪里定义?

    我读到每次使用 with 时都会调用该对象的 enter 和 exit 方法 我知道对于用户定义的对象 您可以自己定义这些方法 但我不明白这对于 打开 等内置对象 函数甚至测试用例是如何工作的 这段代码按预期工作 我假设它使用 exit 关
  • Python Selenium 打印另存为 PDF 等待文件名输入

    我正在尝试通过打印对话框将网站另存为 PDF 我的代码允许我另存为pdf 但要求我输入文件名 我不知道如何将文件名传递到弹出框 附上我的代码 import time from selenium import webdriver import
  • 使用 Tkinter 打开网页

    因此 我的应用程序需要能够打开其中的单个网页 并且它必须来自互联网并且未保存 特别是我想使用 Tkinter GUI 工具包 因为它是我最熟悉的工具包 最重要的是 我希望能够在窗口中生成事件 例如单击鼠标 但无需实际使用鼠标 有什么好的方法
  • 了解 Python 2.7 中的缩进错误

    在编写 python 代码时 我往往会遇到很多缩进错误 有时 当我删除并重写该行时 错误就会消失 有人可以为菜鸟提供 python 中 IndentationErrors 的高级解释吗 以下是我在玩 CheckIO 时收到的最近 inden
  • 无法通过 Android 应用程序访问我的笔记本电脑的本地主机

    因此 我在发布此内容之前做了一项研究 我发现的解决方案不起作用 更准确地说 连接到我的笔记本电脑的 IPv4192 168 XXX XXX 没用 连接到10 0 2 2 加上端口 不起作用 我需要测试使用 Django Rest 框架构建的
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • Python:导入模块一次然后与多个文件共享

    我有如下文件 file1 py file2 py file3 py 假设这三个都使用 lib7 py lib8 py lib9 py 目前 这三个文件中的每一个都有以下行 import lib7 import lib8 import lib
  • 获取多个同名请求参数

    我的问题是给定的代码 from flask import Flask request app Flask name app route def hello return str request values get param None a
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO
  • AWS 将 MQTT 消息存储到 DynamoDB

    我构建了一个定期发送 MQTT 消息的 python 脚本 这是发送到后端的 JSON 字符串 Id 1234 Ut 1488395951 Temp 22 86 Rh 48 24 在后端 我想将 MQTT 消息存储到 DynamoDB 表中
  • 检查 IP 地址是否在给定范围内

    我想检查一下是否有IP180 179 77 11位于特定范围之间 例如180 179 0 0 180 179 255 255 我编写了一个函数 它将每个 IP 八位字节与其他八位字节进行比较 def match mask IP min ip
  • Chrome 驱动程序和 Chromium 二进制文件无法在 aws lambda 上运行

    我陷入了一个问题 我需要在 AWS lambda 上做一些抓取工作 所以我按照下面提到的博客及其代码库作为起点 这非常有帮助 并且在运行时环境 Python 3 6 的 AWS lambda 上对我来说工作得很好 https manivan
  • 超过两个点的Python相对导入

    是否可以使用路径中包含两个以上点的模块引用 就像这个例子一样 Project structure sound init py codecs init py echo init py nix init py way1 py way2 py w

随机推荐

  • 如何将 JIRA 与 Selenium WebDriver 集成?

    如何将 JIRA 与 Selenium WebDriver 集成 实际上我想执行测试用例并报告 JIRA 中每个测试用例的通过 失败状态 你的问题很笼统 我的回答也很笼统 Jira 并不完全是一个 TCM 测试用例管理器 应用程序 尽管它肯
  • 如何使用 MongoDB 搜索文档中所有字段的单词或字符串?

    我们遇到的情况是 用户希望有一个 多功能框 来搜索文档中任何位置的单词 短语 MongoDB 是否能够执行此搜索 还是必须对每个字段进行显式搜索 你需要创建一个通配符文本索引 https docs mongodb org manual co
  • 相当于 PowerShell 中的 Bash 别名

    PowerShell 新手问题 我想在 PowerShell 中创建一个与此 Bash 别名完全相同的别名 alias django admin jy jython path to jython dev dist bin django ad
  • 使用一个字段创建 Ada 记录

    我定义了一个类型 type Foo is record bar Positive end record 我想创建一个返回记录实例的函数 function get foo return Foo is return 1 end get foo
  • 当为自动模拟设置自定义 AutoDataAttribute 时,告诉 AutoFixture 忽略所有递归结构的正确语法是什么?

    我让 xUnit Moq AutoFixture 成功地协同工作 以便我可以通过测试方法输入参数自动模拟对象 我创建了一个自定义 AutoMoqData 我在每次测试中使用的属性 这是该属性的代码 using System Linq usi
  • Android 谷歌加号登录按钮

    下列的谷歌签名按钮 https developers google com mobile android sign in 我在我的android设备上实现了它 单击该按钮时 它会显示一个弹出窗口 询问您的许可 了解您在 Google 上的身
  • 将图像上传到网络服务会导致图像损坏

    我正在尝试从 iPhone 将图像上传到网络服务 但即使文件已成功上传 也无法查看 jpg 它似乎已损坏 使用以下 c 代码可以成功上传文件并正常工作 var url http myurl co uk services service sv
  • 是否有类似于 XMLSpy 的带有网格视图的 XML 编辑器? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我已经测试了一些不同的 xml 编辑器 查看器 但似乎找不到任何具有与 XMLSpy 的网格视图相媲美的
  • 使用 Rails 3 输出格式化的 json

    我使用rails 3 0 3 javascript 自动完成需要这样的数据 query Li suggestions Liberia Libyan Arab Jamahiriya Liechtenstein Lithuania data L
  • Golang 嵌入结构类型

    我有这些类型 type Value interface type NamedValue struct Name string Value Value type ErrorValue struct NamedValue Error error
  • Kotlin 如何与 Java 和 JavaScript 互操作?

    Kotlin 网站指出 Kotlin 与 Java 100 具有互操作性 Kotlin 是 Java 的子集 超集吗 另外 文档指出 Kotlin 与 JavaScript 兼容 那么它是如何编译以支持两者的呢 Kotlin 是像 Xama
  • 内循环 Lambda

    我在 for 循环中有一个 lambda 其中循环变量参数在 lambda 中 当我运行它时 我期望输出数字 0 9 但由于它是 lambda 因此 x 不会立即求值 for int x 0 x lt n x vec push back t
  • 如何解决java.io.InvalidClassException:本地类不兼容:流classdesc serialVersionUID [重复]

    这个问题在这里已经有答案了 我在这么大的项目中有一个可序列化的类 编码时没有指定serialVersionUID 并将其作为blob保存在MySQL数据库中 我必须向此类添加一些字段 但是执行此操作后 我收到如下异常 IOException
  • 文本装饰:下划线与边框底部

    使用上有什么区别 text decoration underline and border bottom 哪个易于设计且跨浏览器兼容 当我们应该使用border bottom over text decoration underline 用
  • 使用 Lua 表 C API 创建一个简单的表

    我正在运行一个 MySQL 查询 它总是返回 4 行 row gt name row gt date row gt ip row gt custom 我想要实现的是根据上述结果创建一个简单的表 因此它看起来像 name result of
  • 如何将信号作为函数参数传递?

    因此 我希望创建我们自己的通用继承复选框类 该类将能够在其构造函数中接受一些值 并弹出一个以我们需要的方式完全连接到我们的模型的小部件 目前我们在我们的视野范围内做这样的事情 connect checkboxWidget QCheckbox
  • 如何在android中使用intent发送.text文件?

    我正在使用下面的代码发送邮件 并且我需要仅使用 gmail 发送 text 文件 我该怎么做 请问有人可以帮助我吗 Intent send new Intent Intent ACTION SENDTO String uriText mai
  • 需要为 Yesod 路径定义哪些类型类?

    在我的应用程序中 我的数据模型有几个使用整数或字符串作为某些标识符的不同实例 为了安全起见 我将这些标识符包装到新类型声明中 如下所示 newtype DocId DocId Integer newtype GroupName GroupN
  • 在 Pixel 2 和 Pixel 2 XL 上接收 UDP 广播数据包

    我正在开发一个从 Wi Fi 摄像头接收 UDP 广播数据包的应用程序 在我发现 Google Pixel 2 Pixel 2 XL 接收 UDP 广播包有问题之前一直都很好 为了找出原因 我做了2个测试应用程序 一个是UPD广播发送器 h
  • Python - 作业 - 将任意基数转换为任意基数

    我正在尝试编写一个程序 将任何基数中的数字转换为用户选择的另一个基数 到目前为止我的代码是这样的 innitvar float raw input Please enter a number basevar int raw input Pl