简体   繁体   English

带有元组的非常简单的函数(python)

[英]REALLY simple functions with tuples (python)

I know this is really easy but I can't understand how to code at all.我知道这真的很容易,但我根本不明白如何编码。 So I need to create two functions (if you can only help me with one that's fine):所以我需要创建两个函数(如果你只能帮我一个就好了):

Function a which receives a positive integer and transforms it into a tuple, like this:函数 a 接收一个正整数并将其转换为一个元组,如下所示:

>>>a(34500)
(3, 4, 5, 0, 0)
>>>a(3.5)
ValueError: a: error

And function b which receives a tuple and transforms it into an integer, like this:函数 b 接收一个元组并将其转换为一个整数,如下所示:

>>>b((3, 4, 0, 0, 4))
34004
>>>b((2, ’a’, 5))
ValueError: b: error

I haven't learned much yet, only functions, while and for cycles, tuples, raise and isinstance(for the error message?), and probably some other things.我还没有学到很多东西,只有函数、while 和 for 循环、元组、raise 和 isinstance(用于错误消息?),以及其他一些东西。 I've tried looking for answers but they all used things I haven't learned.我试图寻找答案,但他们都使用了我没有学到的东西。

def to_tuple(input_number):
    # check if input number is int or not
    if isinstance(input_number,(int)):
        # convert number to string
        to_string = str(input_number)
        # finally convert string to
        # list of numbers followed by converting the list to tuple
        tuple_output = tuple(map(int,to_string))
        return tuple_output
    # if not int return empty tuple
    # well coz nobody likes useful but ugly python tracebacks
    else:
        return ()

# lets see example
number = 3450
print to_tuple(number)
(3, 4, 5, 0)

number = 353984
print to_tuple(number)
(3, 5, 3, 9, 8, 4)

number = 2.6
print to_tuple(number)
()

If you like this example I'd post answer for the second part如果你喜欢这个例子,我会发布第二部分的答案

The comments already state what you can do: Convert the int to str by doing (I know this does not work for floats, here you can show some further effort:))评论已经说明了您可以做什么:通过执行将 int 转换为 str (我知道这不适用于浮点数,在这里您可以展示一些进一步的努力:))

for c in str(integerVariable):
    print c

The other way around is even more simple.反过来说就更简单了。

''.join(tupleVariable)

Try this尝试这个

def a(n):
result = []

while n > 0:
    result.append(n%10)
    n=n//10

return tuple(reversed(result))

for question 2, try doing the same thing in reverse ie multiplying each number by 1, 10, 100 and adding them up.对于问题 2,尝试反过来做同样的事情,即将每个数字乘以 1、10、100 并将它们相加。

also don't forget error checking code.也不要忘记错误检查代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM