所以我需要做的是讀入一個數字并轉換每個數字。
- 奇數加 2
- 從偶數中減去 3(注意負數!)
- 零保持 0
輸入
14502
想要的輸出
31701
當前輸出
14504
以下是我現在所擁有的,我可以讀取 for 回圈中的每個數字,但我不知道如何逐個轉換它們。
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num 2)
else:
print(num - 3)
也沒有進口
uj5u.com熱心網友回復:
num = input("Enter a number:")
new_num = []
single_number = ''
for digit in num:
digit = int(digit)
if digit == 0:
new_num.append(digit)
elif (digit % 2)!=0:
digit = digit 2
new_num.append(digit)
elif (digit % 2)==0:
digit = digit-3
if digit>=0:
new_num.append(digit)
else:
digit = digit*(-1)
new_num.append(digit)
print(new_num)
# for single int instead of array
for digit in new_num:
digit = str(digit)
single_number = single_number digit
print(single_number)
new_number 是數字陣列 single_number 是您想要的最終數字。
uj5u.com熱心網友回復:
您的代碼在 for 回圈后是否缺少縮進?我知道這可能無法解決問題,但這是您的代碼的另一個問題還是只是堆疊上的格式問題?
num = int(input("Enter a number:"))
for digit in str(num):
print(digit)
if (num % 2)==0:
print(num 2)
else:
print(num - 3)
uj5u.com熱心網友回復:
num = int(input("Enter a number:"))
print(len(str(num)))
finaloutput = []
for i in range(len(str(num))):
digit = num%10
if digit%2==0:
if digit - 3 < 0:
digit = 0
else:
digit = digit - 3
else:
digit = digit 2
finaloutput.append(digit)
num = num //10
print(finaloutput)
string=""
for i in range(len(finaloutput)):
string = string str(finaloutput[i])
print(string[::-1])
可能會磨損很大,但可以完成作業。從偶數中減去 3,在賠率上加 2,然后注意零。
輸出:
Enter a number:14502
5
[0, 0, 7, 1, 3]
31700
我這樣說,如果偶數 sub 3 小于零,它就保持為零,這就是我的理解。您可以輕松修改代碼以滿足您的需要并根據您的任務或其他
uj5u.com熱心網友回復:
嘗試:
num = 9876543210
l = [int(c) for c in str(s)]
l = [min(c, 7) 2 if c % 2 else max(c, 4) - 3 if c != 0 else c for c in l]
out = int(''.join(str(c) for c in l))
輸出:
>>> out
9593715130
細節:
9 -> 9 (else 12)
8 -> 5 (-3)
7 -> 9 (else 10)
6 -> 3 (-3)
5 -> 7 ( 2)
4 -> 1 (-3)
3 -> 5 ( 2)
2 -> 1 (else -1)
1 -> 3 ( 2)
0 -> 0 (do nothing)
uj5u.com熱心網友回復:
基于您的解決方案的簡單實作。它只能處理整數。還有一種情況是你沒有指定的
- 當數字是9時該怎么辦?As
9 2 = 11和 11 不是數字,但很可能是您在演算法中想要的?
在這個實作中,9 變為 1。
def calc_on_digits(num: str):
result: str = ""
for digit in num:
digit = int(digit)
if digit == 0:
result = "0"
continue
if digit % 2 == 0:
# in case it get negative take the absolute value
digit = abs(digit - 3)
else:
digit = 2
# in case its 9 the result would be 11 -> make it one
digit = digit % 10
result = str(digit)
return result
# string in this implementation can only contain valid integer values
print(calc_on_digits("14502"))
uj5u.com熱心網友回復:
您不能從字串計算模數。此外,您必須執行每個數字的比較,而不是整數。
num = input("Enter a number:") # no need to cast to int just to transform back to str below
new_number = ""
for digit in num:
digit = int(digit)
print(digit)
if (digit % 2) = 0:
tmp = digit 2
if tmp >= 10:
tmp = 0
else:
tmp = digit - 3
if tmp < 0:
tmp = 0
new_number = str(tmp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445436.html
標籤:Python python-3.x
上一篇:使用python-binance時,heroku[regex._regex_core.error:badescape\datposition7]出錯
下一篇:根據位置在python中拆分陣列
