python限制输入数字个数_使用python创建一个基数为12的计算器,在不同的数字上具有不同的限制...

I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits.

Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,"A","B"]

The limits must be:

First digit: limit "B"

Second digit: limit 4

Third digit: limit "B"

(The idea would be that it follows the hourly System limits but in base 12 so for example in base 12 there are 50 seconds in a minute)

That means you would count like this:[1,2,3,4,5,6,7,8,9,A,B,10,11,...48,49,4A,4B,100,101,...14B,200,201,...B4B,1000,1001..]

So I made the following code

import string

digs = string.digits + string.ascii_uppercase

def converter(number):

#split number in figures

figures = [int(i,12) for i in str(number)]

#invert oder of figures (lowest count first)

figures = figures[::-1]

result = 0

#loop over all figures

for i in range(len(figures)):

#add the contirbution of the i-th figure

result += figures[i]*12**i

return result

def int2base(x):

if x < 0:

sign = -1

elif x == 0:

return digs[0]

else:sign = 1

x *= sign

digits = []

while x:

digits.append(digs[int(x % 12)])

x = int(x / 12)

if sign < 0:

digits.append('-')

digits.reverse()

return ''.join(digits)

def calculator (entry1, operation, entry2):

value1=float(converter(entry1))

value2=float(converter(entry2))

if operation == "suma" or "+":

resultvalue=value1+value2

else:

print("operación no encontrada, porfavor ingrese +,-,")

result=int2base(resultvalue)

return result

print(calculator(input("Ingrese primer valor"), input("ingrese operación"), input("Ingrese segundo valor")))

The thing is that I dont know how to establish the limits to the different digits

If someone could help me I would be extreamly greatful

解决方案

You can define two converters:

class Base12Convert:

d = {hex(te)[2:].upper():te for te in range(0,12)}

d.update({val:key for key,val in d.items()})

d["-"] = "-"

@staticmethod

def text_to_int(text):

"""Converts a base-12 text into an int."""

if not isinstance(text,str):

raise ValueError(

f"Only strings allowed: '{text}' of type '{type(text)}' is invalid")

t = text.strip().upper()

if any (x not in Base12Convert.d for x in t):

raise ValueError(

f"Only [-0123456789abAB] allowed in string: '{t}' is invalid")

if "-" in t.lstrip("-"):

raise ValueError(f"Sign '-' only allowed in front. '{t}' is invalid")

# easy way

return int(t,12)

# self-calculated way

# return sum(Base12Convert.d[num]*12**idx for idx,num in enumerate(t[::-1]))

@staticmethod

def int_to_text(num):

"""Converts an int into a base-12 string."""

sign = ""

if not isinstance(num,int):

raise ValueError(

f"Only integer as input allowed: '{num} of type {type(num)}' is invalid")

if num < 0:

sign = "-"

num *= -1

# get highest possible number

p = 1

while p < num:

p *= 12

# create string

rv = [sign]

while True:

p /= 12

div = num // p

num -= div*p

rv.append(Base12Convert.d[div])

if p == 1:

break

return ''.join(rv)

Then you can use them to convert what you want:

text = "14:54:31" # some time

# convert each int of the time into base12 - join with | again

base12 = '|'.join(Base12Convert.int_to_text (int(t)) for t in text.split(":"))

# split base12 at |, convert to int, make str from int and join with | again

base10 = '|'.join(map(str,(Base12Convert.text_to_int (b12) for b12 in base12.split("|"))))

# print all 3

print(text,base12,base10,sep="\n")

Output:

14:54:31

12|46|27

14|54|31

and enforce whatever restrictions you have on your "digits" using normal ints. You should split up your "digits" of a clock ... 14b (203 in base 10) does not make sense, 1:4b might if you mean 1:59 hours/minutes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用 tkinter 制作的简易计算器,可以检验输入数据是否为纯数字: ```python import tkinter as tk class Calculator: def __init__(self): self.window = tk.Tk() self.window.title("简易计算器") self.window.geometry("300x150") self.label1 = tk.Label(self.window, text="请输入第一个数字:") self.label1.pack() self.entry1 = tk.Entry(self.window) self.entry1.pack() self.label2 = tk.Label(self.window, text="请输入第二个数字:") self.label2.pack() self.entry2 = tk.Entry(self.window) self.entry2.pack() self.label3 = tk.Label(self.window, text="请选择运算符(+、-、*、/):") self.label3.pack() self.entry3 = tk.Entry(self.window) self.entry3.pack() self.button = tk.Button(self.window, text="计算", command=self.calculate) self.button.pack() self.result = tk.Label(self.window, text="") self.result.pack() self.window.mainloop() def calculate(self): try: num1 = float(self.entry1.get()) num2 = float(self.entry2.get()) operator = self.entry3.get() if operator == '+': result = num1 + num2 elif operator == '-': result = num1 - num2 elif operator == '*': result = num1 * num2 elif operator == '/': result = num1 / num2 else: self.result.config(text="输入的运算符不正确!") return self.result.config(text="结果为:" + str(result)) except ValueError: self.result.config(text="输入的数据不是纯数字,请重新输入!") if __name__ == '__main__': Calculator() ``` 这个计算器使用了 tkinter 库创建窗口界面,包括三个输入框、一个计算按钮和一个结果显示标签。当用户点击计算按钮时,程序会尝试将输入的数据转换为浮点数,如果输入的数据不是纯数字,就会抛出 `ValueError` 异常,然后程序会在结果显示标签中提示用户重新输入。如果输入的数据是纯数字,就会执行相应的计算并在结果显示标签中输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值