Python Forum
Adding spaces to digits
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding spaces to digits
#1
"""I am new to python and programming in general, currently learning at an institution, which is why def is not even seen in my code. I am very lost right now, was tasked this:

Let us assume that we have the following credit card number issued by a
bank: (You can assume that user enter the credit card numbers separated by
hyphens)

2323-2005-7766-3554

For each of the tokens, you reverse the numbers (we remove the hyphen too)
3232 5002 6677 4553

For every token, you multiply by 2 every digit in the even position, i.e.
positions 2 and 4 (left to right for each token). We have the following new
four tokens:

3434 5004 612714 41056

I am stucked at the last part mentioned above. I am only able to get every single set of number separated by spaces.

Here's my code:
"""
print ("Welcome to DEF credit card company")
print()


ccnum_with_hyphens = input("Enter a credit card:")
ccnum_without_hyphens = ccnum_with_hyphens.replace("-", " ")

  
reversed_ccnum = ""

for i in range(0, len(ccnum_without_hyphens), 5):
    reversed_ccnum += ccnum_without_hyphens[i+3] + ccnum_without_hyphens[i+2]+ ccnum_without_hyphens[i+1] + ccnum_without_hyphens[i] + " "

print(reversed_ccnum)


reversed_ccnum = reversed_ccnum.replace(" ", "")
print(reversed_ccnum)
# Convert the string to a list of characters
chars = list(reversed_ccnum)

# Iterate over the characters and multiply every digit at even positions by 2
for i in range(1, len(chars)-2, 4):
    chars[i] = str(int(chars[i]) * 2)
for i in range(3, len(chars), 4):
    chars[i] = str(int(chars[i]) * 2)
    
modified_ccnum = ' '.join(chars)
print(modified_ccnum)
"""
I am stuck here. Can someone kindly help me out? Cry Thank you!
"""
Reply
#2
There are a few different ways to do this and your code can be made much more succinct.

This (for example) removes the hyphens and reverses each 'token'. The resulting tokens are replaced, within the same list object.

ccn = "2323-2005-7766-3554"
ccn_lst = ccn.split("-")

for index, token in enumerate(ccn_lst):
    ccn_lst[index] = token[::-1]
Have a look into string slicing to see how this works and to complete the rest of your project.

to add: you could also look into the third perimeter of the range() function, which is commonly called a 'step': range(start, stop, step).
deadkill02 likes this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
@deadkill02

For the rest of this task, I would create a 'new tokens' list object, then nest two for loops; one to loop through the existing tokens, and the other to loop though the numbers (which will be string objects, don't forget) within the tokens:

for token in ccn_lst:

for index, item in enumerate(token):

In the first loop, create a 'new token' string: new_token = ""
In the second loop, have an if/else branch the checks the index number in range(1, 4, 2) and build up the 'new_token' string, from that branch.
Do you know why I have (1, 4, 2)?

When that's done, .append() the 'new token' to the 'new tokens' list, at which point, the second loop is finished and the first loop will grab the next token in the 'ccn_lst'.

It is in fact, far more work to describe this as I have, than it is to write the code, but give it a shot and if you get stuck, simply post back with what you have and I'll guide you some more.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#4
Positions are 1, 2, 3, 4. The corresponding indices are 0, 1, 2, 3. If the index is odd, you should multiply the corresponding digit by 2.
for i, digit in enumerate(chars):
    if i is odd:
        chars[i] = str(int(chars[i]) * 2)
How can you test if the index is odd. Read up on python functions and operands that return a remainder.
Reply
#5
I broke a bone in my foot 10 days ago, so I have to sit around for another 2 weeks with my leg in plaster. I have time!

"""
1. reverse each 4 digit number
2. multiply each second number x2
"""
num = '2323-2005-7766-3554'
nums = num.split('-')

# a function to reverse the numbers
def rev(num):
    newnum = ''
    # set -1 as low range or you won't get 0
    for i in range(len(num)-1,-1, -1):
        newnum = newnum + num[i]
    return newnum

# step 1 reverse all nums
for j in range(len(nums)):
    nums[j] = rev(nums[j])


# step 2 multiply every second number by 2 and save the new number in result[]
result = []
for n in nums:
    # [n[0], n[2] remain the same
    mylist = [n[0], n[2]]
    print(f'mylist is {mylist}')
    for i in range(1, len(n) +1, 2):        
        print(f'number is {n[i]}')
        num = int(n[i]) * 2
        print(f'{n[i]} x 2 = {num}')
        mylist.insert(i, str(num))
        print(f'mylist is {mylist}')
    newstring = ''.join(mylist)
    print(f'newstring is {newstring}')
    result.append(newstring)

# step 3 join result[]      
newCCnum = '-'.join(result) # '3434-5004-612714-41056'
Reply
#6
I'm sure that there is (or was) a ruling that complete answers to home work questions, should not be posted. Has this changed and if so, why?

Giving the answer without first encouraging a OP to work it out, is going to be of limited help to a OP, as well as being "bad form", IMHO.

@deadkill02

There are now too many people involved in this, pulling you in different direction, which could be counterproductive, so I'm going to side-line, wish you the best in your coding, and encourage you to find your own way to complete this project. For coders, such as the ones that have posted here, this is a simple task; for you maybe not so much, but (as I said, from the start) there's more than one way to do this, and now you can see that.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020