繁体   English   中英

如何在字符串中添加数字

[英]How to add numbers in a string

我是 Python 新手,我有一个作业来验证信用卡号。 我完成了前两个条件,但我坚持 #3 和 #4 条件。 任何帮助表示赞赏

状况:

  1. 第一个数字必须是 4.- done
  2. 第四位数字必须比第五位数字大一位; 请记住,这些用破折号分隔,因为格式是####-####-####.-done
  3. 所有数字的总和必须能被 4 整除 - 需要帮助
  4. 如果您将前两位数字视为两位数,将第七位和第八位数字视为两位数,则它们的总和必须为 100.- 需要帮助
def verify(number) : # do not change this line!

  # write your code here so that it verifies the card number
  #condtion 1  
  if number[0] != '4':
    return "violates rule #1"

  #condition 2
  if int(number[3]) != (int(number[5]) + 1) :
    return  "violates rule #2"

  #condition 3
  for i in number:
    if i >= '0' and i !='-':

  # be sure to indent your code!

  return True # modify this line as needed

input = "4037-6000-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
# do not remove this line!

预期产出:

● "5000-0000-0000": violates rule #1
● "4000-0000-0000": passes rule #1, violates rule #2
● "4007-6000-0000": passes rules #1-2, violates rule #3
● "4037-6000-0000": passes rules #1-3, violates rule #4
● “4094-3460-2754”: passes all rules

对于规则 3,您需要对所有数字求和并检查除以 4 的余数是否为零:

  #condition 3
  s = 0
  for i in number:
    if i != '-':
      s += int(i)
  if s % 4 != 0:
    return "violates rule #3"

对于规则 4,您可以获得子字符串的 int 总和:

if (int(number[0:2]) + int(number[7:8])) != 100:
    return "violates rule #4"

完整代码:

def verify(number) : # do not change this line!

  # write your code here so that it verifies the card number
  #condtion 1  
  if number[0] != '4':
    return "violates rule #1"

  #condition 2
  if int(number[3]) != (int(number[5]) + 1) :
    return  "violates rule #2"

  #condition 3
  s = 0
  for i in number:
    if i != '-':
      s += int(i)
  if s % 4 != 0:
    return "violates rule #3"

  if (int(number[0:2]) + int(number[7:9])) != 100:
    return "violates rule #4"

  # be sure to indent your code!
  return True # modify this line as needed

input = "4037-6000-0000" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output of the function
# do not remove this line!

对于条件 #3

Python 中的字符串是可迭代的,这意味着您可以在for循环中传递它们。 循环中的每个元素都是字符串中的一个字符。 所以如果你做了

for char in "4094-3460-2754":
    print(char)

你会得到:

4
0
9
4
-
3
4
etc.

使用它,您可以计算输入中每​​个数字的总和并检查它是否可以被 4 整除。需要注意的两件事,您需要首先将字符转换为整数(使用int )。 你不能做

"4" + "0"

但是你可以做

int("4") + int("0")

您还需要使用if从总和中排除“-”。

其次,我们使用模 ( % ) 检查两个数字在 Python 中是否可整除。 结果是余数,如果余数为 0,则第一个参数可被第二个参数整除。

16 % 4 == 0 # divisible by 4
21 % 4 == 1 # not divisible by 4

对于条件 #4

除了可迭代之外,Python 中的字符串还可以通过索引访问(从 0 开始)

"4094-3460-2754"[0] == "4"
"4094-3460-2754"[1] == "0"
"4094-3460-2754"[2] == "9"
"4094-3460-2754"[0:1] == "40"
"4094-3460-2754"[1:2] == "09"

因此,您可以访问多个字符并将它们视为整数:

int("4094-3460-2754"[0:1]) == 40

现在您可以将它们加在一起,看看它们是否等于 100。

所有数字之和必须能被 4 整除。

您可以使用条件语句进行检查,例如:

if sum_of_nums % 4 != 0:
   print("Violates rule 3!")

这会检查除以 4 时是否有余数,如果没有余数,它将被平均除,并且表达式将等于 0。 如果它不均分,它将不等于 0!

如果将前两位数视为两位数,将第七位和第八位视为两位数,则它们的总和必须为 100。

在这里,您可以像引用列表一样引用字符串的字符。 如果输入始终保持一致,您可以对引用进行硬编码,将它们更改为整数,然后将它们加在一起并使用条件语句检查它们

first_num = input[0]+input[1]
first_num = int(first_num) #now an int

second_num = input[6]+input[7]
second_num = int(second_num)

if first_num + second_num != 100:
   print("Violates rule 4!")

我宁愿去掉破折号-从数量第一,这样它可以很容易地工作着。 您也可以在不删除它的情况下进行操作。

# split it into parts separated by dashes
# consider 4094-3460-2754
no_dashes = number.split('-')

print(no_dashes) # ['4094', '3460', '2754']

# combine the numbers without dashes
no_dashes = ''.join(no_dashes)

print(no_dashes) # 409434602754

# convert it into a list of integers so that it is more easier to work with
number = [int(x) for x in no_dashes]

print(number) # [4, 0, 9, 4, 3, 4, 6, 0, 2, 7, 5, 4]

您可以在此处阅读有关split()join()信息

现在,正如您所提到的,第一个条件很简单,您可以简单地检查第一个数字是否为 4。

# 1st condition
if number[0] != 4:
    return 'Violates #1'

第二个条件也很简单:

# 2nd condition
# 4th digit is a[3] and 5th digit is a[4]
if number[3] != number[4] + 1:
    return 'Viloates #2'

对于第三个条件,您只需找到数字中每个数字的总和。 由于我们已经将数字转换为整数数组,因此使用sum()函数也很容易:

# 3rd condition
# Find the sum
num_sum = sum(number)

print(num_sum) # 48

# now check if the sum is divisible by 4
if num_sum % 4 != 0:
    return 'Violates #3'

现在,对于第四个条件,您需要将第 1 位和第 2 位数字视为两位数,并与第 7 位和第 8 位数字相同。 您可以将其转换为两位数,如下所示:

# 1st digit is number[0]
# 2nd digit is number[1]
# 7th digit is number[6]
# 8ty digit is number [7]

# convert 1st two digits into a two-digit number
x = number[0] * 10 + number[1]

# convert 7th and 8th digits into a two-digit number
y = number[6] * 10 + number[7]

现在您可以检查它们的总和是否为 100:

 if x + y != 100:
     return 'Violates #4'

因此,组合程序变为(合并了一些步骤):

def verify(number):
    number = [int(x) for x in ''.join(number.split('-'))]

    if number[0] != 4:
        return 'Violates #1'

    if number[3] != number[4] + 1:
        return 'Viloates #2'

    if sum(number) % 4 != 0:
        return 'Violates #3'

    if (number[0] * 10 + number[1] + number[6] * 10 + number[7]) != 100:
        return 'Violates #4'

    return True

但是上面的程序只会给出失败的第一个条件。 如果需要,您可以进一步修改它,如下所示:

def verify(number):
    failed = []
    number = [int(x) for x in ''.join(number.split('-'))]

    if number[0] != 4:
        failed += [1]

    if number[3] != number[4] + 1:
        failed += [2]

    if sum(number) % 4 != 0:
        failed += [3]

    if (number[0] * 10 + number[1] + number[6] * 10 + number[7]) != 100:
        failed += [4]

    res = 'Violates ' + (', '.join[str(x) for x in failed])

    return res if len(failed) != 0 else 'Passed'

print(verify('4094-3460-2754')) # Passed
print(verify('4037-6000-0000')) # Violates 4

您也可以再次修改它以显示通过的条件。 我把它留给你!

暂无
暂无

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

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